This is Info file calc.info, produced by Makeinfo version 1.67 from the
input file /ade-src/fsf/calc/calc.texinfo.

   This file documents Calc, the GNU Emacs calculator.

   Copyright (C) 1990, 1991 Free Software Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU General Public License" is included
exactly as in the original, and provided that the entire resulting
derived work is distributed under the terms of a permission notice
identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the section entitled "GNU General Public License"
may be included in a translation approved by the author instead of in
the original English.


File: calc.info,  Node: List Tutorial,  Prev: Matrix Tutorial,  Up: Vector/Matrix Tutorial

Vectors as Lists
----------------

Although Calc has a number of features for manipulating vectors and
matrices as mathematical objects, you can also treat vectors as simple
lists of values.  For example, we saw that the `k f' command returns a
vector which is a list of the prime factors of a number.

   You can pack and unpack stack entries into vectors:

     3:  10         1:  [10, 20, 30]     3:  10
     2:  20             .                2:  20
     1:  30                              1:  30
         .                                   .
     
                        M-3 v p              v u

   You can also build vectors out of consecutive integers, or out of
many copies of a given value:

     1:  [1, 2, 3, 4]    2:  [1, 2, 3, 4]    2:  [1, 2, 3, 4]
         .               1:  17              1:  [17, 17, 17, 17]
                             .                   .
     
         v x 4 RET           17                  v b 4 RET

   You can apply an operator to every element of a vector using the
"map" command.

     1:  [17, 34, 51, 68]   1:  [289, 1156, 2601, 4624]  1:  [17, 34, 51, 68]
         .                      .                            .
     
         V M *                  2 V M ^                      V M Q

In the first step, we multiply the vector of integers by the vector of
17's elementwise.  In the second step, we raise each element to the
power two.  (The general rule is that both operands must be vectors of
the same length, or else one must be a vector and the other a plain
number.)  In the final step, we take the square root of each element.

   (*) *Exercise 1.*  Compute a vector of powers of two from `2^-4' to
`2^4'.  *Note 1: List Answer 1. (*)

   You can also "reduce" a binary operator across a vector.  For
example, reducing `*' computes the product of all the elements in the
vector:

     1:  123123     1:  [3, 7, 11, 13, 41]      1:  123123
         .              .                           .
     
         123123         k f                         V R *

In this example, we decompose 123123 into its prime factors, then
multiply those factors together again to yield the original number.

   We could compute a dot product "by hand" using mapping and reduction:

     2:  [1, 2, 3]     1:  [7, 12, 0]     1:  19
     1:  [7, 6, 0]         .                  .
         .
     
         r 1 r 2           V M *              V R +

Recalling two vectors from the previous section, we compute the sum of
pairwise products of the elements to get the same answer for the dot
product as before.

   A slight variant of vector reduction is the "accumulate" operation,
`V U'.  This produces a vector of the intermediate results from a
corresponding reduction.  Here we compute a table of factorials:

     1:  [1, 2, 3, 4, 5, 6]    1:  [1, 2, 6, 24, 120, 720]
         .                         .
     
         v x 6 RET                 V U *

   Calc allows vectors to grow as large as you like, although it gets
rather slow if vectors have more than about a hundred elements.
Actually, most of the time is spent formatting these large vectors for
display, not calculating on them.  Try the following experiment (if
your computer is very fast you may need to substitute a larger vector
size).

     1:  [1, 2, 3, 4, ...      1:  [2, 3, 4, 5, ...
         .                         .
     
         v x 500 RET               1 V M +

   Now press `v .' (the letter `v', then a period) and try the
