daveg@csvax.caltech.edu (David Gillespie) (06/06/90)
Posting-number: Volume 13, Issue 42 Submitted-by: daveg@csvax.caltech.edu (David Gillespie) Archive-name: gmcalc/part16 ---- Cut Here and unpack ---- #!/bin/sh # this is part 16 of a multipart archive # do not concatenate these parts, unpack them in order with /bin/sh # file calc.texinfo continued # CurArch=16 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 Xof an angle or complex number. If the input is an HMS form, it is interpreted Xas degrees-minutes-seconds; otherwise, the input is interpreted according Xto the current angular mode. It is best to use Radians mode when operating Xon complex numbers.@refill X X@kindex I S X@pindex calc-arcsin X@tindex arcsin XWith the Inverse flag, @code{calc-sin} computes an arcsine. This is also Xavailable as the @code{calc-arcsin} command or @code{arcsin} algebraic Xfunction. The returned argument is converted to degrees, radians, or HMS Xnotation depending on the current angular mode. X X@kindex H S X@pindex calc-sinh X@tindex sinh X@kindex H I S X@pindex calc-arcsinh X@tindex arcsinh XWith the Hyperbolic flag, @code{calc-sin} computes the hyperbolic Xsine, also available as @code{calc-sinh} [@code{sinh}]. With the XHyperbolic and Inverse flags, it computes the hyperbolic arcsine X(@code{calc-arcsinh}) [@code{arcsinh}]. X X@kindex C X@pindex calc-cos X@tindex cos X@kindex I C X@pindex calc-arccos X@tindex arccos X@kindex H C X@pindex calc-cosh X@tindex cosh X@kindex H I C X@pindex calc-arccosh X@tindex arccosh X@kindex T X@pindex calc-tan X@tindex tan X@kindex I T X@pindex calc-arctan X@tindex arctan X@kindex H T X@pindex calc-tanh X@tindex tanh X@kindex H I T X@pindex calc-arctanh X@tindex arctanh XThe shift-@kbd{C} (@code{calc-cos}) [@code{cos}] command computes the cosine Xof an angle or complex number, and shift-@kbd{T} (@code{calc-tan}) [@code{tan}] Xcomputes the tangent, along with all the various inverse and hyperbolic Xvariants of these functions. X X@pindex calc-arctan2 X@tindex arctan2 XThe @code{calc-arctan2} [@code{arctan2}] command takes two numbers from Xthe stack and computes the arc tangent of their ratio. The result is in Xthe full range from -180 (exclusive) to +180 (inclusive) degrees, or the Xanalogous range in radians. A similar result would be obtained with X@kbd{/} followed by @kbd{I T}, but the value would only be in the range Xfrom -90 to 90 degrees since the division loses information about the Xsigns of the two components, and an error might result from an explicit Xdivision by zero which @code{arctan2} would avoid. By (arbitrary) Xdefinition, @samp{arctan2(0,0)=0}. X X@pindex calc-sincos X@tindex sincos X@tindex arcsincos XThe @code{calc-sincos} [@code{sincos}] command computes the sine and Xcosine of a number, returning them as a vector of the form X@samp{[@var{cos}, @var{sin}]}. XWith the Inverse flag [@code{arcsincos}], this command takes a two-element Xvector as an argument and computes @code{arctan2} of the elements. X(This command does not accept the Hyperbolic flag.)@refill X X@node Branch Cuts, Random Numbers, Trigonometric and Hyperbolic Functions, Scientific Functions X@section Branch Cuts and Principal Values X X@cindex Branch cuts X@cindex Principal values XAll of the logarithmic, trigonometric, and hyperbolic functions are defined Xfor complex numbers as well as for reals. This section describes the values Xreturned in cases where the general result is a family of possible values. XCalc follows section 12.5.3 of Steele's @cite{Common Lisp, the Language} in Xthese matters. This section will describe each function briefly; for a Xmore detailed discussion, consult Steele's book. Except as noted below, Xthese branch cuts also exactly match those implemented by the HP-28C Xcalculator. X XNote: The current implementations of these functions with complex arguments Xare designed with proper behavior around the branch cuts in mind, @emph{not} Xefficiency or accuracy. You may need to increase the floating precision Xand wait a while to get suitable answers from them. X XFor @samp{sqrt(a+bi)}: When @samp{a<0} and @samp{b} is small but positive Xor zero, the result is close to the @samp{+i} axis. For @samp{b} small and Xnegative, the result is close to the @samp{-i} axis. The result always lies Xin the right half of the complex plane. X XFor @samp{ln(a+bi)}: The real part is defined as @samp{ln(abs(a+bi))}. XThe imaginary part is defined as @samp{arg(a+bi) = arctan2(b,a)}. X XFor @samp{z1^z2}: This is defined by @samp{exp(ln(z1)*z2)}. X XFor @samp{arcsin(z)}: This is defined by @samp{-i*ln(i*z + sqrt(1-z^2))}. X XFor @samp{arccos(z)}: This is defined by @samp{-i*ln(z + i*sqrt(1-z^2))}, Xor equivalently by @samp{pi/2 - arcsin(z)}. X XFor @samp{arctan(z)}: This is defined by X@samp{-i*ln((1+i*z) * sqrt(1/(1+z^2)))}. The HP-28C differs in that the Xbranch cuts are continuous on the opposite sides.@refill X XFor @samp{arcsinh(z)}: This is defined by @samp{ln(z + sqrt(1+z^2))}. X XFor @samp{arccosh(z)}: This is defined by X@samp{ln(z + (z+1)*sqrt((z-1)/(z+1)))}. X XFor @samp{arctanh(z)}: This is defined by @samp{ln((1+z) * sqrt(1/(1-z^2)))}. XAgain this differs from the HP-28C in that the values exactly on the branch Xcuts are continuous with the opposite sides. X X@node Random Numbers, Combinatorial Functions, Branch Cuts, Scientific Functions X@section Random Numbers X X@kindex k r X@pindex calc-random X@tindex random XThe @kbd{k r} (@code{calc-random}) [@code{random}] command produces Xrandom numbers of various sorts. X XGiven a positive numeric prefix argument @samp{M}, it produces a random Xinteger @samp{N} in the range @samp{0 <= N < M}. Each of the @samp{M} Xvalues appears with equal probability.@refill X XWith no numeric prefix argument, the @kbd{k r} command takes its argument Xfrom the stack instead. Once again, if this is a positive integer @samp{M} Xthe result is a random integer less than @samp{M}. However, note that Xwhile numeric prefix arguments are limited to six digits or so, an @samp{M} Xtaken from the stack can be arbitrarily large. X XIf the value on the stack is a real number @samp{M}, the result is a Xrandom real number @samp{N} in the range @samp{0 <= N < M} or X@samp{M < N <= 0}, according to the sign of @samp{M}. X XIf @samp{M} is zero, the result is a Gaussian-distributed random real Xnumber; the distribution has a mean of zero and a variance of one. XThe algorithm used generates random numbers in pairs; thus, every other Xcall to this function will be especially fast. X XIf @samp{M} is an interval form, the lower and upper bounds specify the Xacceptable limits of the random numbers. If both bounds are integers, Xthe result is a random integer in the specified range. If either bound Xis floating-point, the result is a random real number in the specified Xrange. X X@pindex calc-rrandom XThe @code{calc-rrandom} command produces a random real number between Xzero and one. It is equivalent to @samp{random(1.0)}. X X@kindex k a X@pindex calc-random-again XThe @kbd{k a} (@code{calc-random-again}) command produces another random Xnumber, re-using the most recent value of @samp{M}. X X@node Combinatorial Functions, , Random Numbers, Scientific Functions X@section Combinatorial Functions X XCommands relating to combinatorics and number theory begin with the X@kbd{k} key prefix. X X@kindex k g X@pindex calc-gcd X@tindex gcd XThe @kbd{k g} (@code{calc-gcd}) [@code{gcd}] command computes the XGreatest Common Divisor of two integers. (For non-integer arguments the Xoperation is left in symbolic form.)@refill X X@kindex k l X@pindex calc-lcm X@tindex lcm XThe @kbd{k l} (@code{calc-lcm}) [@code{lcm}] command computes the XLeast Common Multiple of two integers. The product of the LCM and GCD Xof two integers is equal to the product of the integers.@refill X X@kindex k G X@pindex calc-extended-gcd X@tindex egcd XThe @kbd{k G} (@code{calc-extended-gcd}) [@code{egcd}] command computes Xthe GCD of two integers @samp{x} and @samp{y} and returns a vector X@samp{[g, a, b]} where @samp{g = gcd(x,y) = a x + b y}. X X@kindex ! X@pindex calc-factorial X@tindex fact XThe @kbd{!} (@code{calc-factorial}) [@code{fact}] command computes the Xfactorial of the number at the top of the stack. If the number is an Xinteger, the result is an exact integer. If the number is an Xinteger-valued float, the result is a floating-point approximation. If Xthe number is a non-integral real number, the generalized factorial is used, Xas defined by the Euler Gamma function. Please note that computation of Xlarge factorials can be slow; using floating-point format will help Xsince fewer digits must be maintained.@refill X X@pindex calc-gamma X@tindex gamma XThe @code{calc-gamma} [@code{gamma}] command computes the Euler Gamma Xfunction explicitly, according to the rule @samp{gamma(x+1) = fact(x)}. X X@kindex k d X@pindex calc-double-factorial X@tindex dfact XThe @kbd{k d} (@code{calc-double-factorial}) [@code{dfact}] command Xcomputes the ``double factorial'' of an integer. For an even integer, Xthis is the product of even integers from 2 to @samp{N}. For an odd Xinteger, this is the product of odd integers from 3 to @samp{N}. If Xthe argument is an integer-valued float, the result is a floating-point Xapproximation.@refill X X@kindex k b X@pindex calc-choose X@tindex choose XThe @kbd{k b} (@code{calc-choose}) [@code{choose}] command computes the Xbinomial coefficient @samp{N}-choose-@samp{M}, where @samp{M} is the number Xon the top of the stack and @samp{N} is second-to-top. If both arguments Xare integers, the result is an exact integer. Otherwise, the result is a Xfloating-point approximation. The binomial coefficient is defined for all Xreal numbers by @samp{N! / M! (N-M)!}. X X@kindex H k b X@pindex calc-perm X@tindex perm XThe @kbd{H k b} (@code{calc-perm}) [@code{perm}] command computes the Xnumber-of-permutations function @samp{N! / M!}. X X@kindex k p X@pindex calc-prime-test X@cindex Primes XThe @kbd{k p} (@code{calc-prime-test}) command checks if the integer on Xthe top of the stack is prime. For integers less than eight million, the Xanswer is always exact and reasonably fast. For larger integers, a Xprobabilistic method is used (See Knuth vol. II, section 4.5.4, algorithm P). XThe number is first checked against small prime factors (up to 13). Then, Xany number of iterations of the algorithm are performed. Each step either Xdiscovers that the number is non-prime, or substantially increases the Xcertainty that the number is prime. After a few steps, the chance that Xa number was mistakenly described as prime will be less than one percent. X(Indeed, this is the worst case; in practice even a single iteration is Xquite reliable.) After the @kbd{k p} command, the number will be reported Xas definitely prime or non-prime if possible, or otherwise ``probably'' Xprime with a certain probability of error. X XThe normal @kbd{k p} command performs one iteration of the primality Xtest. Pressing @kbd{k p} repeatedly for the same integer will perform Xadditional iterations. Also, @kbd{k p} with a numeric prefix performs Xthe specified number of iterations. X X@kindex k f X@pindex calc-prime-factors X@tindex prfac XThe @kbd{k f} (@code{calc-prime-factors}) [@code{prfac}] command Xattempts to decompose an integer into its prime factors. For numbers up Xto 25 million, the answer is exact although it may take some time. The Xresult is a vector of the prime factors in increasing order. For larger Xinputs, prime factors above 5000 may not be found, in which case the Xlast number in the vector will be an unfactored integer greater than 25 Xmillion. X X@kindex k n X@pindex calc-next-prime X@tindex nextprime XThe @kbd{k n} (@code{calc-next-prime}) [@code{nextprime}] command finds Xthe next prime above a given number. Essentially, it searches by calling X@code{calc-prime-test} on successive integers until it finds one that Xpasses the test. This is quite fast for integers less than eight million, Xbut once the probabilistic test comes into play the search may be rather Xslow. Ordinarily this command stops for any prime that passes one iteration Xof the primality test. With a numeric prefix argument, a number must pass Xthe specified number of iterations before the search stops. (This only Xmatters when searching above eight million.) You can always use additional X@kbd{k p} commands to increase your certainty that the number is indeed Xprime. X X@kindex I k n X@pindex calc-prev-prime X@tindex prevprime XThe @kbd{I k n} (@code{calc-prev-prime}) [@code{prevprime}] command Xanalogously finds the next prime less than a given number. X X@kindex k t X@pindex calc-totient X@tindex totient XThe @kbd{k t} (@code{calc-totient}) [@code{totient}] command computes the XEuler ``totient'' function, the number of integers less than @samp{n} which Xare relatively prime to @samp{n}. X X@kindex k m X@pindex calc-moebius X@tindex moebius XThe @kbd{k m} (@code{calc-moebius}) [@code{moebius}] command computes the XMoebius ``mu'' function. If the input number is a product of @samp{k} Xdistinct factors, this is @samp{(-1)^k}. If the input number has any Xduplicate factors (i.e., can be divided by the same prime more than once), Xthe result is zero. X X@node Binary Functions, Matrix Functions, Scientific Functions, Top X@chapter Binary Number Functions X XThe commands in this chapter all use two-letter sequences beginning with Xthe @kbd{b} prefix. X X@cindex Binary numbers XThe ``binary'' operations actually work regardless of the currently Xdisplayed radix, although their results make the most sense in a radix Xlike 2, 8, or 16 (as obtained by the @kbd{d 2}, @kbd{d 8}, or @kbd{d 6} Xcommands, respectively). You may also wish to enable display of leading Xzeros with @kbd{d z}. @xref{Radix Modes}. X X@cindex Word size for binary operations XThe Calculator maintains a current @dfn{word size} @samp{w}, an Xarbitrary positive or negative integer. For a positive word size, all Xof the binary operations described here operate modulo @samp{2^w}. In Xparticular, negative arguments are converted to positive integers modulo X@samp{2^w} by all binary functions.@refill X XIf the word size is negative, binary operations produce 2's complement Xintegers from @samp{-(2^(-w-1))} to @samp{2^(-w-1)-1} inclusive. Either Xmode accepts inputs in any range; the sign of @samp{w} affects only Xthe results produced. X X@kindex b c X@pindex calc-clip X@tindex clip XThe @kbd{b c} (@code{calc-clip}) X[@code{clip}] command can be used to clip a number by reducing it modulo X@samp{2^w}. The commands described in this chapter automatically clip Xtheir results to the current word size. Note that other operations like Xaddition do not use the current word size, since integer addition Xgenerally is not ``binary.'' (However, @pxref{Simplification Modes}, X@code{calc-bin-simplify-mode}.)@refill X X@kindex b w X@pindex calc-word-size XThe default word size is 32 bits. All operations except the shifts and Xrotates allow you to specify a different word size for that one Xoperation by giving a numeric prefix argument: @kbd{C-u 8 b c} clips the Xtop of stack to the range 0 to 255 regardless of the current word size. XTo set the word size permanently, use @kbd{b w} (@code{calc-word-size}). XBy default this command displays the current word size; with a numeric Xprefix, it sets the word size to that value. X XWhen the binary operations are written in symbolic form, they take an Xoptional second (or third) word-size parameter. When a formula like X@samp{and(a,b)} is finally evaluated, the word size current at that time Xwill be used, but when @samp{and(a,b,-8)} is evaluated, a word size of -8 Xwill always be used. A symbolic binary function will be left in symbolic Xform unless the all of its argument(s) are integers or integer-valued floats. X XIf either or both arguments are modulo forms for which @samp{M} is a Xpower of two, that power of two is taken as the word size unless a Xnumeric prefix argument overrides it. The current word size is never Xconsulted when modulo-power-of-two forms are involved. X X@kindex b a X@pindex calc-and X@tindex and XThe @kbd{b a} (@code{calc-and}) [@code{and}] command computes the bitwise XAND of the two numbers on the top of the stack. In other words, for each Xof the @samp{w} binary digits of the two numbers (pairwise), the corresponding Xbit of the result is 1 if and only if both input bits are 1. X X@kindex b o X@pindex calc-or X@tindex or XThe @kbd{b o} (@code{calc-or}) [@code{or}] command computes the bitwise Xinclusive OR of two numbers. A bit is 1 if either of the input bits, or Xboth, are 1. X X@kindex b x X@pindex calc-xor X@tindex xor XThe @kbd{b x} (@code{calc-xor}) [@code{xor}] command computes the bitwise Xexclusive OR of two numbers. A bit is 1 if exactly one of the input bits Xis 1. X X@kindex b d X@pindex calc-diff X@tindex diff XThe @kbd{b d} (@code{calc-diff}) [@code{diff}] command computes the bitwise Xdifference of two numbers; this is defined by @samp{diff(a,b) = and(a,not(b))}. X X@kindex b n X@pindex calc-not X@tindex not XThe @kbd{b n} (@code{calc-not}) [@code{not}] command computes the bitwise XNOT of a number. A bit is 1 if the input bit is 0 and vice-versa. X X@kindex b l X@pindex calc-lshift-binary X@tindex lsh XThe @kbd{b l} (@code{calc-lshift-binary}) [@code{lsh}] command shifts a Xnumber left by one bit, or by the number of bits specified in the numeric Xprefix argument. A negative prefix argument performs a logical right shift, Xin which zeros are shifted in on the left. In symbolic form, @samp{lsh(a)} Xis short for @samp{lsh(a,1)}, which in turn is short for @samp{lsh(a,n,w)}. XBits shifted ``off the end,'' according to the current word size, are lost. X X@kindex b r X@pindex calc-rshift-binary X@tindex rsh XThe @kbd{b r} (@code{calc-rshift-binary}) [@code{rsh}] command shifts a Xnumber right by one bit, or by the number of bits specified in the numeric Xprefix argument: @samp{rsh(a,n) = lsh(a,-n)}. X X@kindex b s X@pindex calc-shift-binary X@tindex ash XThe @kbd{b s} (@code{calc-shift-binary}) [@code{ash}] command shifts a Xnumber left in the same way as @code{lsh}. However, if shifting right, Xit performs an ``arithmetic'' shift, in which the leftmost bit (according Xto the current word size) is duplicated rather than shifting in zeros. XThis corresponds to dividing by two where the input is interpreted as a Xsigned, twos-complement number. (The distinction between the @samp{lsh} Xand @samp{ash} operations is totally independent from whether the word Xsize is positive or negative.) X X@kindex b R X@pindex calc-rotate-binary X@tindex rot XThe @kbd{b R} (@code{calc-rotate-binary}) [@code{rot}] command rotates a Xnumber one bit to the left. The leftmost bit (according to the current Xword size) is dropped off the left and shifted in on the right. With a Xnumeric prefix argument, the number is rotated the specified number of Xbits to the left or right. X X@node Matrix Functions, Algebra, Binary Functions, Top X@chapter Vector and Matrix Functions X XMany of the commands described here begin with the @kbd{v} prefix. X(For convenience, the shift-@kbd{V} prefix is equivalent to @kbd{v}.) XThe commands usually apply to both plain vectors and matrices; some Xapply only to matrices or only to square matrices. If the argument Xhas the wrong dimensions the operation is left in symbolic form. X X@menu X* Building Vectors:: X* Extracting Elements:: X* Vector and Matrix Arithmetic:: X* Reducing and Mapping:: X* Vector and Matrix Formats:: X@end menu X X@node Building Vectors, Extracting Elements, Matrix Functions, Matrix Functions X@section Building Vectors X XVectors are entered and displayed using @samp{[a,b,c]} notation. XMatrices are vectors of which all elements are vectors of equal length. X(Though none of the standard Calc commands use this concept, a Xthree-dimensional matrix or rank-3 tensor could be defined as a Xvector of matrices, and so on.) Vectors and matrices can be added, Xsubtracted, multiplied, and divided; @pxref{Basic Arithmetic}.@refill X X@kindex | X@pindex calc-concat XThe @kbd{|} (@code{calc-concat}) command ``concatenates'' two vectors Xtogether. For example, after @kbd{[ 1 , 2 ] [ 3 , 4 ] |}, the stack Xwill contain the single vector @samp{[1, 2, 3, 4]}. If the arguments Xare matrices, the rows of the first matrix are concatenated with the Xrows of the second. (In other words, two matrices are just two vectors of Xrow-vectors as far as @code{calc-concat} is concerned.) X XIf either argument to @kbd{|} is a scalar (a non-vector), it is treated Xlike a one-element vector for purposes of concatenation: @kbd{1 [ 2 , 3 ] |} Xproduces the vector @samp{[1, 2, 3]}. Likewise, if one argument is a Xmatrix and the other is a plain vector, the vector is treated as a Xone-row matrix. X X@kindex v p (vectors) X@pindex calc-pack (vectors) XThe @kbd{v p} (@code{calc-pack}) command collects several elements from Xthe stack into a matrix, complex number, HMS form, or error form. XBy itself, it collects two Xstack elements into a complex number according to the current Polar XMode. With a numeric prefix argument of -1 or -2, it builds a Xrectangular or polar number (respectively) regardless of the polar mode. XWith an argument of -3 it builds an HMS form from the top three elements Xon the stack. With an argument of -4 it builds an error form from the Xtop two elements on the stack. With an argument of -5 it builds a Xmodulo form. XWith a positive numeric prefix, it collects the specified number of Xstack elements into a vector.@refill X XThe same effect can be had by pressing @kbd{[} or @kbd{(} to push an Xincomplete vector or complex number on the stack, using @code{calc-roll-down} Xto sneak the incomplete object up past a certain number of elements, and Xthen pressing the matching @kbd{]} or @kbd{)}. X X@kindex v u (vectors) X@pindex calc-unpack (vectors) XThe @kbd{v u} (@code{calc-unpack}) command takes the vector, complex Xnumber, HMS form, or other composite object on the top of the stack and X``unpacks'' it, pushing each of its elements onto the stack as separate Xobjects. Thus, it is the ``inverse'' of @code{calc-pack}. If the value Xat the top of the stack is a formula, @code{calc-unpack} unpacks it by Xpushing each of the arguments of the top-level operator onto the stack. X X@kindex v d X@pindex calc-diag X@tindex diag XThe @kbd{v d} (@code{calc-diag}) [@code{diag}] function builds a diagonal Xsquare matrix. The optional numeric prefix gives the number of rows Xand columns in the matrix. If the value at the top of the stack is a Xvector, the elements of the vector are used as the diagonal elements; the Xprefix, if specified, must match the size of the vector. If the value on Xthe stack is a scalar, it is used for each element on the diagonal, and Xthe prefix argument is required. X XTo build a constant square matrix, e.g., a 3x3 matrix filled with ones, Xuse @kbd{0 M-3 v d 1 +}, i.e., build a zero matrix first and then add a Xconstant value to that matrix. (Another alternative would be to use X@code{calc-build-vector} and @code{calc-arrange-vector}; see below.) X X@kindex v i X@pindex calc-ident XThe @kbd{v i} (@code{calc-ident}) function builds an identity matrix of Xthe specified size. It is a convenient form of @code{calc-diag} where the Xdiagonal element is always one. X X@kindex v x X@pindex calc-index X@tindex index XThe @kbd{v x} (@code{calc-index}) [@code{index}] function builds a vector Xof consecutive integers from 1 to @var{n}, where @var{n} is the numeric Xprefix argument. If you do not provide a prefix argument, you will be Xprompted to enter a suitable number. X X@kindex v b X@pindex calc-build-vector X@tindex cvec XThe @kbd{v b} (@code{calc-build-vector}) [@code{cvec}] function builds a Xvector of @var{n} copies of the value on the top of the stack, where @var{n} Xis the numeric prefix argument. In algebraic formulas, @samp{cvec(x,n,m)} Xcan also be used to build an @var{n}-by-@var{m} matrix of copies of @var{x}. X X@kindex v a X@pindex calc-arrange-vector X@tindex arrange X@cindex Arranging a matrix X@cindex Reshaping a matrix X@cindex Flattening a matrix XThe @kbd{v a} (@code{calc-arrange-vector}) [@code{arrange}] function Xrearranges a vector to have a certain number of columns and rows. The Xnumeric prefix argument specifies the number of columns; if you do not Xprovide an argument, you will be prompted for the number of columns. XThe vector or matrix on the top of the stack is @dfn{flattened} into a Xplain vector. If the number of columns is nonzero, this vector is Xthen formed into a matrix by taking successive groups of @var{n} elements. XIf the number of columns does not evenly divide the number of elements Xin the vector, the last row will be short and the result will not be Xsuitable for use as a matrix. For example, with the matrix X@samp{[[1, 2], [3, 4]]} on the stack, @kbd{v a 4} produces X@samp{[[1, 2, 3, 4]]} (a 1x4 matrix), @kbd{v a 1} produces X@samp{[[1], [2], [3], [4]]} (a 4x1 matrix), @kbd{v a 2} produces X@samp{[[1, 2], [3, 4]]} (the original 2x2 matrix), @kbd{v a 3} produces X@samp{[[1, 2, 3], [4]]} (not a matrix), and @kbd{v a 0} produces Xthe flattened list @samp{[1, 2, 3, 4]}. X X@kindex v s X@kindex I v s X@pindex calc-sort X@tindex sort X@tindex rsort XThe @kbd{v s} (@code{calc-sort}) [@code{sort}] function sorts the elements of Xa vector into increasing order. Non-real vector elements are sorted Xaccording to a kind of lexicographic ordering. The @kbd{I v s} [@code{rsort}] Xfunction sorts a vector into decreasing order. X X@kindex v h X@pindex calc-histogram XThe @kbd{v h} (@code{calc-histogram}) [@code{histogram}] function builds a Xhistogram of a vector of numbers. Vector elements are assumed to be Xintegers or real numbers in the range [0..@var{n}) for some ``number of Xbins'' @var{n}, which is the numeric prefix argument given to the Xcommand. The result is a vector of @var{n} counts of how many times Xeach value appeared in the original vector. Non-integers in the input Xare rounded down to integers. Any vector elements outside the specified Xrange are ignored. (You can tell if elements have been ignored by checking Xthat the elements in the result vector add up to the length of the input Xvector.) X XWith the Hyperbolic flag, @kbd{v h} pulls two vectors from the stack. XThe second-to-top vector is the list of numbers as before. The top Xvector is an equal-sized list of ``weights'' to attach to the elements Xof the data vector. For example, if the first data element is 4.2 and Xthe first weight is 10, then 10 will be added to bin 4 of the result Xvector. Without the hyperbolic flag, every element has a weight of one. X X@node Extracting Elements, Vector and Matrix Arithmetic, Building Vectors, Matrix Functions X@section Extracting Vector and Matrix Elements X X@kindex v r X@pindex calc-mrow X@tindex mrow XThe @kbd{v r} (@code{calc-mrow}) [@code{mrow}] command extracts one row of Xthe matrix on the top of the stack, or one element of the plain vector on Xthe top of the stack. The row or element is specified by the numeric Xprefix argument; the default is to prompt for the row or element number. XThe matrix or vector is replaced by the specified row or element in the Xform of a vector or scalar, respectively. X X@tindex mrrow XGiven a negative prefix argument, @kbd{v r} instead deletes one row or Xelement from the matrix or vector on the top of the stack. Thus X@kbd{C-u 2 v r} replaces a matrix with its second row, but @kbd{C-u -2 v r} Xreplaces the matrix with the same matrix with its second row removed. XIn algebraic form this function is called @code{mrrow}. X X@tindex getdiag XGiven a prefix argument of zero, @kbd{v r} extracts the diagonal elements Xof a square matrix in the form of a vector. In algebraic form this Xfunction is called @code{getdiag}. X X@kindex v c X@pindex calc-mcol X@tindex mcol X@tindex mrcol XThe @kbd{v c} (@code{calc-mcol}) [@code{mcol} or @code{mrcol}] command is Xthe analogous operation on columns of a matrix. Given a plain vector Xit extracts (or removes) one element, just like @kbd{v r}.@refill X XTo extract a matrix element at a given row and column, use @kbd{v r} to Xextract the row as a vector, then @kbd{v c} to extract the column element Xfrom that vector. X X@kindex v l X@pindex calc-vlength X@tindex vlen XThe @kbd{v l} (@code{calc-vlength}) [@code{vlen}] command computes the Xlength of a vector. The length of a non-vector is considered to be zero. XNote that matrices are just vectors of vectors for the purposes of this Xcommand.@refill X X@node Vector and Matrix Arithmetic, Reducing and Mapping, Extracting Elements, Matrix Functions X@section Vector and Matrix Arithmetic X XBasic arithmetic operations like addition and multiplication are defined Xfor vectors and matrices as well as for numbers. Division of matrices, in Xthe sense of multiplying by the inverse, is supported. (Division by a Xmatrix actually uses LU-decomposition for greater accuracy and speed.) X@xref{Basic Arithmetic}. X XThe following functions are applied element-wise if their arguments are Xvectors or matrices: @code{change-sign}, @code{conj}, @code{arg}, X@code{re}, @code{im}, @code{polar}, @code{rect}, @code{clean}, X@code{float}, @code{frac}. @xref{Function Index}.@refill X X@kindex v t X@pindex calc-transpose X@tindex trn XThe @kbd{v t} (@code{calc-transpose}) [@code{trn}] command computes Xthe transpose of the matrix at the top of the stack. If the argument Xis a plain vector, it is treated as a row vector and transposed into Xa one-column matrix. X X@kindex V J X@pindex calc-conj-transpose XThe @kbd{V J} (@code{calc-conj-transpose}) [@code{ctrn}] command computes Xthe conjugate transpose of its argument, i.e., @samp{conj(trn(x))}. X X@kindex A (vectors) X@pindex calc-abs (vectors) X@tindex abs (vectors) XThe @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the XFrobenius norm of a vector or matrix argument. This is the square Xroot of the sum of the squares of the absolute values of the Xelements of the vector or matrix.@refill X X@kindex v n X@pindex calc-rnorm X@tindex rnorm XThe @kbd{v n} (@code{calc-rnorm}) [@code{rnorm}] command computes Xthe row norm, or infinity-norm, of a vector or matrix. For a plain Xvector, this is the maximum of the absolute values of the elements. XFor a matrix, this is the maximum of the row-absolute-value-sums, Xi.e., of the sums of the absolute values of the elements along the Xvarious rows. X X@kindex V N X@pindex calc-cnorm X@tindex cnorm XThe @kbd{V N} (@code{calc-cnorm}) [@code{cnorm}] command computes Xthe column norm, or one-norm, of a vector or matrix. For a plain Xvector, this is the sum of the absolute values of the elements. XFor a matrix, this is the maximum of the column-absolute-value-sums. XGeneral @samp{k}-norms for @samp{k} other than one or infinity are Xnot provided. X X@kindex V C X@pindex calc-cross X@tindex cross XThe @kbd{V C} (@code{calc-cross}) [@code{cross}] command computes the Xright-handed cross product of two vectors, each of which must have Xexactly three elements. X X@kindex V I X@pindex calc-inv X@tindex inv XThe @kbd{V I} (@code{calc-inv}) [@code{inv}] command computes the Xinverse of a square matrix. If the matrix is singular, the inverse Xoperation is left in symbolic form. Matrix inverses are recorded so Xthat once an inverse (or determinant) of a particular matrix has been Xcomputed, the inverse and determinant of the matrix can be recomputed Xquickly in the future. X XIf the argument to @kbd{V I} is a plain number @samp{x}, this Xcommand simply computes @samp{1/x}. The same operation is also Xavailable on the @kbd{&} key. X X@kindex V D X@pindex calc-mdet X@tindex det XThe @kbd{V D} (@code{calc-mdet}) [@code{det}] command computes the Xdeterminant of a square matrix. X X@kindex V L X@pindex calc-mlud X@tindex lud XThe @kbd{V L} (@code{calc-mlud}) [@code{lud}] command computes the XLU decomposition of a matrix. The result is a list of three matrices Xwhich, when multiplied together left-to-right, form the original matrix. XThe first is a permutation matrix that arises from pivoting in the Xalgorithm, the second is lower-triangular with ones on the diagonal, Xand the third is upper-triangular. X X@kindex V T X@pindex calc-mtrace X@tindex tr XThe @kbd{V T} (@code{calc-mtrace}) [@code{tr}] command computes the Xtrace of a square matrix. This is defined as the sum of the diagonal Xelements of the matrix. X X@node Reducing and Mapping, Vector and Matrix Formats, Vector and Matrix Arithmetic, Matrix Functions X@section Reducing and Mapping Vectors X XThe commands in this section allow for more general operations on the Xelements of vectors. X X@kindex V A X@pindex calc-apply X@tindex apply XThe @kbd{V A} (@code{calc-apply}) command applies a given operator to Xthe elements of a vector. For example, applying the hypothetical Xfunction @code{f} to the vector @samp{[1, 2, 3]} would produce the Xfunction call @samp{f(1, 2, 3)}. Applying the @code{+} function to the Xvector @samp{[a, b]} produces @samp{a + b}. Applying @code{+} to Xthe vector @samp{[a, b, c]} is an error, since the @code{+} function Xaccepts exactly two arguments. (While @code{calc-apply} is useful in Xsome cases, you will usually find that @code{calc-reduce} or @code{calc-map}, Xdescribed below, are closer to what you want.) X XThe @kbd{V A} command prompts you to press the key corresponding to the Xdesired operator. Press @kbd{?} for a list of all available operators. XOr, press @samp{x} at the operator prompt to select any algebraic Xfunction by name to use as the operator. This can include functions you Xhave defined yourself using the @kbd{Z F} command. (@xref{Algebraic XDefinitions}.) If you give a name for which no function has been Xdefined, the result is left in symbolic form, as in @samp{f(1, 2, X3)}.@refill X XIt is also possible to apply any formula to a vector by treating that Xformula as a function. When prompted for the operator to use, press X@kbd{'} (the apostrophe) and type your formula as an algebraic entry. XYou will then be prompted for the argument list, which defaults to a Xlist of all variables that appear in the formula, sorted into alphabetic Xorder. For example, suppose you enter the formula @samp{x + 2y^x}. XThe default argument list would be @samp{(x y)}, which means that if Xthis function is applied to the arguments @samp{[3, 10]}, the result would Xbe @samp{3 + 2*10^3}. If you plan to use a certain formula in this Xway often, you might consider defining it as a function with @kbd{Z F}. X XIf you press @kbd{$} at the operator prompt, the effect is similar to Xthe apostrophe except that the relevant formula is taken from top-of-stack Xinstead. The actual vector argument of the @code{calc-apply} command is Xthen taken from the second-to-top stack position. You will still be Xprompted for an argument list. X X@cindex Generic functions X@cindex Lambda expressions X@tindex lambda XThe algebraic notation for a ``generic function'' is @samp{lambda(a1,a2,a3,x)} Xwhere the @code{a}s are argument variables, and @code{x} is a formula Xinvolving those variables. For example, when you use the apostrophe to Xenter the formula @samp{x + 2y^x} as an operator with argument list X@samp{(x y)}, Calc builds the generic function @samp{lambda(x, y, x + 2y^x)} Xand gives that to the @code{apply} operation instead of a function name. XYou can enter a lambda expression by hand if you wish, either directly Xwith @kbd{'}, or on the stack with @kbd{$}. (The word @code{lambda} Xderives from Lisp notation and the theory of functions. Note that there Xis no actual Calc function called @code{lambda}; the whole point is that Xthe @code{lambda} expression is used in its symbolic form, not evaluated Xfor an answer.) X X@kindex V R X@pindex calc-reduce X@tindex reduce XThe @kbd{V R} (@code{calc-reduce}) command applies a given binary operator Xacross all the elements of a vector. A binary operator is a function such Xas @code{+} or @code{max} which takes two arguments. For example, reducing X@code{+} over a vector computes the sum of the elements of the vector. XReducing @code{-} computes the first element minus each of the remaining Xelements. Reducing @code{max} computes the maximum element, and so on. XIn general, reducing @code{f} over the vector @samp{[a, b, c, d]} produces X@samp{f(f(f(a, b), c), d)}. X X@kindex V M X@pindex calc-map X@tindex map XThe @kbd{V M} (@code{calc-map}) command applies a given operator elementwise Xto one or more vectors. For example, mapping @code{A} [@code{abs}] produces Xa vector of the absolute values of the elements in the input vector. Mapping X@code{+} pops two vectors from the stack, which must be of equal length, and Xproduces a vector of the pairwise sums of the elements. If either argument Xis a non-vector, it is duplicated for each element of the other vector. For Xexample, @kbd{[1,2,3] 2 V M ^} squares the elements of the specified vector. XWith the 2 listed first, it would have computed a vector of powers of two. XMapping a user-defined function pops as many arguments from the stack as Xthe function requires. If you give an undefined name, you will be prompted Xfor the number of arguments to use.@refill X X@tindex add X@tindex sub X@tindex mul X@tindex div X@tindex pow X@tindex neg X@tindex mod X@tindex vconcat XIn algebraic formulas, these operations can be expressed as X@samp{apply(@var{oper}, @var{vec})}, X@samp{reduce(@var{oper}, @var{vec})}, and X@samp{map(@var{oper}, @var{v1}, @var{v2}, ...)}. XFor example, @samp{map(gcd, [10,20,30], x)}. XIf @var{vec}, or all of the @var{v}'s, Xare non-vectors, the expression is left in symbolic form. Here, @var{oper} Xis any function name like @code{max} or @code{gcd}, or a @code{lambda} Xexpression as described above. Operators that are Xnormally written as symbols have the names @code{add}, @code{sub}, @code{mul}, X@code{div}, @code{pow}, @code{neg}, @code{mod}, and @code{vconcat}.@refill X X(Experts will notice that it's not quite proper to use a variable to name Xa function, since the name @code{gcd} corresponds to the Lisp variable X@code{var-gcd} but to the function @code{calcFunc-gcd}. Calc automatically Xmakes this translation, so you don't have to worry about it.) X X@menu X* Map/Reduce Examples:: X* Mapping Matrices:: X* Reducing Matrices:: X@end menu X X@node Map/Reduce Examples, Mapping Matrices, Reducing and Mapping, Reducing and Mapping X@subsection Further Examples X X@cindex Statistical operations XConsider computing the mean and standard deviation of a list of values. XTo compute the mean, sum the values and divide by the Xlength of the vector. To automate this process, type the sequence X@kbd{@key{RET} V R + @key{TAB} v l /} to duplicate the vector, compute Xits sum, bring the duplicate to the top of the stack and compute its length, Xthen divide the sum by the length.@refill X XTo compute the standard deviation, duplicate twice, compute the mean as Xabove, then type @kbd{V M - 2 V M ^ V R + @key{TAB} v l 1 - / Q}. XThe steps are to subtract the mean from the elements of the vector, Xsquare the elements, sum the elements, compute the length, then divide Xthe sum of squares by the length minus one to yield the variance; the Xstandard deviation is the square root of this. Note that some of these Xoperations could be done more easily with other built-in commands; Xfor example, plain @kbd{-} will subtract a number from a vector elementwise, Xand @kbd{A} will compute the square root of the sum of the squares of the Xelements of a vector. @xref{Keyboard Macros}, for a convenient way to Xprogram a key sequence like this into the Calculator for easy re-use. X XIf you have a matrix and wish to compute the means and standard deviations Xof all the rows or columns at once, just use the appropriate mapping modes Xas described in the next two sections. X X@cindex Summations (by vector mapping) XAs another example, suppose you wish to sum the function @samp{x^1.5} Xover the integers from 5 to 20. First, build a vector of index values Xwith @kbd{v x 16 @key{RET} 4 +}. Next, map the function @samp{x^1.5} Xover this vector with @kbd{V M ' x^1.5}. Finally, sum the vector with X@kbd{V R +}. This same technique can be used to compute any sum or Xproduct over a reasonably small set of index values. X X@node Mapping Matrices, Reducing Matrices, Map/Reduce Examples, Reducing and Mapping X@subsection Mapping Matrices X X@cindex Mapping modes XWhen matrices are involved in a mapping operation, they can be interpreted Xin several ways. The current @dfn{mapping mode} controls this Xinterpretation; you set the mode by typing a two-letter combination Xstarting with @kbd{m} when Calc asks which operator to use. Once you Xhave set a mapping mode, that mode stays in effect until you change it. XThe default mode is map-by-elements. The mapping mode is also used by Xthe @code{calc-reduce} command, as described in the next section. XThe mapping mode has no effect if the arguments are plain vectors. X XUse @kbd{m e} to select map-by-elements mode. In this mode, the operator Xis applied to each element of the argument matrix, or to corresponding Xelements of the argument matrices. For example, mapping by elements Xthe sine function over a matrix replaces each matrix element by its sine. XMapping addition by elements adds corresponding matrix elements. If Xeither argument is a scalar, the same scalar is mapped with each element Xof the other matrix. X X@tindex mapr XUse @kbd{m r} to select map-by-rows mode. In this mode, the operator is Xapplied to each row of the argument matrix, or to corresponding rows of Xthe argument matrices. Rows are presented to the operator as plain vectors. XFor example, mapping multiplication by rows computes a vector of dot Xproducts of the rows of the input matrices, since multiplying two plain Xvectors computes a dot product. If either argument is scalar, or a plain Xvector of the same length as a row of the other matrix, it is mapped with Xevery row of the matrix. X X@tindex mapc XUse @kbd{m c} to select map-by-columns mode. Essentially, this transposes Xall matrix arguments, maps by rows, then transposes the result. X X@tindex mapa XUse @kbd{m a} to select map-across mode. In this mode, the input is a Xsingle matrix with as many columns as the operator takes arguments. XThe columns of the matrix are treated as arguments in a regular vector Xmapping operation. For example, mapping multiplication across matrix X@samp{[[a, b], [c, d], [e, f]]} produces the vector @samp{[a*b, c*d, e*f]}. X X@tindex mapd XUse @kbd{m d} to select map-down mode. This mode is analogous to map-across, Xexcept that it treats the rows of the matrix as arguments to the mapping Xoperation. X XAs another example, you could concatenate two matrices horizontally by Xmapping @samp{|} (vector concatenation) by rows. X X@node Reducing Matrices, , Mapping Matrices, Reducing and Mapping X@subsection Reducing Matrices X XThe current @dfn{mapping mode}, as described in the previous section, Xalso influences reduction operations when the argument is a matrix. X XUse @kbd{m e} to select reduce-by-elements mode. In this mode, all the Xelements of the matrix are reduced into one scalar result. For example, Xmapping addition by elements over a 3x4 matrix adds all 12 elements Xtogether. Normal English left-to-right, top-to-bottom order is used; Xfor example, reducing subtraction by elements over the matrix X@samp{[[a, b], [c, d]]} produces @samp{(((a - b) - c) - d)}. X X@tindex reducer XUse @kbd{m r} to select reduce-by-rows mode. In this mode, the rows of Xthe matrix are treated as vectors; the operator is applied to these Xrow vectors. For example, mapping addition by rows produces a vector Xof the sums of the various columns of the matrix, because adding two Xvectors does a standard vector addition. Reducing multiplication by Xrows is not very useful unless there are only two rows, in which case Xit computes the dot product of the two rows. X X@tindex reducec XUse @kbd{m c} to select reduce-by-columns mode. In this mode, the columns Xof the matrix are treated as vectors; the operator is reduced along the Xcolumn vectors. In other words, it transposes the argument matrix and Xthen reduces by rows. X X@tindex reducea XUse @kbd{m a} to select reduce-across mode. In this mode, the rows of the Xmatrix are treated as vectors; each row is reduced in the usual way, and Xthe results are collected into a vector. For example, reducing Xmultiplication across a matrix produces a vector of the products of the Xvarious rows. Reducing addition produces a vector of the sums of the Xvarious rows, producing the same result as reducing by columns but in a Xdifferent way. X X@tindex reduced XUse @kbd{m d} to select reduce-down mode. In this mode, the columns of the Xmatrix are treated as vectors which are reduced individually. This is Xthe same as transposing the argument matrix and then reducing across. X X@node Vector and Matrix Formats, , Reducing and Mapping, Matrix Functions X@section Vector and Matrix Display Formats X XCommands for controlling vector and matrix display use the @kbd{v} prefix Xinstead of the usual @kbd{d} prefix. X X@kindex v < X@pindex calc-matrix-left-justify X@kindex v = X@pindex calc-matrix-center-justify X@kindex v > X@pindex calc-matrix-right-justify XThe @kbd{v <} (@code{calc-matrix-left-justify}), @kbd{v >} X(@code{calc-matrix-right-justify}), and @kbd{v =} X(@code{calc-matrix-center-justify}) commands control whether matrix elements Xare justified to the left, right, or center of their columns.@refill X X@kindex v [ X@pindex calc-vector-brackets X@kindex v @{ X@pindex calc-vector-braces X@kindex v ( X@pindex calc-vector-parens XThe @kbd{v [} (@code{calc-vector-brackets}) command turns the square Xbrackets that surround vectors and matrices displayed in the stack on Xand off. The @kbd{v @{} (@code{calc-vector-braces}) and @kbd{v (} X(@code{calc-vector-parens}) commands use curly braces or parentheses, Xrespectively, instead of square brackets. For example, @kbd{v @{} might Xbe used in preparation for yanking a matrix into a buffer running XMathematica. (In fact, the Mathematica language mode uses this mode; X@pxref{Mathematica Language Mode}.) Note that, regardless of the Xdisplay mode, either brackets and braces may be used to enter vectors, Xand parentheses may never be used for this purpose.@refill X X@kindex v , X@pindex calc-vector-commas XThe @kbd{v ,} (@code{calc-vector-commas}) command turns commas on and Xoff in vector and matrix display.@refill X X@node Algebra, Units, Matrix Functions, Top X@chapter Algebra X XThe commands for operating on algebraic formulas use the @kbd{a} key Xprefix. @xref{Editing Stack Entries}, to see how to manipulate formulas Xusing regular Emacs editing commands. X XMany of these commands prompt for a variable name or formula. If you Xanswer the prompt with a blank line, the variable or formula is taken Xfrom top-of-stack, and the normal argument for the command is taken Xfrom second-to-top. X XWhen doing algebraic work, you may find several of the Calculator's Xmodes to be helpful, including algebraic-simplification mode (@kbd{m A}), Xalgebraic-entry mode (@kbd{m a}), fraction mode (@kbd{m f}), and Xsymbolic mode (@kbd{m s}). @xref{Mode Settings}, for discussions Xof these modes. You may also wish to select ``big'' display mode (@kbd{d B}). X@xref{Normal Language Modes}. X X@menu X* Algebraic Manipulation:: X* Rewrite Rules:: X* Logical Operations:: X* Calculus:: X@end menu X X@node Algebraic Manipulation, Rewrite Rules, Algebra, Algebra X@section Algebraic Manipulation X X@kindex a s X@pindex calc-simplify XThe @kbd{a s} (@code{calc-simplify}) command applies various algebraic Xrules to simplify a formula. This generally entails combining like Xterms of sums and products. The result will be a formula which is Xmathematically equivalent to the original one, but somewhat simpler. X X@kindex a e X@pindex calc-simplify-extended XThe @kbd{a e} (@code{calc-simplify-extended}) command is like @kbd{a s} Xexcept that it applies some additional simplifications which are not X``safe'' in all cases. For example, powers are simplified according Xto the rule @samp{(a^b)^c = a^(b c)}, even though this is not always Xtrue (consider @samp{sqrt(a^2)} for negative @samp{a}). The symbolic Xintegrator uses @code{calc-simplify-extended}; one effect of this is Xthat the integrator's results must be used with caution. Where an Xintegral table will often attach conditions like ``for positive @samp{a} Xonly,'' Calc (and most other symbolic integration programs) will simply Xproduce an unqualified result. X X@kindex a x X@pindex calc-expand XThe @kbd{a x} (@code{calc-expand}) command expands an expression by Xapplying the distributive law. It applies to products, quotients, and Xpowers involving sums. By default, it fully distributes all parts of Xthe expression. With the a numeric prefix argument, the distributive Xlaw is applied only the specified number of times, then the partially Xexpanded expression is left on the stack. X XCalc's automatic simplifications will sometimes reverse a partial Xexpansion. For example, the first step in expanding @samp{(x+1)^3} is Xto write @samp{(x+1)*(x+1)^2}. If @code{calc-expand} stops there and Xtries to put this formula onto the stack, though, Calc will automatically Xsimplify it back to @samp{(x+1)^3} form. The solution is to turn Xsimplification off first (@pxref{Simplification Modes}), or to run X@kbd{a x} without a numeric prefix argument so that it expands all Xthe way in one step. X X@kindex a c X@pindex calc-collect XThe @kbd{a c} (@code{calc-collect}) command rearranges a formula as a Xpolynomial in a given variable. For example, expanding @samp{(x+y)^3} Xwith @kbd{a x} produces a sum of four terms, initially written in Xarbitrary order. You can use @kbd{a c x} or @kbd{a c y} to arrange Xthe terms in order of decreasing powers of @code{x} or @code{y}, Xrespectively. You can also give any expression about which to collect: X@kbd{a c ln(x+1)} will collect together all terms multiplied by @samp{ln(x+1)} Xor integer powers thereof. X X@kindex a b X@pindex calc-substitute XThe @kbd{a b} (@code{calc-substitute}) command substitutes occurrences Xof some variable or sub-expression of an expression with a new Xsub-expression. For example, substituting @samp{sin(x)} to @samp{cos(y)} Xin @samp{2 sin(x)^2 + x sin(x) + sin(2 x)} produces X@samp{2 cos(y)^2 + x cos(y) + sin(2 x)}. XNote that this is a purely structural substitution; the lone @code{x} and the X@samp{sin(2 x)} stayed the same because they did not look like X@samp{sin(x)}. @xref{Rewrite Rules}, for a more general method for Xdoing substitutions.@refill X XThe @code{calc-substitute} command normally prompts for two formulas, Xthe old one and the new one. If you enter a blank line for the first Xprompt, all three arguments are taken from the stack (old, then new, Xthen target expression). If you type an old formula but then enter a Xblank line for the new one, the new formula is taken from top-of-stack Xand the target from second-to-top. If you answer both prompts, the Xtarget is taken from top-of-stack as usual. X X@node Rewrite Rules, Logical Operations, Algebraic Manipulation, Algebra X@section Rewrite Rules X X@cindex Rewrite rules X@cindex Transformations X@cindex Pattern matching X@kindex a r X@pindex calc-rewrite XThe @kbd{a r} (@code{calc-rewrite}) command makes substitutions in a Xformula according to a specified pattern or patterns. It is like a Xgeneralized version of @code{calc-substitute}. You provide Calc with Xone or more @dfn{rewrite rules}, which take the form of vectors of Xtwo or three elements: @samp{[old, new]} or @samp{[old, new, cond]}. XTo specify a set of rules, make a vector of rule vectors. (Calc will Xinterpret this structure as a matrix as long as the rules either all Xinclude or all omit the @samp{cond} part. Whether or not this is true Xmakes no difference to @code{calc-rewrite} itself.) X XWhen you are prompted to enter the rewrite rules, you can either type Xthe vector directly (as an algebraic entry), or type the name of a XCalc variable into which you have stored a rules vector, or enter Xa blank line in which case the rules vector will be taken from the Xtop of the stack. It is most convenient to store rules you use often Xin a variable and invoke them by naming the variable. You may also Xwish to use @kbd{Z V} (@code{calc-permanent-variable}) to save the Xrules permanently; @pxref{Storing Variables}. X XTo match a particular formula @samp{x} with a particular rule vector X@samp{[old, new]}, Calc compares the structure of @samp{x} with the Xstructure of @samp{old}. Variables that appear in @samp{old} are Xtreated as ``meta-variables''; the corresponding positions in @samp{x} Xmay contain any sub-formulas. For example, the pattern @samp{f(x,y)} Xwould match the expression @samp{f(12, a+1)} with the meta-variable X@samp{x} corresponding to 12 and with @samp{y} corresponding to X@samp{a+1}. However, this pattern would not match @samp{f(12)} or X@samp{g(12, a+1)}, since there is no assignment of the meta-variables Xthat will allow the pattern to match these expressions. Notice that Xif the pattern is a single variable, it will match any expression. X XIf a given meta-variable appears more than once in @var{old}, the Xcorresponding sub-formulas of @samp{x} must be identical. Thus Xthe pattern @samp{f(x,x)} would match @samp{f(12, 12)} and X@samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(12, 12.0)}. X XThings other than variables must match exactly between the pattern Xand the target formula. To match a particular variable, use the Xpseudo-function @samp{quote(v)} in the pattern. For example, the Xpattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or X@samp{sin(x)+y}. X XPattern-matching is completely structural, not taking the algebraic Xproperties of formulas into account. Thus @samp{f(x+1)} matches Xthe formula @samp{f(a+1)} but not @samp{f(a)}, @samp{f(a+2)}, or X@samp{f(1+a)}.@refill X XIf the @samp{old} pattern is found to match a given formula, that Xformula is replaced by @samp{new}, where any occurrences in @samp{new} Xof meta-variables from the pattern are replaced with the sub-formulas Xthat they matched. Thus, applying the rule @samp{[f(x,y), g(y+x,x)]} Xto @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}. X XIf a @samp{cond} part is also present in the rule, this is an Xadditional condition that must be satisfied before the rule is Xaccepted. Once @samp{old} has been successfully matched to the Xtarget expression, @samp{cond} is evaluated (with the meta-variables Xsubstituted for the values they matched) and simplified with X@code{calc-simplify}. If the result is a nonzero number, the rule Xis accepted. If the result is zero or if it is still a symbolic Xformula, the rule is rejected. @xref{Logical Operations}, for a Xnumber of functions that return 1 or 0 according to the result of Xsome test. For example, the formula @samp{n > 0} simplifies to X1 or 0 if @samp{n} is a replaced by a positive or nonpositive Xnumber, respectively. Thus, the rule @samp{[f(x,y), g(y+x,x), x+y > 0]} Xwould be applied to @samp{f(0, 4)} but not to @samp{f(-3, 2)} or X@samp{f(12, a+1)}. (In the former case, the condition can be shown Xnot to be satisfied; in the latter case, the condition merely cannot Xbe shown to be satisfied, but that is enough to reject the rule.) X XWhen @code{calc-rewrite} is used, it takes an expression from the Xtop of the stack and attempts to match any of the specified rules Xto any part of the expression, starting with the whole expression Xand then, if that fails, trying deeper and deeper sub-expressions. XFor each part of the expression, the rules are tried in the Xspecified order. The first rule to match the first sub-expression Xwins; it replaces the matched sub-expression according to the X@samp{new} part of the rule. By default, only one substitution Xis made per @code{calc-rewrite} command. X XGiven a positive numeric prefix argument, @code{calc-rewrite} will Xperform up to that many substitutions before stopping. First, the Xtop-level formula is matched and substituted repeatedly until it Xno longer matches the pattern; then, sub-formulas are tried, and Xso on. If the limit still has not been reached, the top-level Xformula is check again (in case a substitution of one of its Xarguments causes it again to match). This continues until no Xfurther matches can be made, or until the limit is reached. X XGiven a negative numeric prefix argument, @code{calc-rewrite} will Xmatch and substitute the top-level expression up to that many times, Xbut will not attempt to match any sub-expressions. X XA prefix argument of zero is equivalent to a prefix of 25. This is Xmeant to be a convenient limit that is usually enough to finish the Xjob, but not enough to be too slow in case the rule transformations Xget into an infinite loop. X XAs a larger example, suppose we wish to substitute the pattern X@samp{sin(x)^2 + cos(x)^2} with 1 in a given expression. The rule X@samp{[sin(x)^2 + cos(x)^2, 1]} would work, but only for the most Xliteral matches. This would miss the formula @samp{2 sin(a)^2 + 2 Xcos(a)^2}, for example, because our pattern does not account for both Xterms being multiplied by an equal factor. A more flexible solution Xwould be to use the rule @samp{[cos(x)^2, 1 - sin(x)^2]}, followed by Xalgebraic simplification if necessary.@refill X XSimilarly, the pattern @samp{[f(x, x+1), g(x)]} is not a very reliable Xrule since it fails to match in cases like @samp{f(2, 3)}. A better Xrule would be @samp{[f(x,y), g(x), y=x+1]}, since the algebraic Xsimplifier is applied to conditions but not to patterns. X XAs another example, we could define our own factorial function with the Xrules @samp{[[f(0), 1], [f(n), n*f(n-1), n>0]]}. Enter this rules Xvector and store it in a variable: @kbd{s factrules}. Now, given a Xfactorial formula like @samp{f(5)} on the stack, type @samp{C-u 0 a r Xfactrules} to apply these rules repeatedly. After six applications, X@code{calc-rewrite} will stop with 120 on the stack. If we expect to SHAR_EOF echo "End of part 16" echo "File calc.texinfo is continued in part 17" echo "17" > s2_seq_.tmp exit 0