# Replacing the calculator with a computer

Let's consider a basic  calculator with buttons to add, subtract, multiply, divide, and take square roots. Using such a simple thing is certainly familiar for any reader of this. `Julia` makes all these tasks just as easy, offering numerous conveniences along the way.

The following image is the calculator that Google presents upon searching for "calculator." 

```
using WeavePynb
img = "calculator.png"
calculator_image = gif_to_data(img, "Screenshot of a calculator provided by the Google search engine.")
WeavePynb.HTMLoutput(calculator_image)
```

This calculator should have a familiar appearance with a keypad of
numbers, a set of buttons for arithmetic operations, a set of buttons
for some common mathematical functions, a degree/radian switch, and
buttons for interacting with the calculator: `Ans`, `AC` (also `CE`),
and `=`.


---

For an illustration of *really* basic calculator, have some fun watching this video:

```
txt = """
<iframe width="560" height="315" src="https://www.youtube.com/embed/sxLdGjV-_yg" frameborder="0" allowfullscreen></iframe>
"""
WeavePynb.HTMLoutput(txt)
```

## Operations

Performing a simple computation on the calculator typically involves
hitting buttons in a sequence, such as "1", "+", "2", "`=`" to compute
3 from adding 1 + 2. In `Julia`, the process is not so
different. Instead of pressing buttons, the various values are
typed in. So, we would have:

```
1 + 2
```

Sending an expression to `Julia`'s interpreter -- the equivalent of
pressing the "`=`" key on a calculator -- is done at the command line
by pressing the `Enter` or `Return` key, and in `IJulia` using the
"play" icon, or the keyboard shortcut `Shift-Enter`. If the current
expression is complete, then `Julia` evaluates it and shows any
output.  If the expression is not complete, `Julia`'s response depends
on how it is being called. Within `IJulia`, a message about
"premature" end of input is given. If the expression raises an error,
this will be noted.


The basic arithmetic operations on a calculator are "+", "-", "×",
"÷", and "$xʸ$". These have parallels in `Julia` through the *binary*
operators: `+`, `-`, `*`, `/`, and `^`:

```
1 + 2, 2 - 3, 3 * 4, 4 / 5, 5 ^ 6
```

On some calculators, there is a distinction between minus signs. The
binary minus sign and the unary minus sign to create values such as
$-1$.

In `Julia`, the same "`-`" value is used for each:

```
-1 - 2
```

An expression like $6 - -3$ must be handled with some care.  With the
Google calculator, the expression must be entered with accompanying
parentheses: $6 -(-3)$. In `Julia`, parentheses are not needed, but a
space is between the two minus signs:

```
6 - -3
```

(If no space is included, the value "`--`" is parsed like a different, undefined, operation.)


```
warning(L"""

`Julia` only uses one symbol for minus, but web pages may not! Copying
and pasting an expression with a minus sign can lead to hard to
understand errors such as: `invalid character "−"`. There are several
Unicode symbols that look similar to the ASCII minus sign, but are
different. These pages use a different character for the minus sign for
the typeset math (e.g., $1 - \pi$), but not the code within cells
(e.g. `1 - 2`).

""")
```

### Examples

- For everyday temperatures, the conversion from Celsius to Fahrenheit
  ($9/5 C + 32$) is well approximated by simply doubling and
  adding 30. Compare these values for C=18.


```
9/5*18 + 32
```

The approximate one is:

```
2 * 18 + 30
```

##### Example

Add the numbers $1 + 2 + 3 + 4 + 5$.

```
1 + 2 + 3 + 4 + 5
```

##### Example

How small is $1/2/3/4/5/6$? It is about $14/10000$, as this will show:

```
1/2/3/4/5/6
```

##### Example

Which is bigger $4^3$ or $3^4$? We can check by computing their difference:

```
4^3 - 3^4
```

So $3^4$ is bigger.

##### Example

A right triangle has sides $a=11$ and $b=12$. Find the length of the
  hypotenuse squared. As $c^2 = a^2 + b^2$ we have:

```
11^2 + 12^2
```

## Order of operations

The calculator must use some rules to define how it will evaluate its instructions when two or more operations are involved. We know mathematically, that when $1 + 2 \cdot 3$ is to be evaluated the multiplication is  done first then the addition.