experiment again.  In `v .' mode, long vectors are displayed
"abbreviated" like this:

     1:  [1, 2, 3, ..., 500]   1:  [2, 3, 4, ..., 501]
         .                         .
     
         v x 500 RET               1 V M +

(where now the `...' is actually part of the Calc display).  You will
find both operations are now much faster.  But notice that even in
`v .' mode, the full vectors are still shown in the Trail.  Type `t .'
to cause the trail to abbreviate as well, and try the experiment one
more time.  Operations on long vectors are now quite fast!  (But of
course if you use `t .' you will lose the ability to get old vectors
back using the `t y' command.)

   An easy way to view a full vector when `v .' mode is active is to
press ``' (back-quote) to edit the vector; editing always works with
the full, unabbreviated value.

   As a larger example, let's try to fit a straight line to some data,
using the method of least squares.  (Calc has a built-in command for
least-squares curve fitting, but we'll do it by hand here just to
practice working with vectors.)  Suppose we have the following list of
values in a file we have loaded into Emacs:

       x        y
      ---      ---
      1.34    0.234
      1.41    0.298
      1.49    0.402
      1.56    0.412
      1.64    0.466
      1.73    0.473
      1.82    0.601
      1.91    0.519
      2.01    0.603
      2.11    0.637
      2.22    0.645
      2.33    0.705
      2.45    0.917
      2.58    1.009
      2.71    0.971
      2.85    1.062
      3.00    1.148
      3.15    1.157
      3.32    1.354

If you are reading this tutorial in printed form, you will find it
easiest to press `M-# i' to enter the on-line Info version of the
manual and find this table there.  (Press `g', then type `List
Tutorial', to jump straight to this section.)

   Position the cursor at the upper-left corner of this table, just to
the left of the `1.34'.  Press `C-@' to set the mark.  (On your system
this may be `C-2', `C-SPC', or `NUL'.) Now position the cursor to the
lower-right, just after the `1.354'.  You have now defined this region
as an Emacs "rectangle."  Still in the Info buffer, type `M-# r'.  This
command (`calc-grab-rectangle') will pop you back into the Calculator,
with the contents of the rectangle you specified in the form of a
matrix.

     1:  [ [ 1.34, 0.234 ]
           [ 1.41, 0.298 ]
           ...

(You may wish to use `v .' mode to abbreviate the display of this large
matrix.)

   We want to treat this as a pair of lists.  The first step is to
transpose this matrix into a pair of rows.  Remember, a matrix is just
a vector of vectors.  So we can unpack the matrix into a pair of row
vectors on the stack.

     1:  [ [ 1.34,  1.41,  1.49,  ... ]     2:  [1.34, 1.41, 1.49, ... ]
           [ 0.234, 0.298, 0.402, ... ] ]   1:  [0.234, 0.298, 0.402, ... ]
         .                                      .
     
         v t                                    v u

Let's store these in quick variables 1 and 2, respectively.

     1:  [1.34, 1.41, 1.49, ... ]        .
         .
     
         t 2                             t 1

(Recall that `t 2' is a variant of `s 2' that removes the stored value
from the stack.)

   In a least squares fit, the slope `m' is given by the formula

     m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)

where `sum(x)' represents the sum of all the values of `x'.  While
there is an actual `sum' function in Calc, it's easier to sum a vector
using a simple reduction.  First, let's compute the four different sums
that this formula uses.

     1:  41.63                 1:  98.0003
         .                         .
     
      r 1 V R +   t 3           r 1 2 V M ^ V R +   t 4

     1:  13.613                1:  33.36554
         .                         .
     
      r 2 V R +   t 5           r 1 r 2 V M * V R +   t 6

These are `sum(x)', `sum(x^2)', `sum(y)', and `sum(x y)', respectively.
(We could have used `*' to compute `sum(x^2)' and `sum(x y)'.)

Finally, we also need `N', the number of data points.  This is just the
length of either of our lists.

     1:  19
         .
     
      r 1 v l   t 7

(That's `v' followed by a lower-case `l'.)

   Now we grind through the formula:

     1:  633.94526  2:  633.94526  1:  67.23607
         .          1:  566.70919      .
                        .
     
      r 7 r 6 *      r 3 r 5 *         -

     2:  67.23607   3:  67.23607   2:  67.23607   1:  0.52141679
     1:  1862.0057  2:  1862.0057  1:  128.9488       .
         .          1:  1733.0569      .
                        .
     
      r 7 r 4 *      r 3 2 ^           -              /   t 8

That gives us the slope `m'.  The y-intercept `b' can now be found with
the simple formula,

     b = (sum(y) - m sum(x)) / N

     1:  13.613     2:  13.613     1:  -8.09358   1:  -0.425978
         .          1:  21.70658       .              .
                        .
     
        r 5            r 8 r 3 *       -              r 7 /   t 9

   Let's "plot" this straight line approximation, `m x + b', and
compare it with the original data.

     1:  [0.699, 0.735, ... ]    1:  [0.273, 0.309, ... ]
         .                           .
     
         r 1 r 8 *                   r 9 +    s 0

