# Examples

## Finance

### Fixed-rate Mortgage

I'm looking to buy a house. Here in Seattle, you can buy a condo for about `$250,000`

, or you can splurge to get a house on a bit of land for `$350,000`

. Let's splurge...

```
price = $350,000
down payment = 20% * price => $70,000
finance amount
= price - down payment
=> $280,000
interest rate = 3.7%/year
term = 30year
n = term * 12/year => 360
r = interest rate / (12/year) => 0.0031
monthly payment
= r/(1 - (1 + r)^(-n)) * finance amount
=> $1,288.7924
```

Looks like if I don't mind dropping `$70,000`

, I can get a nice place for about `$1,300`

a month.

Try editing the price and interest rate to see how much your dream home will cost.

### Budget

Here is my budget, how is yours different? Just change any of the numbers to match your life.

```
expenses = rent + car + office + other
rent = $750 + utils
utils = $200
car = $400
office = $1,300 + parking
parking = $120
other = $1200
expenses => $3,970
daily expenses
= expenses/30day
=> $132.3333/day
```

Now let's look at my income. I have a job and do a little gambling on the side:

```
income = (job + gambling) * (100% - income tax rate)
income tax rate = 33%
job = $100,000/12 => $8,333.3333
gambling = -$100
daily income
= income / 30day
=> $183.8778/day
```

Let's see how profitable each day has been:

```
daily profit
= daily income - daily expenses
=> $51.5444/day
```

Wow, I'm making money every day. Great! I wonder how long until I'm a millionaire?

```
time til millionaire
= $1,000,000/(daily profit * 365day/years)
=> 53.1527years
```

That's too long... What if I made more money?

```
time til millionaire(job = $8,000) => 62.1253years
time til millionaire(job = $16,000) => 12.2986years
time til millionaire(job = $32,000) => 4.7229years
time til millionaire(job = $64,000) => 2.116years
time til millionaire(job =$128,000) => 1.0057years
```

So, if I just make `$128,000`

per month, I will be a millionaire in just over a year! Time to start looking!

## Mathematics

### Pythagorean Theorem

The square of the hypotenuse of a triangle is equal to the sum of the squares of its legs.

```
a^2 + b^2 = c^2
```

Let's imagine that to get to work I have to drive `5miles`

north then `8miles`

east to get to work. How far is it as the crow flies?

```
c(a=5miles, b=8miles) => 9.434miles
```

### Arithmetic using Logarithms

Back before Calca, scientists and engineers had to do math using long hand. This is easy enough, but gets quite tedious. Thankfully we have computers now.

These engineers and scientists used a mathematical identity to make their jobs easier.

```
log(x*y, b) => log(x, b) + log(y, b)
log(x/y, b) => log(x, b) - log(y, b)
```

When they needed to multiply large complicated numbers, they were smart and kept those numbers in the logarithm form. Then they could simply add those numbers. The same trick worked for multiplication.

Let's look at an example. I want to find volume of the earth.

```
volume = 4/3*pi * r^3 => 4.1888r^3
r = 6,378,100
```

I need to multiple a lot of numbers, `4.18888`

and `r`

three times to find the volume. Instead we'll use logarithms and addition:

```
log c = log10(4/3*pi) => 0.6221
log r = log10(r) => 6.8047
log volume = log c + log r + log r + log r => 21.0362
10^log volume => 10.8683e20
volume => 10.8683e20
```

We were able to calculate `4/3*pi * r^3`

using just three additions. Pretty impressive I think!

### Solving linear equations using matrices

You can use matrices to solve a set of linear equations. Let's solve the following set of equations:

```
12x + 13y = 163
-2x + 100y = 688
```

We can solve for x and y by taking the constants on the left hand side and putting them in a matrix:

```
a = [12, 13; -2, 100]
```

and by putting the right hand side into a vector:

```
b = [163; 688]
```

Now we can convert our two equations into one and solve for x and y:

```
a * xy = b
xy => [6; 7]
```

Great! We now know `x = 6`

and `y = 7`

. We can even solve other linear equations:

```
xy(a=[1,2;3,4],b=[3;2]) => [-4; 3.5]
```

### Imaginary Numbers

Imaginary numbers are written as numbers multiplied by the imaginary unit `i`

.

```
5i
```

They are defined by the property that their squares are negative.

```
i^2 => -1
(5i)^2 => -25
sqrt(-1) => i
sqrt(-16) => 4i
sqrt(i) => 0.7071i + 0.7071
```

A **complex number** is an imaginary number added to another number:

```
b*i + a => b*i + a
5i - 1 => 5i - 1
-8i + 100 => -8i + 100
```

The complex conjugate negates the imaginary part of a complex number:

```
conj(5i - 1) => -5i - 1
conj(-8i + 100) => 8i + 100
```

