[comp.sources.misc] v13i039: Emacs Calculator 1.01, part 13/19

daveg@csvax.caltech.edu (David Gillespie) (06/06/90)

Posting-number: Volume 13, Issue 39
Submitted-by: daveg@csvax.caltech.edu (David Gillespie)
Archive-name: gmcalc/part13

---- Cut Here and unpack ----
#!/bin/sh
# this is part 13 of a multipart archive
# do not concatenate these parts, unpack them in order with /bin/sh
# file calc.texinfo continued
#
CurArch=13
if test ! -r s2_seq_.tmp
then echo "Please unpack part 1 first!"
     exit 1; fi
( read Scheck
  if test "$Scheck" != $CurArch
  then echo "Please unpack part $Scheck next!"
       exit 1;
  else exit 0; fi
) < s2_seq_.tmp || exit 1
echo "x - Continuing file calc.texinfo"
sed 's/^X//' << 'SHAR_EOF' >> calc.texinfo
Xyour direction of motion is -64 degrees from horizontal.  Suppose
Xwe move in the opposite direction, up and to the left:
X
X@group
X@example
X2:  -0.89879   2:  0.89879    1:  -2.0503    1:  -64.
X1:  0.43837    1:  -0.43837       .              .
X    .              .
X
X   U U           M-2 n            /             I T
X@end example
X@end group
X
XHow can the angle be the same?  The answer is that the @kbd{/} operation
Xloses information about the signs of its inputs.  Because the quotient
Xis negative, we know exactly one of the inputs was negative, but we
Xcan't tell which one.  There is an @code{arctan2} function which
Xcomputes the inverse tangent of the quotient of a pair of numbers.
XSince you feed it the two original numbers, it has enough information
Xto give you a full 360-degree answer.
X
X@group
X@example
X2:  0.89879    1:  116.       3:  116.       2:  116.       1:  180.
X1:  -0.43837       .          2:  -0.89879   1:  -64.           .
X    .                         1:  0.43837        .
X                                  .
X
X   U U          x arctan2       X M-2 n       x arctan2         -
X@end example
X@end group
X
XThe resulting angles differ by 180 degrees; in other words, they
Xpoint in opposite directions, just as we would expect.
X
XThe shift-@kbd{X} we used in the third step is the ``last-X'' command.
XIt is sort of like Undo, except that it restores the arguments of the
Xlast command to the stack without removing the command's result.  It
Xis useful in situations like we have here, where we need to do
Xseveral operations on the same inputs.  We could have accomplished
Xthe same thing by using @kbd{M-2 @key{RET}} to duplicate the top two
Xstack elements right after the @kbd{U U}, then a pair of @kbd{M-@key{TAB}}
Xcommands to cycle the 116 up around the duplicates.
X
XA similar identity is supposed to hold for hyperbolic sines and cosines,
Xexcept that it is the @emph{difference}
X@samp{cosh(@var{x})^2 - sinh(@var{x})^2} that always equals one.
XLet's try to verify this identity.@refill
X
X@group
X@example
X2:  -64        2:  -64        2:  -64        2:  9.7192e54  2:  9.7192e54
X1:  -64        1:  -3.1175e27 1:  9.7192e54  1:  -64        1:  9.7192e54
X    .              .              .              .              .
X
X 64 n RET RET      H C           2 ^            TAB           H S 2 ^
X@end example
X@end group
X
XSomething's obviously wrong, because when we subtract these numbers
Xthe answer will clearly be zero!  But if you think about it, if these
Xnumbers @emph{did} differ by one, it would be in the 55th decimal
Xplace.  The difference we seek has been lost entirely to roundoff
Xerror.
X
XWe could verify this hypothesis by doing the actual calculation with,
Xsay, 60 decimal places of precision.  This will be slow, but not
Xenormously so.  Try it if you wish; sure enough, the answer is
X0.99999, reasonably close to 1.
X
XOf course, a more reasonable way to verify the identity is to use
Xa more reasonable value for @var{x}!
X
XSome Calculator commands use the Hyperbolic prefix for other purposes.
XThe logarithm and exponential functions, for example, work to the base
X@samp{e} normally but use base-10 instead if you use the Hyperbolic
Xprefix.
X
X@group
X@example
X1:  1000       1:  6.9077     1:  1000       1:  3.
X    .              .              .              .
X
X    1000           L              U              H L
X@end example
X@end group
X
XFirst, we mistakenly compute a natural logarithm.  Then we undo
Xand compute a common logarithm instead.
X
XThe @kbd{B} key computes a general base-@var{b} logarithm for any
Xvalue of @var{b}.
X
X@group
X@example
X2:  1000       1:  3.         1:  1000.      2:  1000.      1:  6.9077
X1:  10             .              .          1:  2.71828        .
X    .                                            .
X
X 1000 RET 10       B             H E            H P             B
X@end example
X@end group
X
XHere we first use @kbd{B} to compute the base-10 logarithm, then use
Xthe ``hyperbolic'' exponential as a cheap hack to recover the number
X1000, then use @kbd{B} again to compute the natural logarithm.  Note
Xthat @kbd{P} with the hyperbolic prefix pushes the constant @samp{e}
Xonto the stack.
X
XThe Calculator also has a set of functions relating to combinatorics
Xand statistics.  You may be familiar with the @dfn{factorial} function,
Xwhich computes the product of all the integers up to a given number.
X
X@group
X@example
X1:  100        1:  93326215443...    1:  100.       1:  9.3326e157
X    .              .                     .              .
X
X    100            !                     U c f          !
X@end example
X@end group
X
XThe @kbd{c f} command converts the integer or fraction at the top
Xof the stack to floating-point format.  If you take the factorial
Xof a floating-point number, you get a floating-point result
Xaccurate to the current precision.  But if you give @kbd{!} an
Xexact integer, you get an exact integer result (158 digits long
Xin this case).
X
XIf you take the factorial of a non-integer, Calc uses the generalized
Xfactorial function defined in terms of Euler's Gamma function.
X
X@group
X@example
X3:  4.         3:  24.               1:  5.5        1:  52.342777846
X2:  4.5        2:  52.3427777846         .              .
X1:  5.         1:  120.
X    .              .
X
X                   M-3 !              M-0 DEL 5.5      x gamma
X@end example
X@end group
X
XHere we verify the identity @samp{@var{n}! = gamma(@var{n}+1)}.
X
XThe binomial coefficient @var{n}-choose-@var{m} can be defined as
X@samp{@var{n}! / @var{m}! (@var{n}-@var{m})!} for all reals @var{n} and
X@var{m}.  The intermediate results in this formula can become quite
Xlarge even if the result is small; the @kbd{k b} command computes
Xa binomial coefficient in a way that avoids large intermediate
Xvalues.
X
XThe @kbd{k} prefix key defines several common functions out of
Xcombinatorics and number theory.  Here we compute the binomial
Xcoefficient 30-choose-20, then determine its prime factorization.
X
X@group
X@example
X2:  30         1:  30045015   1:  [3, 3, 5, 7, 11, 13, 23, 29]
X1:  20             .              .
X    .
X
X 30 RET 20        k b            k f
X@end example
X@end group
X
XYou can verify these prime factors by using @kbd{v u} to ``unpack''
Xthis vector into 8 separate stack entries, then @kbd{M-8 *} to
Xmultiply them back together.  The result is the original number,
X30045015.
X
XSuppose a program you are writing needs a hash table with at least
X10000 entries.  It's best to use a prime number as the actual size
Xof a hash table.  Calc can compute the next prime number after 10000:
X
X@group
X@example
X1:  10000      1:  10007      1:  9973
X    .              .              .
X
X    10000          k n           I k n
X@end example
X@end group
X
XJust for kicks we've also computed the next prime @emph{less} than
X10000.
X
X@node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
X@section Vector/Matrix Tutorial
X
XA @dfn{vector} is a list of numbers or other Calc data objects.
XCalc provides a large set of commands that operate on vectors.  Some
Xare familiar operations from vector analysis.  Others simply treat
Xa vector as a list of objects.
X
X@menu
X* Vector Analysis Tutorial::
X* Matrix Tutorial::
X* List Tutorial::
X@end menu
X
X@node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
X@subsection Vector Analysis
X
XIf you add two vectors, the result is a vector of the sums of the
Xelements, taken pairwise.
X
X@group
X@example
X1:  [1, 2, 3]     2:  [1, 2, 3]     1:  [8, 8, 3]
X    .             1:  [7, 6, 0]         .
X                      .
X
X  [1,2,3] s 1       [7 6 0] s 2         +
X@end example
X@end group
X
XNote that we can separate the vector elements with either commas or
Xspaces.  This is true whether we are using incomplete vectors or
Xalgebraic entry.
X
XIf you multiply two vectors, the result is the sum of the products
Xof the elements taken pairwise.  This is called the @dfn{dot product}
Xof the vectors.
X
X@group
X@example
X2:  [1, 2, 3]     1:  19
X1:  [7, 6, 0]         .
X    .
X
X    r 1 r 2           *
X@end example
X@end group
X
XThe dot product of two vectors is equal to the product of their
Xlengths times the cosine of the angle between them.  (Here the vector
Xis interpreted as a line from the origin @samp{(0,0,0)} to the
Xspecified point in three-dimensional space.)  The @kbd{A}
X(absolute value) command can be used to compute the length of a
Xvector.
X
X@group
X@example
X3:  19            3:  19          1:  0.550782    1:  56.579
X2:  [1, 2, 3]     2:  3.741657        .               .
X1:  [7, 6, 0]     1:  9.219544
X    .                 .
X
X    X                 M-2 A          * /             I C
X@end example
X@end group
X
XFirst we recall the arguments to the dot product command, then
Xwe compute the absolute values of the top two stack entries to
Xobtain the lengths of the vectors, then we divide the dot product
Xby the product of the lengths to get the cosine of the angle.
XThe inverse cosine finds that the angle between the vectors
Xis about 56 degrees.
X
XThe @dfn{cross product} of two vectors is a vector whose length
Xis the product of the lengths of the inputs times the sine of the
Xangle between them, and whose direction is perpendicular to both
Xinput vectors.  Unlike the dot product, the cross product is
Xdefined only for three-dimensional vectors.  Let's double-check
Xour computation of the angle using the cross product.
X
X@group
X@example
X2:  [1, 2, 3]  3:  [-18, 21, -8]  1:  [-0.52, 0.61, -0.23]  1:  56.579
X1:  [7, 6, 0]  2:  [1, 2, 3]          .                         .
X    .          1:  [7, 6, 0]
X                   .
X
X    r 1 r 2       V C s 3 X           M-2 A * /                 A I S
X@end example
X@end group
X
XVector-related commands generally begin with the @kbd{v} prefix key.
XSome are uppercase letters and some are lowercase.  To make it easier
Xto type these commands, the shift-@kbd{V} key acts the same as the
X@kbd{v} prefix.
X
XFirst we recall the original vectors and compute their cross product,
Xwhich we also store for later reference.  Now we divide the vector
Xby the product of the lengths of the original vectors.  The length of
Xthis vector should be the sine of the angle; sure enough, it is!
X
XIf we take the dot product of two perpendicular vectors we expect
Xto get zero, since the cosine of 90 degrees is zero.  Let's check
Xthat the cross product is indeed perpendicular to both inputs:
X
X@group
X@example
X2:  [1, 2, 3]      1:  0          2:  [7, 6, 0]      1:  0
X1:  [-18, 21, -8]      .          1:  [-18, 21, -8]      .
X    .                                 .
X
X    r 1 r 3            *          DEL r 2 r 3            *
X@end example
X@end group
X
X@node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
X@subsection Matrices
X
XA @dfn{matrix} is just a vector of vectors, all the same length.
XThis means you can enter a matrix using nested brackets.  You can
Xalso use the semicolon character to enter a matrix.  We'll show
Xboth methods here:
X
X@group
X@example
X1:  [ [ 1, 2, 3 ],            1:  [ [ 1, 2, 3 ],
X      [ 4, 5, 6 ] ]                 [ 4, 5, 6 ] ]
X    .                             .
X
X  [[1 2 3] [4 5 6]]             ' [1 2 3; 4 5 6] RET
X@end example
X@end group
X
XWe'll be using this matrix again, so type @kbd{s 4} to save it now.
X
XNote that semicolons work with incomplete vectors, but they work
Xbetter in algebraic entry.  That's why we use the apostrophe in
Xthe second example.
X
XWhen two matrices are multiplied, the lefthand matrix must have
Xthe same number of columns as the righthand matrix has rows.
XRow @var{i}, column @var{j} of the result is effectively the
Xdot product of row @var{i} of the left matrix by column @var{j}
Xof the right matrix.
X
XIf we try to duplicate this matrix and multiply it by itself,
Xthe dimensions are wrong and the multiplication cannot take place:
X
X@group
X@example
X1:  [ [ 1, 2, 3 ],  * [ [ 1, 2, 3 ],
X      [ 4, 5, 6 ] ]     [ 4, 5, 6 ] ]
X    .
X
X    RET *
X@end example
X@end group
X
XThough rather hard to read, this is a formula which shows the product
Xof two matrices.  The @samp{*} function, having invalid arguments, has
Xbeen left in symbolic form.
X
XWe can multiply the matrices if we @dfn{transpose} one of them first.
X
X@group
X@example
X2:  [ [ 1, 2, 3 ],      1:  [ [ 14, 32 ],     1:  [ [ 17, 22, 27 ],
X      [ 4, 5, 6 ] ]           [ 32, 77 ] ]          [ 22, 29, 36 ],
X1:  [ [ 1, 4 ],             .                       [ 27, 36, 45 ] ]
X      [ 2, 5 ],                                   .
X      [ 3, 6 ] ]
X    .
X
X    U v t                   *                     U TAB *
X@end example
X@end group
X
XMatrix multiplication is not commutative; indeed, switching the
Xorder of the operands can even change the dimensions of the result
Xmatrix, as happened here!
X
XIf you multiply a plain vector by a matrix, it is treated as a
Xsingle row or column depending on which side of the matrix it is
Xon.  The result is a plain vector which should also be interpreted
Xas a row or column as appropriate.
X
X@group
X@example
X2:  [ [ 1, 2, 3 ],     1:  [14, 32]
X      [ 4, 5, 6 ] ]        .
X1:  [1, 2, 3]
X    .
X
X    r 4 r 1                *
X@end example
X@end group
X
XMultiplying in the other order wouldn't work because the number of
Xrows in the matrix is different from the number of elements in the
Xvector.
X
XAn @dfn{identity matrix} is a square matrix with ones along the
Xdiagonal and zeros elsewhere.  It has the property that multiplication
Xby an identity matrix, on the left or on the right, always produces
Xthe original matrix.
X
X@group
X@example
X1:  [ [ 1, 2, 3 ],     2:  [ [ 1, 2, 3 ],     1:  [ [ 1, 2, 3 ],
X      [ 4, 5, 6 ] ]          [ 4, 5, 6 ] ]          [ 4, 5, 6 ] ]
X    .                  1:  [ [ 1, 0, 0 ],         .
X                             [ 0, 1, 0 ],
X                             [ 0, 0, 1 ] ]
X                           .
X
X    r 4                    v i 3 RET              *
X@end example
X@end group
X
XIf a matrix is square, it is often possible to find its @dfn{inverse},
Xthat is, a matrix which, when multiplied by the original matrix, yields
Xan identity matrix.  The @kbd{&} (reciprocal) key also computes the
Xinverse of a matrix.
X
X@group
X@example
X1:  [ [ 1, 2, 3 ],     1:  [ [   -2.4,     1.2,   -0.2 ],
X      [ 4, 5, 6 ],           [    2.8,    -1.4,    0.4 ],
X      [ 7, 6, 0 ] ]          [ -0.73333, 0.53333, -0.2 ] ]
X    .                      .
X
X    r 4 r 2 | s 5          &
X@end example
X@end group
X
XThe vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
Xmatrices together.  Here we have used it to add a new column onto
Xour matrix to make it square.
X
XWe can multiply these two matrices in either order to get an identity.
X
X@group
X@example
X1:  [ [ 1., 0., 0. ],     1:  [ [ 1., 0., 0. ],
X      [ 0., 1., 0. ],           [ 0., 1., 0. ],
X      [ 0., 0., 1. ] ]          [ 0., 0., 1. ] ]
X    .                         .
X
X    X *                       U TAB *
X@end example
X@end group
X
XMatrix inverses are related to systems of linear equations in algebra.
XSuppose we had the following set of equations:
X
X@group
X@example
X    a + 2b + 3c = 6
X   4a + 5b + 6c = 2
X   7a + 6b      = 3
X@end example
X@end group
X
XThis can be cast into the matrix equation,
X
X@group
X@example
X   [ [ 1, 2, 3 ],    [ [ a ],    [ [ 6 ],
X     [ 4, 5, 6 ],  *   [ b ],  =   [ 2 ],
X     [ 7, 6, 0 ] ]     [ c ] ]     [ 3 ] ]
X@end example
X@end group
X
XWe can solve this system of equations by multiplying both sides by the
Xinverse of the matrix.  Calc can do this all in one step:
X
X@group
X@example
X2:  [6, 2, 3]          1:  [-12.6, 15.2, -3.93333]
X1:  [ [ 1, 2, 3 ],         .
X      [ 4, 5, 6 ],
X      [ 7, 6, 0 ] ]
X    .
X
X    [6,2,3] r 5            /
X@end example
X@end group
X
XDividing by a square matrix is equivalent to multiplying by the
Xinverse.
X
XLet's verify this solution:
X
X@example
X' -12.6 + 2*15.2 + 3*-3.93333
X@end example
X
XThe result is 6.00001, reasonably correct considering that we cheated
Xand didn't type all the digits of @samp{c}.
X
X@node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
X@subsection Vectors as Lists
X
XAlthough Calc has a number of features for manipulating vectors and
Xmatrices as mathematical objects, you can also treat vectors as
Xsimple lists of values.  For example, we saw that the @kbd{k f}
Xcommand returns a vector which is a list of the prime factors of a
Xnumber.
X
XYou can pack and unpack stack entries into vectors:
X
X@group
X@example
X3:  10         1:  [10, 20, 30]     3:  10
X2:  20             .                2:  20
X1:  30                              1:  30
X    .                                   .
X
X                M-3 v p                v u
X@end example
X@end group
X
XYou can also build vectors out of consecutive integers, or many
Xcopies of a given value:
X
X@group
X@example
X1:  [1, 2, 3, 4]    2:  [1, 2, 3, 4]    2:  [1, 2, 3, 4]
X    .               1:  17              1:  [17, 17, 17, 17]
X                        .                   .
X
X   v x 4 RET            17                 v b 4 RET
X@end example
X@end group
X
XYou can apply an operator to every element of a vector using the
X@dfn{map} command.
X
X@group
X@example
X1:  [17, 34, 51, 68]   1:  [289, 1156, 2601, 4624]  1:  [17, 34, 51, 68]
X    .                      .                            .
X
X    V M *                  2 V M ^                      V M Q
X@end example
X@end group
X
XIn the first step, we multiply the vector of integers by the vector
Xof 17's elementwise.  In the second step, we raise each element to
Xthe power two.  (The general rule is that both operands must be
Xvectors of the same length, or else one must be a vector and the
Xother a plain number.)  In the final step, we take the square root
Xof each element.
X
XYou can also @dfn{reduce} a binary operator across a vector.
XFor example, reducing @samp{*} computes the product of all the
Xelements in the vector:
X
X@group
X@example
X1:  123123     1:  [3, 7, 11, 13, 41]      1:  123123
X    .              .                           .
X
X    123123         k f                         V R *
X@end example
X@end group
X
XIn this example, we decompose 123123 into its prime factors, then
Xmultiply those factors together again to yield the original number.
X
XWe could compute a dot product ``by hand'' using mapping and
Xreduction:
X
X@group
X@example
X2:  [1, 2, 3]     1:  [7, 12, 0]     1:  19
X1:  [7, 6, 0]         .                  .
X    .
X
X    r 1 r 2           V M *              V R +
X@end example
X@end group
X
XRecalling two vectors from the previous section, we compute the
Xsum of pairwise products of the elements to get the same answer
Xfor the dot product as before.
X
XAs a larger example, let's try to fit a straight line to some data,
Xusing the method of least squares.  Suppose we have the following
Xlist of values in a file we have loaded into Emacs:
X
X@example
X  x        y
X ---      ---
X 1.34    0.234
X 1.41    0.298
X 1.49    0.402
X 1.56    0.412
X 1.64    0.466
X 1.73    0.473
X 1.82    0.601
X 1.91    0.519
X 2.01    0.603
X 2.11    0.637
X 2.22    0.645
X 2.33    0.705
X 2.45    0.917
X 2.58    1.009
X 2.71    0.971
X 2.85    1.062
X 3.00    1.148
X 3.15    1.157
X 3.32    1.354
X@end example
X
XIf you are reading this tutorial in printed form, you will find it
Xeasiest to press @kbd{i} to enter the on-line Info version of this
Xmanual and find this table there.  (Press @kbd{g}, then type
X@kbd{List Tutorial}, to jump straight to this section.)
X
XPosition the cursor at the upper-left corner of this table, right
Xto the left of the @samp{1.34}.  Press @kbd{C-@@} to set the mark.
XNow position the cursor to the lower-right, just after the @samp{1.354}.
XYou have now defined this region as an Emacs ``rectangle.''  Still
Xin the Info buffer, type @kbd{M-x calc-grab-region}.  This command
Xwill pop you back into the Calculator, with the contents of the
Xrectangle you specified in the form of a matrix.
X
X@group
X@example
X1:  [ [ 1.34, 0.234 ],
X      [ 1.41, 0.298 ],
X      @dots{}
X@end example
X@end group
X
XWe want to treat this as a pair of lists.  The first step is to
Xtranspose this matrix into a pair of rows.  Remember, a matrix is
Xjust a vector of vectors.  So we can unpack the matrix into a pair
Xof row vectors on the stack.
X
X@group
X@example
X1:  [ [ 1.34,  1.41,  1.49,  ... ],    2:  [1.34, 1.41, 1.49, ... ]
X      [ 0.234, 0.298, 0.402, ... ] ]   1:  [0.234, 0.298, 0.402, ... ]
X    .                                      .
X
X    v t                                    v u
X@end example
X@end group
X
XLet's store these in quick variables 1 and 2, respectively.
X
X@group
X@example
X1:  [1.34, 1.41, 1.49, ... ]        .
X    .
X
X    s 2 DEL                         s 1 DEL
X@end example
X@end group
X
XIn a least squares fit, the slope is given by the formula
X
X@example
X(N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
X@end example
X
X@noindent
Xwhere @samp{sum(@var{x})} represents the sum of all the values of @var{x}.
XThere is no actual @code{sum} function in Calc, but we can sum a
Xvector using a simple reduction.  First, let's compute the four
Xdifferent sums that this formula uses.
X
X@group
X@example
X1:  41.63                 1:  98.0003
X    .                         .              
X
X r 1 V R +   s 3 DEL       r 1 2 V M ^ V R +   s 4 DEL
X@end example
X@end group
X
X@group
X@example
X1:  13.613                1:  33.36554
X    .                         .
X
X r 2 V R +   s 5 DEL       r 1 r 2 V M * V R +   s 6 DEL
X@end example
X@end group
X
XThese are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
Xrespectively.  Finally, we also need @samp{N}, the number of data points.
XThis is just the length of either of our lists.
X
X@group
X@example
X1:  19
X    .
X
X r 1 v l   s 7 DEL
X@end example
X@end group
X
X(That's @kbd{v} followed by a lower-case @kbd{l}.)  Now, we just grind
Xthrough the formula:
X
X@group
X@example
X1:  633.94526  2:  633.94526  1:  67.23607
X    .          1:  566.70919      .
X                   .
X
X r 7 r 6 *      r 3 r 5 *         -
X@end example
X@end group
X
X@group
X@example
X2:  67.23607   3:  67.23607   2:  67.23607   1:  0.52141679
X1:  1862.0057  2:  1862.0057  1:  128.9488       .
X    .          1:  1733.0569      .
X                   .
X
X r 7 r 4 *      r 3 2 ^           -              /   s 8 DEL
X@end example
X@end group
X
XThat's the slope @var{m}.  The intercept @var{b} can now be found with the
Xsimple formula @samp{(sum(y) - @var{m} sum(x)) / N}.
X
X@group
X@example
X1:  13.613     2:  13.613     1:  -8.09358   1:  -0.425978
X    .          1:  21.70658       .              .
X                   .               
X
X   r 5            r 8 r 3 *       -              r 7 /   s 9
X@end example
X@end group
X
XLet's ``plot'' this straight line, @samp{@var{m} x + @var{b}}, and compare
Xit with the original data.@refill
X
X@group
X@example
X1:  [0.699, 0.735, ... ]    1:  [0.273, 0.309, ... ]
X    .                           .
X
X    r 1 r 8 *                   r 9 +
X@end example
X@end group
X
XNotice that multiplying a vector by a constant, and adding a constant
Xto a vector, can be done without mapping commands since these are
Xcommon operations from vector algebra.  As far as Calc is concerned,
Xwe've just been doing geometry in 19-dimensional space!
X
XWe can subtract this vector from our original @samp{y} vector to get
Xa feel for the error of our fit.  Let's find the maximum error:
X
X@group
X@example
X1:  [0.0387, 0.0112, ... ]   1:  [0.0387, 0.0112, ... ]   1:  0.0897
X    .                            .                            .
X
X    r 2 -                        V M A                        V R X
X@end example
X@end group
X
XFirst we compute a vector of differences, then we take the absolute
Xvalues of these differences, then we reduce the @code{max} function
Xacross the vector.  (Even though @code{max} is not normally assigned
Xa letter, so that you would have to type @kbd{x max} to get it,
Xreducing @code{max} and @code{min} is so common that @kbd{X} and
X@kbd{N} are accepted for those functions in that context.  In
Xgeneral, you answer the @kbd{V M} or @kbd{V R} prompt with the
Xactual key sequence that invokes the function you want.  You could
Xhave typed @kbd{V R x max @key{RET}} if you had preferred.)
X
XAs another example, a theorem about binomial coefficients tells
Xus that the alternating sum of binomial coefficients @var{n}-choose-0 minus
X@var{n}-choose-1 plus @var{n}-choose-2, and so on, always comes out
Xto zero.  Let's verify this for @var{n}=6.
X
X@group
X@example
X1:  [1, 2, 3, 4, 5, 6, 7]     1:  [0, 1, 2, 3, 4, 5, 6]
X    .                             .
X
X    v x 7 RET                     1 -
X@end example
X@end group
X
X@group
X@example
X1:  [1, -6, 15, -20, 15, -6, 1]          1:  0
X    .                                        .
X
X    V M ' (-1)^n choose(6,n) RET RET         V R +
X@end example
X@end group
X
XThe @kbd{V M '} command prompts you to enter any algebraic expression
Xto define the function to map over the vector.  It then prompts for
Xthe ``argument list'' for the function, which defaults to a list of
Xevery variable that appears in the formula.  In this case, the
Xdefault argument list is @samp{(n)} which is just right, so we
Xsimply press @key{RET}.  The Calculator then applies this formula
Xto each element of the vector, substituting each element's value for
X@samp{n} in turn.
X
X@node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
X@section Types Tutorial
X
XCalc understands a variety of data types as well as simple numbers.
XIn this section, we'll experiment with each of these types in turn.
X
XThe numbers we've been using so far have mainly been either @dfn{integers}
Xor @dfn{floats}.  We saw that floats are usually a good approximation to
Xthe mathematical concept of real numbers, but they are only approximations
Xand are susceptible to roundoff error.  Calc also supports @dfn{fractions},
Xwhich can exactly represent any rational number.
X
X@group
X@example
X1:  3628800    2:  3628800    1:  518400:7   1:  518414:7   1:  7:518414
X    .          1:  49             .              .              .
X                   .
X
X    10 !           49 RET         :              2 +            &
X@end example
X@end group
X
XThe @kbd{:} command divides two integers to get a fraction; @kbd{/}
Xwould normally divide integers to get a floating-point result.
XNotice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
Xsince the @kbd{:} would otherwise be interpreted as part of a
Xfraction beginning with 49.
X
XYou can convert between floating-point and fractional format using
X@kbd{c f} and @kbd{c F}:
X
X@group
X@example
X1:  1.35027217629e-5    1:  7:518414
X    .                       .
X
X    c f                     c F
X@end example
X@end group
X
XThe @kbd{c F} command replaces a floating-point number with the
X``simplest'' fraction whose floating-point representation is the
Xsame, to within the current precision.
X
X@group
X@example
X1:  3.14159265359   1:  1146408:364913   1:  3.1416   1:  355:113
X    .                   .                    .            .
X
X    P                   c F      DEL       p 5 RET P      c F
X@end example
X@end group
X
XComplex numbers can be stored in both rectangular and polar form.
X
X@group
X@example
X1:  -9     1:  (0, 3)    1:  (3; 90.)   1:  (6; 90.)   1:  (2.4495; 45.)
X    .          .             .              .              .
X
X    9 n        Q             c p            2 *            Q
X@end example
X@end group
X
XThe square root of -9 is by default rendered in rectangular form
X(@samp{0 + 3i}), but we can convert it to polar form (3 with a
Xphase angle of 90 degrees).  All the usual arithmetic and scientific
Xoperations are defined on both types of complex numbers.
X
X@dfn{HMS forms} represent a value in terms of hours, minutes, and
Xseconds.
X
X@group
X@example
X1:  2@@ 30' 0"     1:  3@@ 30' 0"     2:  3@@ 30' 0"     1:  2.
X    .                 .             1:  1@@ 45' 0."        .
X                                        .
X
X  2@@ 30' RET          1 +               RET 2 /           /
X@end example
X@end group
X
XHMS forms can also be used to hold angles in degrees, minutes, and
Xseconds.
X
X@group
X@example
X1:  0.5        1:  26.56505   1:  26@@ 33' 54.18"    1:  0.44721
X    .              .              .                     .
X
X    0.5            I T            c h                   S
X@end example
X@end group
X
XFirst we convert the inverse tangent of 0.5 to degrees-minutes-seconds
Xform, then we take the sine of that angle.  Note that the trigonometric
Xfunctions will accept HMS forms directly as input.
X
XAn @dfn{error form} represents a mean value with an attached standard
Xdeviation, or error estimate.  Suppose our measurements indicate that
Xa certain telephone pole is about 30 meters away, with an estimated
Xerror of 1 meter, and 8 meters tall, with an estimated error of 0.2
Xmeters.  What is the slope of a line from here to the top of the
Xpole, and what is the equivalent angle in degrees?
X
X@group
X@example
X1:  30 +/- 1     2:  30 +/- 1     1:  3.75 +/- 0.156   1:  75.06 +/- 0.594
X    .            1:  8 +/- 0.2        .                    .
X                     .
X
X    30 p 1           8 p .2           /                   I T
X@end example
X@end group
X
XThis means that the angle is about 75 degrees, and, assuming our
Xoriginal error estimates were valid standard deviations, there is about
Xa 60% chance that the result is correct within 0.59 degrees.
X
XAn @dfn{interval form} represents a range of values.  While an
Xerror form is best for making statistical estimates, intervals give
Xyou exact bounds on an answer.  Suppose we additionally know that
Xour telephone pole is definitely between 28 and 31 meters away,
Xand that it is between 7.7 and 8.1 meters tall.
X
X@group
X@example
X1:  [28 .. 31]  2:  [28 .. 31]    1:  [3.45 .. 4.02]  1:  [73.86 .. 76.05]
X    .           1:  [7.7 .. 8.1]      .                   .
X                    .
X
X  [ 28 .. 31 ]    [ 7.7 .. 8.1 ]      /                  I T
X@end example
X@end group
X
XIf our bounds were correct, then the angle to the top of the pole
Xis sure to lie in the range shown.
X
XThe square brackets around these intervals indicate that the endpoints
Xthemselves are allowable values.  In other words, the distance to the
Xtelephone pole is between 28 and 31, @emph{inclusive}.  You can also
Xmake an interval that is exclusive of its endpoints by writing
Xparentheses instead of square brackets.  You can even make an interval
Xwhich is inclusive (``closed'') on one end and exclusive (``open'') on
Xthe other.
X
X@group
X@example
X1:  [1 .. 10)    1:  (0.1 .. 1]   2:  (0.1 .. 1]   1:  (0.2 .. 3)
X    .                .            1:  [2 .. 3)         .
X                                      .
X
X  [ 1 .. 10 )        &              [ 2 .. 3 )         *
X@end example
X@end group
X
XThe Calculator automatically keeps track of which end values should
Xbe open and which should be closed.
X
XA @dfn{modulo form} is used for performing arithmetic modulo @var{M}.
XFor example, arithmetic involving time is generally done modulo 12
Xor 24 hours.
X
X@group
X@example
X1:  17 mod 24    1:  3 mod 24     1:  21 mod 24    1:  9 mod 24
X    .                .                .                .
X
X    17 M 24 RET      10 +             n                5 /
X@end example
X@end group
X
XIn this last step, Calc has found a new number which, when multiplied
Xby 5 modulo 24, produces the original number, 21.  If @var{M} is prime
Xit is always possible to find such a number.  For non-prime @var{M}
Xlike 24, it is only sometimes possible.
X
X@group
X@example
X1:  10 mod 24    1:  16 mod 24    1:  1000000...   1:  16
X    .                .                .                .
X
X    10 M 24 RET      100 ^            10 RET 100 ^     24 %
X@end example
X@end group
X
XThese two calculations get the same answer, but the first one is
Xmuch more efficient because it avoids the huge intermediate value
Xthat arises in the second one.
X
XThe Calc data types can't be combined in all possible ways, but it
Xis possible to use HMS forms as parts of error forms, intervals,
Xmodulo forms, or as the phase part of a polar complex number.
XFor example, the @code{calc-time} command pushes the current time
Xof day on the stack as an HMS/modulo form.
X
X@group
X@example
X1:  17@@ 34' 45" mod 24@@ 0' 0"     1:  6@@ 22' 15" mod 24@@ 0' 0"
X    .                                 .
X
X    x time RET                        n
X@end example
X@end group
X
XThis calculation tells me it is six hours and 22 minutes until midnight.
X
XAnother kind of data the Calculator can manipulate is numbers with
X@dfn{units}.  This isn't strictly a new data type; it's simply an
Xapplication of algebraic expressions, where we use variables with
Xsuggestive names like @samp{cm} and @samp{in} to represent units,
Xlike centimeters and inches.
X
X@group
X@example
X1:  2 in        1:  5.08 cm      1:  0.027778 fath   1:  0.0508 m
X    .               .                .                   .
X
X    ' 2in RET       u c cm RET       u c fath RET        u b
X@end example
X@end group
X
XWe enter the quantity ``2 inches'' (actually an algebraic expression
Xwhich means two times the variable @samp{in}), then we convert it
Xfirst to centimeters, then to fathoms, then finally to ``base'' units,
Xwhich in this case means meters.
X
X@group
X@example
X1:  9 acre     1:  3 sqrt(acre)   1:  190.84 m   1:  190.84 m + 30 cm
X    .              .                  .              .
X
X ' 9 acre RET      Q                  u s            ' $+30 cm RET
X@end example
X@end group
X
X@group
X@example
X1:  191.14 m     1:  36536.3046 m^2    1:  36536046 cm^2
X    .                .                     .
X
X    u s              2 ^                   u c cgs
X@end example
X@end group
X
XSince units expressions are really just formulas, taking the square
Xroot of @samp{acre} is undefined.  After all, @code{acre} might be an
Xalgebraic variable that you will someday assign a value.  We use the
X``units-simplify'' command to simplify the expression with variables
Xbeing interpreted as unit names.
X
XIn the final step, we have converted not to a particular unit, but to a
Xunits system.  The ``cgs'' system uses centimeters instead of meters
Xas its standard unit of length.
X
XThere are a wide variety of units defined in the Calculator.
X
X@group
X@example
X1:  55 mph     1:  88.5139 kph   1:   88.5139 km / hr   1:  8.20147e-8 c
X    .              .                  .                     .
X
X ' 55 mph RET      u c kph RET        u c km/hr RET         u c c RET
X@end example
X@end group
X
XWe express a speed first in miles per hour, then in kilometers per
Xhour, then again using a slightly more explicit notation, then
Xfinally in terms of fractions of the speed of light.
X
XTemperature conversions are a bit more tricky.  There are two ways to
Xinterpret ``20 degrees Fahrenheit''---it could mean an actual
Xtemperature, or it could mean a change in temperature.  For normal
Xunits there is no difference, but temperature units have an offset
Xas well as a scale factor and so there must be two explicit commands
Xfor them.
X
X@group
X@example
X1:  20 degF       1:  11.1111 degC     1:  -20:3 degC    1:  -6.666 degC
X    .                 .                    .                 .
X
X  ' 20 degF RET       u c degC             U u t degC        c f u s
X@end example
X@end group
X
XFirst we convert a change of 20 degrees Fahrenheit into an equivalent
Xchange in degrees Celsius (or Centigrade).  Then, we convert the
Xabsolute temperature 20 degrees Fahrenheit into Celsius.  Since
Xthis comes out as an exact fraction, we then convert to floating-point,
Xwhich in turn needs a units-simplify command to figure out that
X@code{degC} does not itself need to be converted to floating-point!
X
XTo see a complete list of built-in units, type @kbd{u v}.  Press
X@kbd{M-#} again to re-enter the Calculator when you're done looking
Xat the units table.
X
X@node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
X@section Algebra and Calculus Tutorial
X
XIf you enter a formula in algebraic mode that refers to variables,
Xthe formula itself is pushed onto the stack.  You can manipulate
Xformulas as regular data objects.
X
X@group
X@example
X1:  2 x^2 - 6       1:  6 - 2 x^2       1:  (6 - 2 x^2) (3 x^2 + y)
X    .                   .                   .
X
X    ' 2x^2-6 RET        n                   ' 3x^2+y RET *
X@end example
X@end group
X
XThere are also commands for doing common algebraic operations on
Xformulas.
X
X@group
X@example
X1:  18 x^2 + 6 y - 6 x^4 - 2 x^2 y    1:  (18 - 2 y) x^2 - 6 x^4 + 6 y
X    .                                     .
X
X    a x                                   a c x RET
X@end example
X@end group
X
XFirst we ``expand'' using the distributive law, then we ``collect''
Xterms involving powers of @samp{x}.
X
XLet's find the value of this expression when @samp{x} is 2 and @samp{y}
Xis one half.
X
X@group
X@example
X1:  17 x^2 - 6 x^4 + 3      1:  -25
X    .                           .
X
X    1:2 l y RET                 2 l x RET
X@end example
X@end group
X
XThe letter @kbd{l} means ``let''; it takes a number from the top of
Xthe stack and temporarily assigns it as the value of the variable
Xyou specify.  It then evaluates (as if by the @kbd{=} key) the
Xnext expression on the stack.  After this command, the variable goes
Xback to its original value, if any.
X
XLet's find the maximum value of our original expression when @samp{y}
Xis one half and @samp{x} ranges over all possible values.  We can
Xdo this by taking the derivative with respect to @samp{x} and examining
Xvalues of @samp{x} for which the derivative is zero.  If the second
Xderivative of the function at that value of @samp{x} is negative,
Xthe function has a local maximum there.
X
X@group
X@example
X1:  17 x^2 - 6 x^4 + 3      1:  34 x - 24 x^3
X    .                           .
X
X    U DEL  s 1                  a d x RET   s 2
X@end example
X@end group
X
XWell, the derivative is clearly zero when @samp{x} is zero.  To find
Xthe other root(s), let's divide through by @samp{x} and then solve:
X
X@group
X@example
X1:  (34 x - 24 x^3) / x    1:  34 x / x - 24 x^3 / x    1:  34 - 24 x^2
X    .                          .                            .
X
X    ' x RET /                  a x                          a s
X@end example
X@end group
X
X@group
X@example
X1:  34 - 24 x^2 = 0        1:  x = -1.19023
X    .                          .
X
X    0 a =  s 3                 a S x RET
X@end example
X@end group
X
XNotice the use of @kbd{a s} to ``simplify'' the formula.  When the
Xdefault algebraic simplifications don't do enough, you can use
X@kbd{a s} to tell Calc to spend more time on the job.
X
XNow we compute the second derivative and plug in our values of @samp{x}:
X
X@group
X@example
X2:  x            1:  -1.19023       2:  -1.19023        2:  -1.19023
X1:  -1.19023         .              1:  34 x - 24 x^3   1:  34 - 72 x^2
X    .                                   .                   .
X
X    v u              M-- M-2 DEL        r 2                 a d x RET  s 4
X@end example
X@end group
X
X@group
X@example
X2:  34 - 72 x^2  1:  -68.000000001  2:  34 - 72 x^2     1:  34
X1:  -1.19023         .              1:  0                   .
X    .                                   .
X
X    TAB              l x RET            U DEL 0             l x RET
X@end example
X@end group
X
X(The @kbd{v u} command can be used to pull apart any composite object,
Xnot just a vector.)
X
XThe first of these second derivatives is negative, so we know the function
Xhas a maximum value at @samp{x} = -1.19023.  (The function also has a
Xlocal @emph{minimum} at @samp{x} = 0.)
X
XWhen we solved for @samp{x}, we got only one value even though
X@samp{34 - 24 x^2 = 0} is a quadratic equation that ought to have
Xtwo solutions.  The reason is that @kbd{a S} normally returns a
Xsingle ``principal'' solution.  If it needs to come up with an
Xarbitrary sign (as occurs in the quadratic formula) it picks @samp{+}.
XIf it needs an arbitrary integer, it picks zero.  We can get a full
Xsolution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
X
X@group
X@example
X1:  34 - 24 x^2 = 0    1:  x = -1.19023 s1     1:  1.19023
X    .                      .                       .
X
X    r 3                    H a S x RET  s 5        1 n l s1 RET
X@end example
X@end group
X
XCalc has invented the variable @samp{s1} to represent an unknown sign;
Xit is supposed to be either @samp{+1} or @samp{-1}.  Here we have used
Xthe ``let'' command to evaluate the expression when the sign is negative.
XIf we plugged this into our second derivative we would get the same,
Xnegative, answer, so @samp{x} = 1.19023 is also a maximum.
X
XTo find the actual maximum value, we must plug our two values of @samp{x}
Xinto the original formula.
X
X@group
X@example
X2:  17 x^2 - 6 x^4 + 3    1:  24.08333 s1^2 - 12.04166 s1^4 + 3
X1:  -1.19023 s1               .
X    .
X
X  r 1 r 5 v u M-- M-2 DEL     l x RET
X@end example
X@end group
X
XIt's clear that this will have the same value for either sign of
X@samp{s1}, but let's work it out anyway, just for the exercise:
X
X@group
X@example
X2:  [-1, 1]              1:  [15.04166, 15.04166]
X1:  24.08333 s1^2 ...        .
X
X  [ 1 n , 1 ] TAB            V M $ RET
X@end example
X@end group
X
XHere we have used a vector mapping operation to evaluate the function
Xat several values of @samp{s1} at once.  @kbd{V M $} is like @kbd{V M '}
Xexcept that it takes the formula from the top of the stack.  The
Xformula is taken as a function to apply across the vector at the
Xnext-to-top stack level.  Once again, we press @key{RET} to use the
Xdefault argument list.
X
XIf there had been several different values, we could have used
X@kbd{V R X} to find the global maximum.
X
XWhat is the area under the portion of this curve from @samp{x} = 1 to 2?
XThis is simply the integral of the function:
X
X@group
X@example
X1:  17 x^2 - 6 x^4 + 3     1:  5.6666 x^3 - 1.2 x^5 + 3 x
X    .                          .
X
X    r 1                        a i x
X@end example
X@end group
X
XWe want to evaluate this at our two values for @samp{x} and subtract.
XOne way to do it is again with vector mapping and reduction:
X
X@group
X@example
X2:  [2, 1]            1:  [12.93333, 7.46666]    1:  5.46666
X1:  5.6666 x^3 ...        .                          .
X
X   [ 2 , 1 ] TAB          V M $ RET                  V R -
X@end example
X@end group
X
XCalc's integrator can do many simple integrals symbolically, but many
Xothers are beyond its capabilities.  Suppose we wish to find the area
Xunder the curve @samp{sin(x) ln(x)} over the same range of @samp{x}.  If
Xyou entered this formula and typed @kbd{a i x RET} (don't bother to try
Xthis), Calc would work for a long time but would be unable to find a
Xsolution.  In fact, there is no closed-form solution to this integral.
XNow what do we do?
X
XOne approach would be to do the integral numerically.  While there
Xis no built-in command for this in Calc, you can do it yourself
Xusing vector mapping and reduction.  This is rather slow, though,
Xsince the sine and logarithm functions take a long time.  We can
Xsave some time by reducing the working precision.
X
X@group
X@example
X1:  [1, 2, ... ]    1:  [10, 11, ... ]    1:  [1, 1.1, ... ]
X    .                   .                     .
X
X    v x 10 RET          9 +                   10 /
X@end example
X@end group
X
X@group
X@example
X2:  [1, 1.1, ... ]              1:  [0., 0.084941, 0.16993, ... ]
X1:  sin(x) ln(x)                    .
X    .
X
X    ' sin(x) ln(x) RET  s 1    m r  p 5 RET   V M $ RET
X@end example
X@end group
X
X@group
X@example
X1:  3.4195     0.34195
X    .          .
X
X    V R +      0.1 *
X@end example
X@end group
X
X(If you got wildly different results, did you remember to switch
Xto radians mode?)
X
XHere we have divided the curve into ten segments of equal width;
Xapproximating these segments as rectangular boxes (i.e., assuming
Xthe curve is nearly flat at that resolution), we compute the areas
Xof the boxes (height times width), then sum the areas.  (It is
Xfaster to sum first, then multiply by the width, since the width
Xis the same for every box.)
X
XThe true value of this integral turns out to be about 0.374, so
Xwe're not doing too well.  Let's try another approach.
X
X@group
X@example
X1:  sin(x) ln(x)    1:  0.84147 x - 0.84147 + 0.11957 (x - 1)^2 - ...
X    .                   .
X
X    r 1                 a t x=1 RET 4 RET
X@end example
X@end group
X
XHere we have computed the Taylor series expansion of the function
Xabout the point @samp{x=1}.  We can now integrate this polynomial
Xapproximation, since polynomials are easy to integrate.
X
X@group
X@example
X1:  0.42074 x^2 + ...    1:  [-0.0446, -0.42073]      1:  0.37613
X    .                        .                            .
X
X    a i x RET            [ 2 , 1 ] TAB  V M $ RET         V R -
X@end example
X@end group
X
XBetter!  By increasing the precision and/or asking for more terms
Xin the Taylor series, we can get a result as accurate as we like.
X
X@node Programming Tutorial, , Algebra Tutorial, Tutorial
X@section Programming Tutorial
X
XThe Calculator is written entirely in Emacs Lisp, a highly extensible
Xlanguage.  If you know Lisp, you can program the Calculator to do
Xanything you like.  But learning Lisp is too much trouble for simple
Xtasks, so we'll explore some of Calc's other, more down-to-earth
Xprogramming features here.
X
XThe simplest way to ``program'' Emacs is to define a @dfn{keyboard macro}.
XA keyboard macro is simply a sequence of keystrokes which Emacs has
Xstored away and can play back on demand.  For example, if you find
Xyourself typing @kbd{H a S x @key{RET}} often, you may wish to program
Xa keyboard macro to type this for you.
X
X@group
X@example
X1:  y = sqrt(x)          1:  x = y^2
X    .                        .
X
X    ' y=sqrt(x) RET       C-x ( H a S x RET C-x )
X
X1:  y = cos(x)           1:  x = s1 arccos(y) + 2 pi n1
X    .                        .
X
X    ' y=cos(x) RET           K
X@end example
X@end group
X
XWhen you type @kbd{C-x (}, Emacs begins recording.  But it is also
Xstill ready to execute your keystrokes, so you're really ``training''
XEmacs by walking it through the procedure once.  When you type
X@kbd{C-x )}, the macro is recorded.  You can now type @kbd{K} to
Xre-execute the same keystrokes.
X
XYou can give a name to your macro by typing @kbd{Z K}.
X
X@group
X@example
X1:  .              1:  y = x^4         1:  x = exp(pi i n1 / 2) y^0.25
X                       .                   .
X
X  Z K x RET            ' y=x^4 RET         z x
X@end example
X@end group
X
XNotice that we use shift-@kbd{Z} to define the command, and lower-case
X@kbd{z} to call it up.
X
XKeyboard macros can call other macros.
X
X@group
X@example
X1:  abs(x)        1:  x = s1 y                1:  2 / x    1:  x = 2 / y
X    .                 .                           .            .
X
X ' abs(x) RET   C-x ( ' y RET a = z x C-x )    ' 2/x RET       K
X@end example
X@end group
X
XIn many programs, some of the steps must execute several times.
XCalc has @dfn{looping} commands that allow this.  Loops are useful
Xinside keyboard macros, but actually work at any time.
X
X@group
X@example
X1:  x^6          2:  x^2        1: 360 x^2
X    .            1:  4             .
X                     .
X
X  ' x^6 RET          4        Z < a d x RET Z >
X@end example
X@end group
X
XHere we have computed the fourth derivative of @samp{x^6} by
Xenclosing a derivative command in a ``repeat loop'' structure.
XThis structure pops a repeat count from the stack, then
Xexecutes the body of the loop that many times.
X
XIf you make a mistake while entering the body of the loop,
Xtype @kbd{Z C-g} to cancel the loop command.
X
XHere's another example:
X
X@group
X@example
X3:  1               2:  10946
X2:  1               1:  17711
X1:  20                  .
X    .
X
X1 RET RET 20     Z < TAB C-j + Z >
X@end example
X@end group
X
XThe numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
Xnumbers, respectively.  (To see what's going on, try a few repetitions
Xof the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
Xkey if you have one, pushes a copy of the number in level 2.)
X
XA fascinating property of Fibonacci numbers is that the @var{n}th
XFibonacci number can be found directly by computing @samp{phi^n / sqrt(5)}
Xand then rounding to the nearest integer, where @samp{phi}, the
X``golden ratio,'' is @samp{(1 + sqrt(5)) / 2}.
X
X@group
X@example
X1:  1.61803         1:  24476.0000409    1:  10945.9999817    1:  10946
X    .                   .                    .                    .
X
X
X1 RET 5 Q + 2 /        21 ^                 5 Q /                 R
X@end example
X@end group
X
XA more sophisticated kind of loop is the @dfn{for} loop.  Suppose
Xwe wish to compute the 20th ``harmonic'' number, which is equal to
Xthe sum of the reciprocals of the integers from 1 to 20.
X
X@group
X@example
X3:  0               1:  3.597739
X2:  1                   .
X1:  20
X    .
X
X0 RET 1 RET 20         Z ( & + 1 Z )
X@end example
X@end group
X
XThe ``for'' loop pops two numbers, the lower and upper limit, then
Xrepeats the body of the loop as an internal counter increases from
Xthe lower limit to the upper one.  Just before executing the loop
Xbody, it pushes the current loop counter.  When the loop body
Xfinishes, it pops the ``step,'' i.e., the amount by which to
Xincrement the loop counter.  As you can see, our loop always
Xuses a step of one.
X
XThis harmonic number function uses the stack to hold the running
Xtotal as well as for the various loop housekeeping functions.  If
Xyou find this disorienting, you can sum in a variable instead:
X
X@group
X@example
X1:  0         2:  1                 .                 1:  3.597739
X    .         1:  20                                      .
X                  .
X             
X 0 s 7 DEL      1 RET 20     Z ( & s + 7 DEL 1 Z )        r 7
X@end example
X@end group
X
XNotice that we have to keep hitting @key{DEL} because the store
Xcommands don't remove the value stored from the stack.  The
Xsequence @kbd{s + 7} adds the top-of-stack into the value in
Xvariable 7.
X
XOf course, if we're going to be using variables in our programs,
Xwe have to worry about the programs clobbering values that the
Xcaller was keeping in those same variables.  This is easy to
Xfix, though:
X
X@group
X@example
X    .        1:  0.6667       1:  0.6667     3:  0.6667
X                 .                .          2:  3.597739
X                                             1:  0.6667
X                                                 .
X
X   Z `    p 4 RET 2 RET 3 /   s 7 s a RET    Z '  r 7 r a RET
X@end example
X@end group
X
XWhen we type @kbd{Z `} (that's a back-quote character), Calc saves
Xits mode settings and the contents of the ten ``quick variables''
Xfor later reference.  When we type @kbd{Z '} (that's an apostrophe
Xnow), Calc restores those saved values.  Thus the @kbd{p 4} and
X@kbd{s 7} commands have no effect outside this sequence.  Wrapping
Xthis around the body of a keyboard macro ensures that it doesn't
Xinterfere with what the user of the macro was doing.  Notice that
Xthe contents of the stack, and the values of named variables,
Xsurvive past the @kbd{Z '} command.
X
XThe @dfn{Bernoulli numbers} are a sequence with the interesting
Xproperty that all of the odd Bernoulli numbers are zero, and the
Xeven ones, while difficult to compute, can be roughly approximated
Xby the formula @samp{2 n! / (2 pi)^n}.  Let's write a keyboard
Xmacro to compute (approximate) Bernoulli numbers.
X
X@group
X@example
X1:  10               1:  0.0756823
X    .                    .
X
X    10     C-x ( RET 2 % Z [ DEL 0 Z : ' 2 $! / (2 pi)^$ RET = Z ] C-x )
X@end example
X@end group
X
XYou can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
X@kbd{Z ]} as ``end-if.''  There is no need for an explicit ``if''
Xcommand.  For the purposes of @kbd{Z [}, the condition is ``true''
Xif the value it pops from the stack is a nonzero number, or ``false''
Xif it pops zero or something that is not a number (like a formula).
XHere we take our integer argument modulo 2; this will be nonzero
Xif we're asking for an odd Bernoulli number.
X
XThe actual tenth Bernoulli number is @samp{5/66}.
X
X@group
X@example
X2:  0.0756823    1:  0          1:  0.25305    1:  0          1:  1.16659
X1:  0.0757575        .              .              .              .
X    .
X
X   5 RET 66 /   DEL DEL 11 K    DEL 12 K       DEL 13 K       DEL 14 K
X@end example
X@end group
X
XJust to exercise loops a bit more, let's compute a table of even
XBernoulli numbers.
X
X@group
X@example
X3:  []             1:  [0.10132, 0.03079, 0.02340, 0.33197, ...]
X2:  2                  .
X1:  30
X    .
X
X [ ] 2 RET 30          Z ( K | 2 Z )
X@end example
X@end group
X
XThe vertical-bar @kbd{|} is the vector-concatenation command.  When
Xwe execute it, the list we are building will be in stack level 2
X(initially this is an empty list), and the next Bernoulli number
Xwill be in level 1.  The effect is to append the Bernoulli number
Xonto the end of the list.
X
XIf you make a mistake when entering a keyboard macro, you can edit
Xit using @kbd{Z E}.  First, you must attach it to a key with @kbd{Z K}.
XOne technique is to enter a throwaway dummy definition for the macro,
Xthen enter the real one in the edit command.
X
X@group
X@example
X1:  3                   1:  17          Keyboard Macro Editor.
X    .                       .           Original keys: 1 7 RET
X
X                                        type "1\r"
X                                        type "2"
X                                        calc-plus
X
XC-x ( 1 RET 2 + C-x )    Z K h RET      Z E h
X@end example
X@end group
X
XThis shows the screen display assuming you have the @file{macedit}
Xkeyboard macro editing package installed, which is usually the case
Xsince a copy of this comes bundled with Calc.
X
XA keyboard macro is stored as a pure keystroke sequence.  The
X@file{macedit} package (invoked by @kbd{Z E}) scans along the
Xmacro and tries to decode it back into human-readable steps.
XIf a key or keys are simply shorthand for some command with a
X@kbd{M-x} name, that name is shown.  Anything that doesn't correspond
Xto a @kbd{M-x} command is written as a @samp{type} command.
X
XLet's edit in a new definition, for computing harmonic numbers.
XFirst, erase the three lines of the old definition.  Then, type
Xin the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
Xto copy it from the Info file).
X
X@example
Xcalc-kbd-push         # Save local values (Z `)
Xtype "0"              # Push a zero
Xcalc-store            # Store it in variable 1
Xtype "1"
Xcalc-pop              # Remove the zero from the stack
Xtype "1"              # Initial value for loop
Xcalc-roll-down        # This is the TAB key; swap initial & final
Xcalc-kbd-for          # Begin "for" loop...
Xcalc-inv              #   Take reciprocal
Xcalc-store            #   Add to accumulator
Xtype "+1"
Xcalc-pop              #   Remove from stack
Xtype "1"              #   Loop step is 1
Xcalc-kbd-end-for      # End "for" loop
Xcalc-recall           # Now recall final accumulated value
Xtype "1"
Xcalc-kbd-pop          # Restore values (Z ')
X@end example
X
XIf you don't know how to write a particular command in @file{macedit}
Xformat, you can always write it as keystrokes in a @code{type} command.
X
XPress @kbd{C-c C-c} to finish editing.
X
X@group
X@example
X1:  20         1:  3.597739
X    .              .
X
X    20             z h
X@end example
X@end group
X
X@iftex
X@chapter Calculator Basics
XThis chapter covers basic concepts such as the stack, algebraic and
Xnumeric entry, undo, numeric prefix arguments, etc.
X@end iftex
X
X@node Stack Basics, Numeric Entry, Introduction, Introduction
X@section Stack Basics
X
X@cindex Stack basics
XCalc uses RPN notation.  If you are not familar with RPN, @pxref{RPN
XTutorial}.
X
XTo add the numbers 1 and 2 in Calc you would type the keys:
X@kbd{1 @key{RET} 2 +}.
X(@key{RET} corresponds to the @key{ENTER} key on most calculators.)
XThe first three keystrokes ``push'' the numbers 1 and 2 onto the stack.  The
X@kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
Xand pushes the result (3) back onto the stack.  This number is ready for
Xfurther calculations:  @kbd{5 -} pushes 5 onto the stack, then pops the
X3 and 5, subtracts them, and pushes the result (-2).@refill
X
XNote that the ``top'' of the stack actually appears at the @emph{bottom}
Xof the buffer.  A line containing a single @samp{.} character signifies
Xthe end of the buffer; Calculator commands operate on the number(s)
Xdirectly above this line.  The @kbd{d t} (@code{calc-truncate-stack})
Xcommand allows you to move the @samp{.} marker up and down in the stack;
X@pxref{Truncating the Stack}.
X
X@kindex d l
X@pindex calc-line-numbering
XStack elements are numbered consecutively, with number 1 being the top of
SHAR_EOF
echo "End of part 13"
echo "File calc.texinfo is continued in part 14"
echo "14" > s2_seq_.tmp
exit 0