With the Google Calculator, typing `1 + 2 x 3 =` will give the value
$7$, but *if* we evaluate the `+` sign first, via `1 + 2 = x 3 =` the
answer will be 9, as that will force the addition of `1+2` before
multiplying. The more traditional way of performing that calculation
is to use *parentheses* to force an evaluation. That is,
`(1 + 2) * 3 =` will produce `9` (though one must type it in, and not use a mouse
to enter). Except for the most primitive of calculators, there are
dedicated buttons for parentheses to group expressions.

In `Julia`, the entire expression is typed in before being evaluated,
so the usual conventions of mathematics related to the order of
operations may be used. These are colloquially summarized by the
acronym [PEMDAS](http://en.wikipedia.org/wiki/Order_of_operations).

> **PEMDAS**. This acronym stands for Parentheses, Exponents,
> Multiplication, Division, Addition, Subtraction. The order indicates
> which operation has higher precedence, or should happen first. This
> isn't exactly the case, as "M" and "D" have the same precedence, as
> do "A" and "S". In the case of two operations with equal precedence,
> *associativity* is used to decide which to do. For the operations
> `+`, `-`, `*`, `/` the associativity is left to right, as in the
> left one is done first, then the right. However, `^` has right
> associativity, so `4^3^2` is `4^(3^2)` and not `(4^3)^2`. (Be warned
> that some calculators -- and spread sheets such as Excel -- will
> treat this expression with left associativity.)


With rules of precedence an expression such as the following has a
clear interpretation to `Julia` without the need for parentheses.

```
1 + 2 - 3 * 4 / 5 ^ 6
```

Working through PEMDAS we see that `^` is first, then `*` and then `/`
(this due to associativity and `*` being the leftmost expression of
the two) and finally `+` and then `-`, again by associativity
rules. So we should have the same value with:

```
(1 + 2) - ((3 * 4) / (5 ^ 6))
```


### Examples

The percentage error in $x$ if $y$ is the correct value is $(x-y)/y \cdot 100$. Compute this if $x=100$ and $y=98.6$.

```
(100 - 98.6) / 98.6 * 100
```

##### Example

The marginal cost of producing one unit can be computed by
  finding the cost for $n+1$ units and subtracting the cost for
  $n$ units. If, in general, the cost of $n$ units is $n^2 + 10$, find the marginal cost when $n=100$.

```
(101^2 + 10) - (100^2 + 10)
```

##### Example

The average cost per unit is the total cost divided by the number of units. Again, if, in general, the cost of $n$ units is $n^2 + 10$, find the average cost for $n=100$ units.

```
(100^2 + 10) / 100
```

##### Example

The slope of the line through two points is $m=(y_1 - y_0) / (x_1 - x_0)$. For the two points $(1,2)$ and $(3,4)$ find the slope of the line through them.

```
(4 - 2) / (3 - 1)
```

### Two ways to write division -- and they are not the same

One place where parentheses are required is when a mathematical expression is written with a horizontal division sign (a [vinicula](http://en.wikipedia.org/wiki/Vinculum_%28symbol%29)) and has a complex denominator. For example:

$$~
\frac{1 + 2}{3 + 4}
~$$

This is because unlike `/`, the implied order of operation in the mathematical notation with the horizontal division symbol is to compute the top and the bottom and then divide. That is, the vinicula is a grouping notation like parentheses, only implicitly so. Thus the above expression really represents the more verbose:


$$~
\frac{(1 + 2)}{(3 + 4)}.
~$$

This lends itself readily to the translation:

```
(1 + 2) / (3 + 4)
```

To emphasize, this is not the same as the value without the parentheses:

```
1 + 2 / 3 + 4
```

```
alert(L"""

The viniculum also indicates grouping when used with the square root
(the top bar), and complex conjugation. That usage is often clear
enough, but the usage of the viniculum in division often leads to
confusion. The example above is one where the parentheses are often,
erroneously, omitted. However, more confusion can arise when there is
more than one vinicula. An expression such as $a/b/c$ written inline
has no confusion, it is: $(a/b) / c$ as left association is used; but
when written with a pair of vinicula there is often the typographical
convention of a slightly longer vinicula to indicate which is to
be considered first. In the absence of that, then top to bottom association is
often implied.

""")
```




### Infix notation

The factorial button on the Google Button creates an expression like
`14!` that is then evaluated. The operator, `!`, appears after the
value, `14`, that it is applied to. This is called *postfix
notation*. When a unary minus sign is used, as in `-14`, the minus
sign occurs before the value it operates on. This uses *prefix
notation*. These concepts can be extended to binary operations, where
a third possibility is provided: *infix notation*, where the operator
is between the two values. The infix notation is common for our
familiar mathematical operations. We write `14 + 2` and not `+ 14 2`
or `14 2 +`. (Though if we had an old reverse-Polish notation
calculator, we would enter `14 2 +`!) In `Julia`, there are several
infix operators, such as `+`, `-`, ... and others that we may be
unfamiliar with. These mirror the familiar notation from most math
texts. However, prefix notation is more common, though with a set of
parentheses to separate the operator and the values. For example:

```
+(14, 2)
```

## Constants

The Google calculator has two built in constants, `e` and `π`. Julia provides these as well:

```
e, pi
```

Mathematically these are irrational values with decimal expansions that do not repeat. `Julia` represents them internally with additional accuracy than is displayed. Math constants can be used as though they were numbers, such is done with this expression:

```
e^(1/(2*pi))
```


## Functions

On the Google calculator, the square root button has a single purpose: for the current value find a square root if possible, and if not signal an error (such as what happens if the value is negative). For more general powers, the $x^y$ key can be used. 

In `Julia`, functions are used to perform the actions that a specialized button may do on the calculator. `Julia` provides many standard mathematical functions -- more than there could be buttons on a calculator -- and allows the user to easily define their own functions. For example, julia provides the same set of functions on the calculator, though with different names. For logarithms, $\ln$ becomes `log` and $\log$ is `log10` (computer programs almost exclusively reserve `log` for the natural log); for factorials, $x!$, there is `factorial`; for powers $\sqrt{}$ becomes `sqrt`, $EXP$ becomes `exp`, and $x^y$ is given by `^`. For the trigonometric functions, the basic names are similar: `sin`, `cos`, `tan`. These expect radians. For angles in degrees, the convenience functions `sind`, `cosd`, and `tand` are provided. On the calculator, inverse functions like $\sin^{-1}(x)$ are done by combining $Inv$ with $\sin$. With `Julia`, the function name is `asin`, an abbreviation for "arcsine." (Which is a good thing, as the notation using a power of $-1$ is confusing and is not supported by `Julia`.) Similarly, there are `asind`, `acos`, `acosd`, `atan`, and `atand` functions available to the `Julia` user.



Using a function is very straightforward. A function is called using parentheses, in a manner visually similar to how a function is called mathematically. So if we consider the `sqrt` function, we have:

```
sqrt(4), sqrt(5)
```

The function is referred to by name (`sqrt`) and called with parentheses. Any arguments are passed into the function using commas to separate values, should there be more than one. When there are numerous values for a function, the arguments may need to be given in a specific order or may possibly be specified with *keywords*.

```
note("""

Parentheses have many roles. We've just seen that parentheses may be
used for grouping, and now we see they are used to indicate a function
is being called. These are familiar from their parallel usage in
traditional math notation. In `Julia`, a third usage is common, the
making of a "tuple," or a container of different objects, for example
`(1,e, pi)`.

""")
```

`Julia`'s design embraces *polymorphism*, a term to indicate that the same function may have different implementations and the one ultimately called depends on the number and types of the arguments. Polymorphism is also commonly referred to as *multiple dispatch*. This is a great convenience for the user who only needs to remember one function name for related uses, that may differ only in technicalities.  For example, there are over 100 methods implemented for the generic function `+`. This may be expected from mathematical analogy: the details of the operation of addition are different for integers, than rational numbers, than polynomials, though all can be added.


The power operator, `^`, provides a concrete example. For integer bases there is a different implementation than there is for real bases. When the base is an integer, only those powers that will produce an integer are allowed. This is why `2^(-1)` gives a domain error

```
2^(-1)
```

However, the similar looking value:

```
2.0^(-1)
```

produces an answer, as `2.0` is a floating point value, and floating point values can be used to represent rational values.



For the logarithm, we mentioned that `log` is the natural log and
`log10` implements the logarithm base 10. As well there is
`log2`. However, in general there is no `logb` for any base
`b`. Instead, the basic `log` function can take two arguments. When it
does, the first is the base, and the second the value to take the
logarithm of. This avoids forcing the user to remember that $\log_b(x)
= \log(x)/\log(b)$.

So we have these uses to find logarithms:

```
log(e), log(2, e), log(10, e), log(e, 2)
```

The generic function `log` not only has different implementations for
different types of arguments (real or complex), but also has a
different implementation depending on the number of arguments.

### Examples


A right triangle has sides $a=11$ and $b=12$. Find the length of the hypotenuse. As $c^2 = a^2 + b^2$ we have:

```
sqrt(11^2 + 12^2)
```

##### Example

A formula from statistics to compute the variance for $p$, when
$n=10$ is $\sqrt{p (1-p)/10}$. Compute this value for $p=1/4$.

```
sqrt((1/4 * (1 - 1/4)) / 10)
```

##### Example

Find the distance between the points $(-3, -4)$ and $(5,6)$. Using the distance formula $\sqrt{(x_1-x_0)^2+(y_1-y_0)^2}$, we have:

```
sqrt((5 - -3)^2 + (6 - -4)^2)
```


##### Example

The formula to compute the resistance of two resistors in parallel is
given by: $1/(1/r_1 + 1/r_2)$. Suppose the resistance is $10$ in one resistor
and $20$ in the other. What is the resistance in parallel?

```
1 / (1/10 + 1/20)
```

## Errors

Not all computations on a calculator are valid. For example, the Google calculator will display `Error` as the output of $0/0$ or $\sqrt{-1}$. These are also errors mathematically, though the second is not if the complex numbers are considered.

In `Julia`, there is a richer set of error types. The value `0/0` will in fact not be an error, but rather a value `NaN`. This is a special floating point value indicating "not a number" and is the result for various operations.  The output of $\sqrt{-1}$ (computed via `sqrt(-1)`) will indicate a domain error:

```
sqrt(-1)
```

For integer or real-valued inputs, the `sqrt` function expects non-negative values, so that the output will always be a real number.

Surprisingly at first, the expression `2^-1` will also yield a domain error:


```
2^-1
```

Unlike the calculator, `Julia` makes a distinction between integer and
non-integer values. Julia expects that for integer exponents with
integer bases, the answer will be an integer and the answer in this
expression, $1/2$, is not. The actual error message gives some indication of how to workaround this.

There are other types of errors. Overflow is a common one on most
calculators. The value of $1000!$ is actually *very* large (over 2500
digits large). On the Google calculator it returns `Infinity`, a
slight stretch. `Julia` gives `factorial(1000)` an
`OverflowError`. This means that the answer is too large to be
represented as a regular integer.

```
factorial(1000)
```

How `Julia` handles overflow is a study in tradeoffs. For operations
that demand high performance, `Julia` does not check for overflow. So,
for example, if we are not careful strange answers can be
had. Consider the difference here between powers of 2:

```
2^62, 2^63
```

On a machine with 64-bit integers, the first of these two values is
correct, the second, clearly wrong, as the answer given is
negative. This is due to overflow. The cost of checking is considered
too high, so no error is thrown. The user is expected to have a sense
that they need to be careful when their values are quite large. (Or
use floating point numbers, which though not exact, can represent much
bigger values.)

```
alert("""

In a turnaround from a classic blues song, we can think of `Julia` as
built for speed, not for comfort. All of these errors above could be
worked around so that the end user doesn't see them. However, this
would require slowing things down, either through checking of
operations or allowing different types of outputs for similar type of
inputs. These are tradeoffs that are not made for performance
reasons. For the most part, the tradeoffs don't get in the way, but
learning where to be careful takes some time. The error message can
often give advice.

""")
```


## Questions

###### Question


Compute $22/7$ with `Julia`.

```
val = 22/7
numericq(val)
```

###### Question


Compute $\sqrt{220}$ with `Julia`.

```
val = sqrt(220)
numericq(val)
```

###### Question


Compute $2^8$ with `Julia`.

```
val = 2^8
numericq(val)
```

###### Question

Compute the value of 

$$~
\frac{9 - 5 \cdot (3-4)}{6 - 2}.
~$$

```
val = (9-5*(3-4)) / (6-2)
numericq(val)
```

###### Question


Compute the following using `Julia`:

$$~
\frac{(.25 - .2)^2}{(1/4)^2 + (1/3)^2}
~$$

```
val = (.25 - .2)^2/((1/4)^2 + (1/3)^2);
numericq(val)
```

###### Question


Compute the decimal representation of the following using `Julia`:

$$~
1 + \frac{1}{2} + \frac{1}{2^2} + \frac{1}{2^3} + \frac{1}{2^4}
~$$

```
val = sum((1/2).^(0:4));
numericq(val)
```


###### Question

Compute the following using `Julia`:

$$~
\frac{3 - 2^2}{4 - 2\cdot3}
~$$

```
val = (3 - 2^2)/(4 - 2*3);
numericq(val)
```

###### Question

Compute the following using `Julia`:

$$~
(1/2) \cdot 32 \cdot 3^2 + 100 \cdot 3 - 20
~$$

```
val = (1/2)*32*3^2 + 100*3 - 20;
numericq(val)
```


###### Question


Wich of the following is a valid `Julia` expression for 

$$~
\frac{3 - 2}{4 - 1}
~$$ 

that uses the least number of parentheses?

```
choices = [
q"(3 - 2)/ 4 - 1",
q"3 - 2 / (4 - 1)",
q"(3 - 2) / (4 - 1)"]
ans = 3
radioq(choices, ans)
```

###### Question


Wich of the following is a valid `Julia` expression for 

$$~
\frac{3\cdot2}{4}
~$$ 

that uses the least number of parentheses?

```
choices = [
q"3 * 2 / 4",
q"(3 * 2) / 4"
]
ans = 1
radioq(choices, ans)
```

###### Question


Which of the following is a valid `Julia` expression for 

$$~
2^{4 - 2}
~$$ 

that uses the least number of parentheses?

```
choices = [
q"2 ^ 4 - 2",
q"(2 ^ 4) - 2",
q"2 ^ (4 - 2)"]
ans = 3
radioq(choices, ans)
```

###### Question


One of these three expressions will produce a different answer, select
that one:

```
choices = [
q"2 - 3 - 4",
q"(2 - 3) - 4",
q"2 - (3 - 4)"
];
ans = 3;
radioq(choices, ans)
```


###### Question

One of these three expressions will produce a different answer, select
that one:

```
choices = [
q"2 - 3 * 4",
q"(2 - 3) * 4",
q"2 - (3 * 4)"
];
ans = 2;
radioq(choices, ans)
```


###### Question

One of these three expressions will produce a different answer, select
that one:


```
choices = [
q"-1^2",
q"(-1)^2",
q"-(1^2)"
];
ans = 2;
radioq(choices, ans)
```


###### Question

What is the value of $\sin(\pi/10)$?

```
val = sin(pi/10)
numericq(val)
```
###### Question


What is the value of $\sin(52^\circ)$?

```
val = sind(52)
numericq(val)
```

###### Question


Is $\sin^{-1}(\sin(3\pi/2))$ equal to $3\pi/2$? (The "arc" functions
do no use power notation, but instead a prefix of `a`.)

```
yesnoq(false)
```

###### Question


What is the value of `round(3.5000)`

```
numericq(round(3.5))
```

###### Question


What is the value of `sqrt(32 - 12)`

```
numericq(sqrt(32-12))
```

###### Question


Which is greater $e^\pi$ or $\pi^e$?


```
choices = [
q"e^pi",
q"pi^e"
];
ans = e^pi - pi^e > 0 ? 1 : 2;
radioq(choices, ans)
```

###### Question


What is the value of $\pi - (x - \sin(x)/\cos(x))$ when $x=3$?



```
x = 3;
ans = x - sin(x)/cos(x);
numericq(pi - ans)
```

###### Question


Search the page mathematical
[functions](http://docs.julialang.org/en/latest/stdlib/base/#mathematical-functions)
for a function which finds the factorial of `n`. The proper `Julia`
command to find $10!$ would be:

```
choices = [
q"factorial(10)",
q"fact(10)",
q"10!"
];
ans = 1;
radioq(choices, ans)
```

###### Question

Will `-2^2` produce `4` (unary `-` evaluated before `^`) or `-4` (unary `-` evaluated after `^`)?

```
choices = [q"4", q"-4"]
ans = 2
radioq(choices, ans)
```