You can extract the real and imaginary parts of a complex number using these very clever functions:

```
im(z) = 1/2i*(z - conj(z))
re(z) = 1/2*(z + conj(z))
im(-8i + 100) => -8
re(-8i + 100) => 100
```

## Information Theory

### Normal Distribution

The normal distribution gives the probability of a value `x`

occurring based on an average of all possible values called the `mean`

and a standard deviation `stddev`

of those values around that mean.

```
f(x) = 1/(stddev*sqrt(2*pi)) *
e^-((x-mean)^2/(2*stddev^2))
f(90, mean=100, stddev=10) => 0.0242
f(100, mean=100, stddev=10) => 0.0399
f(110, mean=100, stddev=10) => 0.0242
```

Let's look at some data to model. Here is my population in Seattle of people's ages (not really):

```
ages = [28, 45, 30, 40, 34, 30, 24]
n = sum(1, ages) => 7
mean = reduce(x + y, ages)/n => 33
stddev = sqrt(sum((a - mean)^2, ages)/n) => 6.7401
```

This means that `68%`

(one standard deviation) of people in Seattle are `33`

years old, plus or minus about `7`

years.

So what's the probability on an 18 year old living in Seattle?

```
population of seattle = 620,778 #googled
population given age = f(age) * population of seattle
population given age(18) => 3,088.0792
population given age(30) => 33,278.3747
```

Hmm, there are only `3,000`

18 year olds in Seattle - given my completely made up statistics above.

Why not modify those stats to match your home town?

### Shannon's Entropy

Entropy of a variable is a measure of the uncertainty of its value.

```
H(X) = -sum(p(x)*ln(p(x)), x=X)
```

This function takes a set of values or *messages* `X`

and produces the entropy of that set. To do this, it needs to know the probability of a message being in `X`

; this information is provided by the `p`

function.

The `p`

function must sum to `1`

for all the possible messages.

```
data = [A, B, C]
# Maximum entropy
pmax(x) = 1/3
sum(pmax, data) => 1
# NOT a good value of p because it sums to 0.75
pbad(x) = 1/4
sum(pbad, data) => 0.75
# Here is a modeled p function
pmodel(x) = if x == B then 0.6 else 0.2
sum(pmodel, data) => 1
```

We can now calculate the entropy of the data given the various probabilities of messages:

```
H(data, p = pmax) => 1.0986
H(data, p = pmodel) => 0.9657
```

When the messages are most uncertain - they each have the same probability - the entropy is maxed out at about `1.1`

. If we make the number `11`

most probable - `60%`

likelihood - then the entropy is only `0.95`

.

If we designate one of the messages as very likely to occur then the entropy should go down since there is very little uncertainty.

```
# Here is a modeled p function
pcertain(x) = if x == B then 0.9999 else 0.00005
sum(pcertain, data) => 1
H(data, p = pcertain) => 0.00149
```

Yep! H is very small now because `9,999`

out of `10,000`

messages will be `B`

- the world is certain!

## Health

### Target Heart Rate

The Karvonen Method is a way to calculate your target heart rate given the intensity of a work out. It depends upon your resting and maximum heart rates.

```
HR =
((Maximum HR - Resting HR) * Intensity)
+ Resting HR
Resting HR = 60bpm
Maximum HR = 200bpm
HR(Intensity = 80%) => 172bpm
```

If we know our heart rate already, we can calculate the intensity of the workout:

```
Intensity(HR = 120bpm) => 0.4286
```

## Physics

### Projectile Motion

Here is a classic equation for the motion of an object that is influenced by a uniform acceleration a, an initial velocity v0 and an initial position x0.

```
x(t) = 1/2 * a * t^2 + v0*t + x0
```

We're going to define the parameters of this model using units. That way we can make sure we're calculating everything correctly.

```
a = -9.8m/s/s
v0 = 100m/s
x0 = 490m
x => -4.9m*t^2/s^2 + 100m*t/s + 490m
```

Let's see what it looks like over a 30 second period:

```
x(1s) => 585.1m
x(10s) => 1000m
x(20s) => 530m
x(30s) => -920m
```

We need to make sure to specify the time with the units `s`

, otherwise we'll get a bad result:

```
x(1) => -4.9m/s^2 + 100m/s + 490m
```

### Units of Motion and Power

The velocity of an object is measured in meters `m`

per second `s`

.

```
velocity units = m / s
```

Its acceleration is the change in velocity over time:

```
accel units = velocity units / s
```

Isaac Newton tells us that all objects have a constant velocity (`a = 0`

) unless acted upon by a **force**. This force is measured by multiplying the mass of the moving object (in kg) by the acceleration caused by the force. It's measured in, appropriately enough, Newtons:

```
N = kg * accel units => kg*m/s^2
```