Notice that multiplying a vector by a constant, and adding a constant
to a vector, can be done without mapping commands since these are
common operations from vector algebra.  As far as Calc is concerned,
we've just been doing geometry in 19-dimensional space!

   We can subtract this vector from our original `y' vector to get a
feel for the error of our fit.  Let's find the maximum error:

     1:  [0.0387, 0.0112, ... ]   1:  [0.0387, 0.0112, ... ]   1:  0.0897
         .                            .                            .
     
         r 2 -                        V M A                        V R X

First we compute a vector of differences, then we take the absolute
values of these differences, then we reduce the `max' function across
the vector.  (The `max' function is on the two-key sequence `f x';
because it is so common to use `max' in a vector operation, the letters
`X' and `N' are also accepted for `max' and `min' in this context.  In
general, you answer the `V M' or `V R' prompt with the actual key
sequence that invokes the function you want.  You could have typed `V R
f x' or even `V R x max <RET>' if you had preferred.)

   If your system has the GNUPLOT program, you can see graphs of your
data and your straight line to see how well they match.  (If you have
GNUPLOT 3.0, the following instructions will work regardless of the
kind of display you have.  Some GNUPLOT 2.0, non-X-windows systems may
require additional steps to view the graphs.)

   Let's start by plotting the original data.  Recall the "x" and "y"
vectors onto the stack and press `g f'.  This "fast" graphing command
does everything you need to do for simple, straightforward plotting of
data.

     2:  [1.34, 1.41, 1.49, ... ]
     1:  [0.234, 0.298, 0.402, ... ]
         .
     
         r 1 r 2    g f

   If all goes well, you will shortly get a new window containing a
graph of the data.  (If not, contact your GNUPLOT or Calc installer to
find out what went wrong.)  In the X window system, this will be a
separate graphics window.  For other kinds of displays, the default is
to display the graph in Emacs itself using rough character graphics.
Press `q' when you are done viewing the character graphics.

   Next, let's add the line we got from our least-squares fit:

     2:  [1.34, 1.41, 1.49, ... ]
     1:  [0.273, 0.309, 0.351, ... ]
         .
     
         DEL r 0    g a  g p

   It's not very useful to get symbols to mark the data points on this
second curve; you can type `g S g p' to remove them.  Type `g q' when
you are done to remove the X graphics window and terminate GNUPLOT.

   (*) *Exercise 2.*  An earlier exercise showed how to do least
squares fitting to a general system of equations.  Our 19 data points
are really 19 equations of the form `y_i = m x_i + b' for different
pairs of `(x_i,y_i)'.  Use the matrix-transpose method to solve for `m'
and `b', duplicating the above result.  *Note 2: List Answer 2. (*)

   (*) *Exercise 3.*  If the input data do not form a rectangle, you
can use `M-# g' (`calc-grab-region') to grab the data the way Emacs
normally works with regions--it reads left-to-right, top-to-bottom,
treating line breaks the same as spaces.  Use this command to find the
geometric mean of the following numbers.  (The geometric mean is the
Nth root of the product of N numbers.)

     2.3  6  22  15.1  7
       15  14  7.5
       2.5

The `M-# g' command accepts numbers separated by spaces or commas, with
or without surrounding vector brackets.  *Note 3: List Answer 3. (*)

   As another example, a theorem about binomial coefficients tells us
that the alternating sum of binomial coefficients N-choose-0 minus
N-choose-1 plus N-choose-2, and so on up to N-choose-N, always comes
out to zero.  Let's verify this for `n=6'.

     1:  [1, 2, 3, 4, 5, 6, 7]     1:  [0, 1, 2, 3, 4, 5, 6]
         .                             .
     
         v x 7 RET                     1 -

     1:  [1, -6, 15, -20, 15, -6, 1]          1:  0
         .                                        .
     
         V M ' (-1)^$ choose(6,$) RET             V R +

The `V M '' command prompts you to enter any algebraic expression to
define the function to map over the vector.  The symbol `$' inside this
expression represents the argument to the function.  The Calculator
applies this formula to each element of the vector, substituting each
element's value for the `$' sign(s) in turn.

   To define a two-argument function, use `$$' for the first argument
and `$' for the second:  `V M ' $$-$ RET' is equivalent to `V M -'.
This is analogous to regular algebraic entry, where `$$' would refer to
the next-to-top stack entry and `$' would refer to the top stack entry,
and `' $$-$ RET' would act exactly like `-'.

   Notice that the `V M '' command has recorded two things in the
trail:  The result, as usual, and also a funny-looking thing marked
`oper' that represents the operator function you typed in.  The
function is enclosed in `< >' brackets, and the argument is denoted by
a `#' sign.  If there were several arguments, they would be shown as
`#1', `#2', and so on.  (For example, `V M ' $$-$' will put the
function `<#1 - #2>' on the trail.)  This object is a "nameless
function"; you can use nameless `< >' notation to answer the `V M ''
prompt if you like.  Nameless function notation has the interesting,
occasionally useful property that a nameless function is not actually
evaluated until it is used.  For example, `V M ' $+random(2.0)'
evaluates `random(2.0)' once and adds that random number to all elements
of the vector, but `V M ' <#+random(2.0)>' evaluates the `random(2.0)'
separately for each vector element.

   Another group of operators that are often useful with `V M' are the
relational operators:  `a =', for example, compares two numbers and
gives the result 1 if they are equal, or 0 if not.  Similarly, `a <'
checks for one number being less than another.

   Other useful vector operations include `v v', to reverse a vector
end-for-end; `V S', to sort the elements of a vector into increasing
order; and `v r' and `v c', to extract one row or column of a matrix,
or (in both cases) to extract one element of a plain vector.  With a
negative argument, `v r' and `v c' instead delete one row, column, or
vector element.

   (*) *Exercise 4.*  The `k'th "divisor function" is the sum of the
`k'th powers of all the divisors of an integer `n'.  Figure out a
method for computing the divisor function for reasonably small values
of `n'.  As a test, the 0th and 1st divisor functions of 30 are 8 and
72, respectively.  *Note 4: List Answer 4. (*)

   (*) *Exercise 5.*  The `k f' command produces a list of prime
factors for a number.  Sometimes it is important to know that a number
is "square-free", i.e., that no prime occurs more than once in its list
of prime factors.  Find a sequence of keystrokes to tell if a number is
square-free; your method should leave 1 on the stack if it is, or 0 if
it isn't.  *Note 5: List Answer 5. (*)

   (*) *Exercise 6.*  Build a list of lists that looks like the
following diagram.  (You may wish to use the `v /' command to enable
multi-line display of vectors.)

     1:  [ [1],
           [1, 2],
           [1, 2, 3],
           [1, 2, 3, 4],
           [1, 2, 3, 4, 5],
           [1, 2, 3, 4, 5, 6] ]

*Note 6: List Answer 6. (*)

   (*) *Exercise 7.*  Build the following list of lists.

     1:  [ [0],
           [1, 2],
           [3, 4, 5],
           [6, 7, 8, 9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19, 20] ]

*Note 7: List Answer 7. (*)

   (*) *Exercise 8.*  Compute a list of values of Bessel's `J1'
function `besJ(1,x)' for `x' from 0 to 5 in steps of 0.25.  Find the
value of `x' (from among the above set of values) for which `besJ(1,x)'
is a maximum.  Use an "automatic" method, i.e., just reading along the
list by hand to find the largest value is not allowed!  (There is an `a
X' command which does this kind of thing automatically; *note Numerical
Solutions::..) *Note 8: List Answer 8. (*)

   (*) *Exercise 9.*  You are given an integer in the range `0 <= N <
10^m' for `m=12' (i.e., an integer of less than twelve digits).
Convert this integer into a vector of `m' digits, each in the range
from 0 to 9.  In vector-of-digits notation, add one to this integer to
produce a vector of `m+1' digits (since there could be a carry out of
the most significant digit).  Convert this vector back into a regular
integer.  A good integer to try is 25129925999.  *Note 9: List Answer
9. (*)

   (*) *Exercise 10.*  Your friend Joe tried to use `V R a =' to test
if all numbers in a list were equal.  What happened?  How would you do
this test?  *Note 10: List Answer 10. (*)

   (*) *Exercise 11.*  The area of a circle of radius one is `pi'.  The
area of the 2x2 square that encloses that circle is 4.  So if we throw
N darts at random points in the square, about `pi/4' of them will land
inside the circle.  This gives us an entertaining way to estimate the
value of `pi'.  The `k r' command picks a random number between zero
and the value on the stack.  We could get a random floating-point
number between -1 and 1 by typing `2.0 k r 1 -'.  Build a vector of 100
random `(x,y)' points in this square, then use vector mapping and
reduction to count how many points lie inside the unit circle.  Hint:
Use the `v b' command.  *Note 11: List Answer 11. (*)

   (*) *Exercise 12.*  The "matchstick problem" provides another way to
calculate `pi'.  Say you have an infinite field of vertical lines with
a spacing of one inch.  Toss a one-inch matchstick onto the field.  The
probability that the matchstick will land crossing a line turns out to
be `2/pi'.  Toss 100 matchsticks to estimate `pi'.  (If you want still
more fun, the probability that the GCD (`k g') of two large integers is
one turns out to be `6/pi^2'.  That provides yet another way to
estimate `pi'.) *Note 12: List Answer 12. (*)

   (*) *Exercise 13.*  An algebraic entry of a string in double-quote
marks, `"hello"', creates a vector of the numerical (ASCII) codes of
the characters (here, `[104, 101, 108, 108, 111]').  Sometimes it is
convenient to compute a "hash code" of a string, which is just an
integer that represents the value of that string.  Two equal strings
have the same hash code; two different strings "probably" have
different hash codes.  (For example, Calc has over 400 function names,
but Emacs can quickly find the definition for any given name because it
has sorted the functions into "buckets" by their hash codes.  Sometimes
a few names will hash into the same bucket, but it is easier to search
among a few names than among all the names.) One popular hash function
is computed as follows:  First set `h = 0'.  Then, for each character
from the string in turn, set `h = 3h + c_i' where `c_i' is the
character's ASCII code.  If we have 511 buckets, we then take the hash
code modulo 511 to get the bucket number.  Develop a simple command or
commands for converting string vectors into hash codes.  The hash code
for `"Testing, 1, 2, 3"' is 1960915098, which modulo 511 is 121.  *Note
13: List Answer 13. (*)

   (*) *Exercise 14.*  The `H V R' and `H V U' commands do nested
function evaluations.  `H V U' takes a starting value and a number of
steps N from the stack; it then applies the function you give to the
starting value 0, 1, 2, up to N times and returns a vector of the
results.  Use this command to create a "random walk" of 50 steps.
Start with the two-dimensional point `(0,0)'; then take one step a
random distance between -1 and 1 in both `x' and `y'; then take another
step, and so on.  Use the `g f' command to display this random walk.
Now modify your random walk to walk a unit distance, but in a random
direction, at each step.  (Hint:  The `sincos' function returns a
vector of the cosine and sine of an angle.)  *Note 14: List Answer 14.
(*)


File: calc.info,  Node: Types Tutorial,  Next: Algebra Tutorial,  Prev: Vector/Matrix Tutorial,  Up: Tutorial

Types Tutorial
==============

Calc understands a variety of data types as well as simple numbers.  In
this section, we'll experiment with each of these types in turn.

   The numbers we've been using so far have mainly been either
"integers" or "floats".  We saw that floats are usually a good
approximation to the mathematical concept of real numbers, but they are
only approximations and are susceptible to roundoff error.  Calc also
supports "fractions", which can exactly represent any rational number.

     1:  3628800    2:  3628800    1:  518400:7   1:  518414:7   1:  7:518414
         .          1:  49             .              .              .
                        .
     
         10 !           49 RET         :              2 +            &

The `:' command divides two integers to get a fraction; `/' would
normally divide integers to get a floating-point result.  Notice we had
to type <RET> between the `49' and the `:' since the `:' would
otherwise be interpreted as part of a fraction beginning with 49.

   You can convert between floating-point and fractional format using
`c f' and `c F':

     1:  1.35027217629e-5    1:  7:518414
         .                       .
     
         c f                     c F

   The `c F' command replaces a floating-point number with the
"simplest" fraction whose floating-point representation is the same, to
within the current precision.

     1:  3.14159265359   1:  1146408:364913   1:  3.1416   1:  355:113
         .                   .                    .            .
     
         P                   c F      DEL       p 5 RET P      c F

   (*) *Exercise 1.*  A calculation has produced the result
1.26508260337.  You suspect it is the square root of the product of
`pi' and some rational number.  Is it?  (Be sure to allow for roundoff
error!)  *Note 1: Types Answer 1. (*)

   "Complex numbers" can be stored in both rectangular and polar form.

     1:  -9     1:  (0, 3)    1:  (3; 90.)   1:  (6; 90.)   1:  (2.4495; 45.)
         .          .             .              .              .
     
         9 n        Q             c p            2 *            Q

The square root of -9 is by default rendered in rectangular form
(`0 + 3i'), but we can convert it to polar form (3 with a phase angle
of 90 degrees).  All the usual arithmetic and scientific operations are
defined on both types of complex numbers.

   Another generalized kind of number is "infinity".  Infinity isn't
really a number, but it can sometimes be treated like one.  Calc uses
the symbol `inf' to represent positive infinity, i.e., a value greater
than any real number.  Naturally, you can also write `-inf' for minus
infinity, a value less than any real number.  The word `inf' can only
be input using algebraic entry.

     2:  inf        2:  -inf       2:  -inf       2:  -inf       1:  nan
     1:  -17        1:  -inf       1:  -inf       1:  inf            .
         .              .              .              .
     
     ' inf RET 17 n     *  RET         72 +           A              +

Since infinity is infinitely large, multiplying it by any finite number
(like -17) has no effect, except that since -17 is negative, it changes
a plus infinity to a minus infinity.  ("A huge positive number,
multiplied by -17, yields a huge negative number.")  Adding any finite
number to infinity also leaves it unchanged.  Taking an absolute value
gives us plus infinity again.  Finally, we add this plus infinity to
the minus infinity we had earlier.  If you work it out, you might expect
the answer to be -72 for this.  But the 72 has been completely lost
next to the infinities; by the time we compute `inf - inf' the finite
difference between them, if any, is indetectable.  So we say the result
is "indeterminate", which Calc writes with the symbol `nan' (for Not A
Number).

   Dividing by zero is normally treated as an error, but you can get
Calc to write an answer in terms of infinity by pressing `m i' to turn
on "infinite mode."

     3:  nan        2:  nan        2:  nan        2:  nan        1:  nan
     2:  1          1:  1 / 0      1:  uinf       1:  uinf           .
     1:  0              .              .              .
         .
     
       1 RET 0          /       m i    U /            17 n *         +

Dividing by zero normally is left unevaluated, but after `m i' it
instead gives an infinite result.  The answer is actually `uinf',
"undirected infinity."  If you look at a graph of `1 / x' around
`x = 0', you'll see that it goes toward plus infinity as you approach
zero from above, but toward minus infinity as you approach from below.
Since we said only `1 / 0', Calc knows that the answer is infinite but
not in which direction.  That's what `uinf' means.  Notice that
multiplying `uinf' by a negative number still leaves plain `uinf';
there's no point in saying `-uinf' because the sign of `uinf' is
unknown anyway.  Finally, we add `uinf' to our `nan', yielding `nan'
again.  It's easy to see that, because `nan' means "totally unknown"
while `uinf' means "unknown sign but known to be infinite," the more
mysterious `nan' wins out when it is combined with `uinf', or, for that
matter, with anything else.

   (*) *Exercise 2.*  Predict what Calc will answer for each of these
formulas:  `inf / inf', `exp(inf)', `exp(-inf)', `sqrt(-inf)',
`sqrt(uinf)', `abs(uinf)', `ln(0)'.  *Note 2: Types Answer 2. (*)

   (*) *Exercise 3.*  We saw that `inf - inf = nan', which stands for
an unknown value.  Can `nan' stand for a complex number?  Can it stand
for infinity?  *Note 3: Types Answer 3. (*)

   "HMS forms" represent a value in terms of hours, minutes, and
seconds.

     1:  2@ 30' 0"     1:  3@ 30' 0"     2:  3@ 30' 0"     1:  2.
         .                 .             1:  1@ 45' 0."        .
                                             .
     
       2@ 30' RET          1 +               RET 2 /           /

   HMS forms can also be used to hold angles in degrees, minutes, and
seconds.

     1:  0.5        1:  26.56505   1:  26@ 33' 54.18"    1:  0.44721
         .              .              .                     .
     
         0.5            I T            c h                   S

First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
form, then we take the sine of that angle.  Note that the trigonometric
functions will accept HMS forms directly as input.

   (*) *Exercise 4.*  The Beatles' *Abbey Road* is 47 minutes and 26
seconds long, and contains 17 songs.  What is the average length of a
song on *Abbey Road*?  If the Extended Disco Version of *Abbey Road*
added 20 seconds to the length of each song, how long would the album
be?  *Note 4: Types Answer 4. (*)

   A "date form" represents a date, or a date and time.  Dates must be
entered using algebraic entry.  Date forms are surrounded by `< >'
symbols; most standard formats for dates are recognized.

     2:  <Sun Jan 13, 1991>                    1:  2.25
     1:  <6:00pm Thu Jan 10, 1991>                 .
         .
     
     ' <13 Jan 1991>, <1/10/91, 6pm> RET           -

In this example, we enter two dates, then subtract to find the number
of days between them.  It is also possible to add an HMS form or a
number (of days) to a date form to get another date form.

     1:  <4:45:59pm Mon Jan 14, 1991>     1:  <2:50:59am Thu Jan 17, 1991>
         .                                    .
     
         t N                                  2 + 10@ 5' +

The `t N' ("now") command pushes the current date and time on the
stack; then we add two days, ten hours and five minutes to the date and
time.  Other date-and-time related commands include `t J', which does
Julian day conversions, `t W', which finds the beginning of the week in
which a date form lies, and `t I', which increments a date by one or
several months.  *Note Date Arithmetic::, for more.

   (*) *Exercise 5.*  How many days until the next Friday the 13th?
*Note 5: Types Answer 5. (*)

   (*) *Exercise 6.*  How many leap years will there be between now and
the year 10001 A.D.?  *Note 6: Types Answer 6. (*)

   An "error form" represents a mean value with an attached standard
deviation, or error estimate.  Suppose our measurements indicate that a
certain telephone pole is about 30 meters away, with an estimated error
of 1 meter, and 8 meters tall, with an estimated error of 0.2 meters.
What is the slope of a line from here to the top of the pole, and what
is the equivalent angle in degrees?

     1:  8 +/- 0.2    2:  8 +/- 0.2   1:  0.266 +/- 0.011   1:  14.93 +/- 0.594
         .            1:  30 +/- 1        .                     .
                          .
     
         8 p .2 RET       30 p 1          /                     I T

This means that the angle is about 15 degrees, and, assuming our
original error estimates were valid standard deviations, there is about
a 60% chance that the result is correct within 0.59 degrees.

   (*) *Exercise 7.*  The volume of a torus (a donut shape) is
`2 pi^2 R r^2' where `R' is the radius of the circle that defines the
center of the tube and `r' is the radius of the tube itself.  Suppose
`R' is 20 cm and `r' is 4 cm, each known to within 5 percent.  What is
the volume and the relative uncertainty of the volume?  *Note 7: Types
Answer 7. (*)

   An "interval form" represents a range of values.  While an error
form is best for making statistical estimates, intervals give you exact
bounds on an answer.  Suppose we additionally know that our telephone
pole is definitely between 28 and 31 meters away, and that it is
between 7.7 and 8.1 meters tall.

     1:  [7.7 .. 8.1]  2:  [7.7 .. 8.1]  1:  [0.24 .. 0.28]  1:  [13.9 .. 16.1]
         .             1:  [28 .. 31]        .                   .
                           .
     
       [ 7.7 .. 8.1 ]    [ 28 .. 31 ]        /                   I T

If our bounds were correct, then the angle to the top of the pole is
sure to lie in the range shown.

   The square brackets around these intervals indicate that the
endpoints themselves are allowable values.  In other words, the
distance to the telephone pole is between 28 and 31, *inclusive*.  You
can also make an interval that is exclusive of its endpoints by writing
parentheses instead of square brackets.  You can even make an interval
which is inclusive ("closed") on one end and exclusive ("open") on the
other.

     1:  [1 .. 10)    1:  (0.1 .. 1]   2:  (0.1 .. 1]   1:  (0.2 .. 3)
         .                .            1:  [2 .. 3)         .
                                           .
     
       [ 1 .. 10 )        &              [ 2 .. 3 )         *

The Calculator automatically keeps track of which end values should be
open and which should be closed.  You can also make infinite or
semi-infinite intervals by using `-inf' or `inf' for one or both
endpoints.

   (*) *Exercise 8.*  What answer would you expect from `1 /
(0 .. 10)'?  What about `1 / (-10 .. 0)'?  What about `1 / [0 .. 10]'
(where the interval actually includes zero)?  What about `1 /
(-10 .. 10)'?  *Note 8: Types Answer 8. (*)

   (*) *Exercise 9.*  Two easy ways of squaring a number are `RET *'
and `2 ^'.  Normally these produce the same answer.  Would you expect
this still to hold true for interval forms?  If not, which of these
will result in a larger interval?  *Note 9: Types Answer 9. (*)

   A "modulo form" is used for performing arithmetic modulo M.  For
example, arithmetic involving time is generally done modulo 12 or 24
hours.

     1:  17 mod 24    1:  3 mod 24     1:  21 mod 24    1:  9 mod 24
         .                .                .                .
     
         17 M 24 RET      10 +             n                5 /

In this last step, Calc has found a new number which, when multiplied
by 5 modulo 24, produces the original number, 21.  If M is prime it is
always possible to find such a number.  For non-prime M like 24, it is
only sometimes possible.

     1:  10 mod 24    1:  16 mod 24    1:  1000000...   1:  16
         .                .                .                .
     
         10 M 24 RET      100 ^            10 RET 100 ^     24 %

These two calculations get the same answer, but the first one is much
more efficient because it avoids the huge intermediate value that
arises in the second one.

   (*) *Exercise 10.*  A theorem of Pierre de Fermat says that `x^(n-1)
mod n = 1' if `n' is a prime number and `x' is an integer less than
`n'.  If `n' is *not* a prime number, this will *not* be true for most
values of `x'.  Thus we can test informally if a number is prime by
trying this formula for several values of `x'.  Use this test to tell
whether the following numbers are prime: 811749613, 15485863.  *Note
10: Types Answer 10. (*)

   It is possible to use HMS forms as parts of error forms, intervals,
modulo forms, or as the phase part of a polar complex number.  For
example, the `calc-time' command pushes the current time of day on the
stack as an HMS/modulo form.

     1:  17@ 34' 45" mod 24@ 0' 0"     1:  6@ 22' 15" mod 24@ 0' 0"
         .                                 .
     
         x time RET                        n

This calculation tells me it is six hours and 22 minutes until midnight.

   (*) *Exercise 11.*  A rule of thumb is that one year is about
`pi * 10^7' seconds.  What time will it be that many seconds from right
now?  *Note 11: Types Answer 11. (*)

   (*) *Exercise 12.*  You are preparing to order packaging for the CD
release of the Extended Disco Version of *Abbey Road*.  You are told
that the songs will actually be anywhere from 20 to 60 seconds longer
than the originals.  One CD can hold about 75 minutes of music.  Should
you order single or double packages?  *Note 12: Types Answer 12. (*)

   Another kind of data the Calculator can manipulate is numbers with
"units".  This isn't strictly a new data type; it's simply an
application of algebraic expressions, where we use variables with
suggestive names like `cm' and `in' to represent units like centimeters
and inches.

     1:  2 in        1:  5.08 cm      1:  0.027778 fath   1:  0.0508 m
         .               .                .                   .
     
         ' 2in RET       u c cm RET       u c fath RET        u b

We enter the quantity "2 inches" (actually an algebraic expression
which means two times the variable `in'), then we convert it first to
centimeters, then to fathoms, then finally to "base" units, which in
this case means meters.

     1:  9 acre     1:  3 sqrt(acre)   1:  190.84 m   1:  190.84 m + 30 cm
         .              .                  .              .
     
      ' 9 acre RET      Q                  u s            ' $+30 cm RET

     1:  191.14 m     1:  36536.3046 m^2    1:  365363046 cm^2
         .                .                     .
     
         u s              2 ^                   u c cgs

Since units expressions are really just formulas, taking the square
root of `acre' is undefined.  After all, `acre' might be an algebraic
variable that you will someday assign a value.  We use the
"units-simplify" command to simplify the expression with variables
being interpreted as unit names.

   In the final step, we have converted not to a particular unit, but
to a units system.  The "cgs" system uses centimeters instead of meters
as its standard unit of length.

   There is a wide variety of units defined in the Calculator.

     1:  55 mph     1:  88.5139 kph   1:   88.5139 km / hr   1:  8.201407e-8 c
         .              .                  .                     .
     
      ' 55 mph RET      u c kph RET        u c km/hr RET         u c c RET

We express a speed first in miles per hour, then in kilometers per
hour, then again using a slightly more explicit notation, then finally
in terms of fractions of the speed of light.

   Temperature conversions are a bit more tricky.  There are two ways to
interpret "20 degrees Fahrenheit"--it could mean an actual temperature,
or it could mean a change in temperature.  For normal units there is no
difference, but temperature units have an offset as well as a scale
factor and so there must be two explicit commands for them.

     1:  20 degF       1:  11.1111 degC     1:  -20:3 degC    1:  -6.666 degC
         .                 .                    .                 .
     
       ' 20 degF RET       u c degC RET         U u t degC RET    c f

First we convert a change of 20 degrees Fahrenheit into an equivalent
change in degrees Celsius (or Centigrade).  Then, we convert the
absolute temperature 20 degrees Fahrenheit into Celsius.  Since this
comes out as an exact fraction, we then convert to floating-point for
easier comparison with the other result.

   For simple unit conversions, you can put a plain number on the stack.
Then `u c' and `u t' will prompt for both old and new units.  When you
use this method, you're responsible for remembering which numbers are
in which units:

     1:  55         1:  88.5139              1:  8.201407e-8
         .              .                        .
     
         55             u c mph RET kph RET      u c km/hr RET c RET

   To see a complete list of built-in units, type `u v'.  Press `M-# c'
again to re-enter the Calculator when you're done looking at the units
table.

   (*) *Exercise 13.*  How many seconds are there really in a year?
*Note 13: Types Answer 13. (*)

   (*) *Exercise 14.*  Supercomputer designs are limited by the speed
of light (and of electricity, which is nearly as fast).  Suppose a
computer has a 4.1 ns (nanosecond) clock cycle, and its cabinet is one
meter across.  Is speed of light going to be a significant factor in
its design?  *Note 14: Types Answer 14. (*)

   (*) *Exercise 15.*  Sam the Slug normally travels about five yards
in an hour.  He has obtained a supply of Power Pills; each Power Pill
he eats doubles his speed.  How many Power Pills can he swallow and
still travel legally on most US highways?  *Note 15: Types Answer 15.
(*)


File: calc.info,  Node: Algebra Tutorial,  Next: Programming Tutorial,  Prev: Types Tutorial,  Up: Tutorial

Algebra and Calculus Tutorial
=============================

This section shows how to use Calc's algebra facilities to solve
equations, do simple calculus problems, and manipulate algebraic
formulas.

* Menu:

* Basic Algebra Tutorial::
* Rewrites Tutorial::