If we apply a force over a distance (imagine pushing your car), then are said to have done **work** (so long as the object accelerates in the direction we're pushing!). Work is measured in Joules:

```
J = N*m => kg*m^2/s^2
```

There is another quantity called **energy** that is measured in Joules. Energy is *the capacity for doing work*. In every day speech, we use energy instead of work since work has a lot of real world connotations that are best left ignored.

The change in energy over time is called **power** and is measured in Watts.

```
W = J/s => kg*m^2/s^3
```

Voltage and Current:

```
V = J/C => kg*m^2/(s^2*C)
A = C/s => C/s
V*A => kg*m^2/s^3
```

### Gravity

Let's start with Newton's Law that force is proportional to acceleration:

```
force = mass * accel
```

When I'm standing on earth, it is constantly accelerating me so that I stay glued to the ground. That acceleration is called **standard gravity**.

```
g = 9.80665 m/s^2
```

Now some personal info:

```
weight = 165lbs
kg per pound = 0.453592kg/lbs #googled
weight in kg = weight * kg per pound
=> 74.84268kg
```

With that out of the way, we can measure the force that the earth exerts on me:

```
earth force = force(weight in kg, g)
=> 733.955968kg*m/s^2
```

That was fun! We now know that the earth exerts `734 N`

of force on me. All the time. But we love her anyway.

Change the values in blue above to find out how much she exerts on you!

#### Newton's Universal Gravitation

Previously, we used the fact that the earth constantly accelerates us at the rate `g`

to keep us on the ground.

```
g => 9.80665m/s^2
```

But where did this number come from? We can use Newton's Law of Universal Gravitation to calculate it. Here's that law:

```
force of gravity = G*(mass * other mass)/dist^2
```

It states that the force due to gravity is proportional to the masses of two objects and *inversely* proportional to the squared distance between them.

The constant of proportionality is `G`

- a very different number from the `g`

we knew before. It is:

```
G = 6.67384e-11 m^3/kg/s^2 #gravitational constant
```

Let's now use the law to calculate that value of `g = 9.8m/s^2`

from above. We'll do it by using the mass of the earth and the ma

```
mass of earth = 5.972e24 kg #googled
radius of earth = 6,378,100 m #googled
earth gravity = force of gravity(
other mass = mass of earth,
dist = radius of earth)
=> 9.79745m*mass/s^2
```

And there it is! Well it's not quite `9.81m/s`

but that's just because our input numbers for earth's mass and radius weren't exactly what is used to calculate standard gravity, but it's darn close!

How close is it? Well let's give it our mass and see how close to `734 N`

it gets:

```
earth gravity(mass = weight in kg)
=> 733.267222m*kg/s^2
```

So close! It calculated `733 N`

.

Why not try changing the numbers to see how much gravity would affect you if you lived on mars?

## Electronics

### Ohm's law

Ohm's law is fundamental to understanding electronics. It states that the current `i`

through a conductor is proportional to the voltage `v`

across it.

```
v = i * r
i => v/r
```

We can use it directly to measure that voltage:

```
v(i = 2A, r = 100Ohm) => 200A*Ohm
```

Oops, it would be better if we told Calca about Amperes:

```
A = V/Ohm
v(i = 2A, r = 100Ohm) => 200V
```

We can use Ohm's Law to solve for any of three variables using any of the other two:

```
v(i = 2A, r = 100Ohm) => 200V
i(v = 200V, r = 100Ohm) => 2V/Ohm
r(v = 200V, i = 2A) => 100Ohm
```

### Capacitors

The current through a capacitor is proportional to the rate of change of the voltage across it:

```
ic(t) = C*der(v(t), t)
```

We can see the common property that the capacitor causes a 90 degree phase shift in current when its voltage is AC:

```
ic(t, v=sin(t)) => C*cos(t)
```

## Logic Programming

### Digital Adders

Now you can define logic functions, here is an implementation of exclusive or:

```
xor(a, b) = if a then !b else b
xor(0, 0) => 0
xor(1, 0) => 1
xor(0, 1) => 1
xor(1, 1) => 0
half adder(a, b) = [xor(a,b), a && b]
half adder(0, 0) => [0, 0]
half adder(0, 1) => [1, 0]
half adder(1, 0) => [1, 0]
half adder(1, 1) => [0, 1]
```

Those are pretty cool, huh? We can use them to create a full adder.

```
adder(a, b, c) =
let ab = half adder(a, b) in
let abc = half adder(ab[0], c) in
[abc[0], abc[1] || ab[1]]
adder(0, 0, 0) => [0, 0]
adder(0, 0, 1) => [1, 0]
adder(0, 1, 0) => [1, 0]
adder(0, 1, 1) => [0, 1]
adder(1, 0, 0) => [1, 0]
adder(1, 0, 1) => [0, 1]
adder(1, 1, 0) => [0, 1]
adder(1, 1, 1) => [1, 1]
```