*** empty log message ***
[bpt/emacs.git] / doc / misc / calc.texi
CommitLineData
4009494e
GM
1\input texinfo @c -*-texinfo-*-
2@comment %**start of header (This is for running Texinfo on a region.)
3@c smallbook
db78a8cb 4@setfilename ../../info/calc
4009494e
GM
5@c [title]
6@settitle GNU Emacs Calc 2.1 Manual
7@setchapternewpage odd
8@comment %**end of header (This is for running Texinfo on a region.)
9
10@c The following macros are used for conditional output for single lines.
11@c @texline foo
12@c `foo' will appear only in TeX output
13@c @infoline foo
14@c `foo' will appear only in non-TeX output
15
16@c @expr{expr} will typeset an expression;
17@c $x$ in TeX, @samp{x} otherwise.
18
19@iftex
20@macro texline
21@end macro
22@alias infoline=comment
23@alias expr=math
24@alias tfn=code
25@alias mathit=expr
8dc6104d 26@alias summarykey=key
4009494e
GM
27@macro cpi{}
28@math{@pi{}}
29@end macro
30@macro cpiover{den}
31@math{@pi/\den\}
32@end macro
33@end iftex
34
35@ifnottex
36@alias texline=comment
37@macro infoline{stuff}
38\stuff\
39@end macro
40@alias expr=samp
41@alias tfn=t
42@alias mathit=i
8dc6104d
JB
43@macro summarykey{ky}
44\ky\
45@end macro
4009494e
GM
46@macro cpi{}
47@expr{pi}
48@end macro
49@macro cpiover{den}
50@expr{pi/\den\}
51@end macro
52@end ifnottex
53
54
55@tex
56% Suggested by Karl Berry <karl@@freefriends.org>
57\gdef\!{\mskip-\thinmuskip}
58@end tex
59
60@c Fix some other things specifically for this manual.
61@iftex
62@finalout
63@mathcode`@:=`@: @c Make Calc fractions come out right in math mode
64@tex
65\gdef\coloneq{\mathrel{\mathord:\mathord=}}
66
67\gdef\beforedisplay{\vskip-10pt}
68\gdef\afterdisplay{\vskip-5pt}
69\gdef\beforedisplayh{\vskip-25pt}
70\gdef\afterdisplayh{\vskip-10pt}
71@end tex
72@newdimen@kyvpos @kyvpos=0pt
73@newdimen@kyhpos @kyhpos=0pt
74@newcount@calcclubpenalty @calcclubpenalty=1000
75@ignore
76@newcount@calcpageno
77@newtoks@calcoldeverypar @calcoldeverypar=@everypar
78@everypar={@calceverypar@the@calcoldeverypar}
79@ifx@turnoffactive@undefinedzzz@def@turnoffactive{}@fi
80@ifx@ninett@undefinedzzz@font@ninett=cmtt9@fi
81@catcode`@\=0 \catcode`\@=11
82\r@ggedbottomtrue
83\catcode`\@=0 @catcode`@\=@active
84@end ignore
85@end iftex
86
87@copying
88This file documents Calc, the GNU Emacs calculator.
89
90Copyright @copyright{} 1990, 1991, 2001, 2002, 2003, 2004,
3f548a7c 912005, 2006, 2007, 2008 Free Software Foundation, Inc.
4009494e
GM
92
93@quotation
94Permission is granted to copy, distribute and/or modify this document
95under the terms of the GNU Free Documentation License, Version 1.2 or
96any later version published by the Free Software Foundation; with the
97Invariant Sections being just ``GNU GENERAL PUBLIC LICENSE'', with the
98Front-Cover texts being ``A GNU Manual,'' and with the Back-Cover
99Texts as in (a) below. A copy of the license is included in the section
100entitled ``GNU Free Documentation License.''
101
6f093307
GM
102(a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
103modify this GNU manual. Buying copies from the FSF supports it in
104developing GNU and promoting software freedom.''
4009494e
GM
105@end quotation
106@end copying
107
108@dircategory Emacs
109@direntry
110* Calc: (calc). Advanced desk calculator and mathematical tool.
111@end direntry
112
113@titlepage
114@sp 6
115@center @titlefont{Calc Manual}
116@sp 4
117@center GNU Emacs Calc Version 2.1
118@c [volume]
119@sp 5
120@center Dave Gillespie
121@center daveg@@synaptics.com
122@page
123
124@vskip 0pt plus 1filll
125Copyright @copyright{} 1990, 1991, 2001, 2002, 2003, 2004,
3f548a7c 126 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4009494e
GM
127@insertcopying
128@end titlepage
129
130
131@summarycontents
132
133@c [end]
134
135@contents
136
137@c [begin]
138@ifnottex
139@node Top, Getting Started, (dir), (dir)
140@chapter The GNU Emacs Calculator
141
142@noindent
143@dfn{Calc} is an advanced desk calculator and mathematical tool
144written by Dave Gillespie that runs as part of the GNU Emacs environment.
145
146This manual, also written (mostly) by Dave Gillespie, is divided into
147three major parts: ``Getting Started,'' the ``Calc Tutorial,'' and the
148``Calc Reference.'' The Tutorial introduces all the major aspects of
149Calculator use in an easy, hands-on way. The remainder of the manual is
150a complete reference to the features of the Calculator.
151@end ifnottex
152
153@ifinfo
154For help in the Emacs Info system (which you are using to read this
155file), type @kbd{?}. (You can also type @kbd{h} to run through a
156longer Info tutorial.)
157@end ifinfo
158
159@menu
160* Getting Started:: General description and overview.
161@ifinfo
162* Interactive Tutorial::
163@end ifinfo
164* Tutorial:: A step-by-step introduction for beginners.
165
166* Introduction:: Introduction to the Calc reference manual.
167* Data Types:: Types of objects manipulated by Calc.
168* Stack and Trail:: Manipulating the stack and trail buffers.
169* Mode Settings:: Adjusting display format and other modes.
170* Arithmetic:: Basic arithmetic functions.
171* Scientific Functions:: Transcendentals and other scientific functions.
172* Matrix Functions:: Operations on vectors and matrices.
173* Algebra:: Manipulating expressions algebraically.
174* Units:: Operations on numbers with units.
175* Store and Recall:: Storing and recalling variables.
176* Graphics:: Commands for making graphs of data.
177* Kill and Yank:: Moving data into and out of Calc.
178* Keypad Mode:: Operating Calc from a keypad.
179* Embedded Mode:: Working with formulas embedded in a file.
180* Programming:: Calc as a programmable calculator.
181
182* Copying:: How you can copy and share Calc.
183* GNU Free Documentation License:: The license for this documentation.
184* Customizing Calc:: Customizing Calc.
185* Reporting Bugs:: How to report bugs and make suggestions.
186
187* Summary:: Summary of Calc commands and functions.
188
189* Key Index:: The standard Calc key sequences.
190* Command Index:: The interactive Calc commands.
191* Function Index:: Functions (in algebraic formulas).
192* Concept Index:: General concepts.
193* Variable Index:: Variables used by Calc (both user and internal).
194* Lisp Function Index:: Internal Lisp math functions.
195@end menu
196
197@ifinfo
198@node Getting Started, Interactive Tutorial, Top, Top
199@end ifinfo
200@ifnotinfo
201@node Getting Started, Tutorial, Top, Top
202@end ifnotinfo
203@chapter Getting Started
204@noindent
205This chapter provides a general overview of Calc, the GNU Emacs
206Calculator: What it is, how to start it and how to exit from it,
207and what are the various ways that it can be used.
208
209@menu
210* What is Calc::
211* About This Manual::
212* Notations Used in This Manual::
213* Demonstration of Calc::
214* Using Calc::
215* History and Acknowledgements::
216@end menu
217
218@node What is Calc, About This Manual, Getting Started, Getting Started
219@section What is Calc?
220
221@noindent
222@dfn{Calc} is an advanced calculator and mathematical tool that runs as
223part of the GNU Emacs environment. Very roughly based on the HP-28/48
224series of calculators, its many features include:
225
226@itemize @bullet
227@item
228Choice of algebraic or RPN (stack-based) entry of calculations.
229
230@item
231Arbitrary precision integers and floating-point numbers.
232
233@item
234Arithmetic on rational numbers, complex numbers (rectangular and polar),
235error forms with standard deviations, open and closed intervals, vectors
236and matrices, dates and times, infinities, sets, quantities with units,
237and algebraic formulas.
238
239@item
240Mathematical operations such as logarithms and trigonometric functions.
241
242@item
243Programmer's features (bitwise operations, non-decimal numbers).
244
245@item
246Financial functions such as future value and internal rate of return.
247
248@item
249Number theoretical features such as prime factorization and arithmetic
250modulo @var{m} for any @var{m}.
251
252@item
253Algebraic manipulation features, including symbolic calculus.
254
255@item
256Moving data to and from regular editing buffers.
257
258@item
259Embedded mode for manipulating Calc formulas and data directly
260inside any editing buffer.
261
262@item
263Graphics using GNUPLOT, a versatile (and free) plotting program.
264
265@item
266Easy programming using keyboard macros, algebraic formulas,
267algebraic rewrite rules, or extended Emacs Lisp.
268@end itemize
269
270Calc tries to include a little something for everyone; as a result it is
271large and might be intimidating to the first-time user. If you plan to
272use Calc only as a traditional desk calculator, all you really need to
273read is the ``Getting Started'' chapter of this manual and possibly the
274first few sections of the tutorial. As you become more comfortable with
275the program you can learn its additional features. Calc does not
276have the scope and depth of a fully-functional symbolic math package,
277but Calc has the advantages of convenience, portability, and freedom.
278
279@node About This Manual, Notations Used in This Manual, What is Calc, Getting Started
280@section About This Manual
281
282@noindent
283This document serves as a complete description of the GNU Emacs
284Calculator. It works both as an introduction for novices, and as
285a reference for experienced users. While it helps to have some
286experience with GNU Emacs in order to get the most out of Calc,
287this manual ought to be readable even if you don't know or use Emacs
288regularly.
289
290The manual is divided into three major parts:@: the ``Getting
291Started'' chapter you are reading now, the Calc tutorial (chapter 2),
292and the Calc reference manual (the remaining chapters and appendices).
293@c [when-split]
294@c This manual has been printed in two volumes, the @dfn{Tutorial} and the
295@c @dfn{Reference}. Both volumes include a copy of the ``Getting Started''
296@c chapter.
297
298If you are in a hurry to use Calc, there is a brief ``demonstration''
299below which illustrates the major features of Calc in just a couple of
300pages. If you don't have time to go through the full tutorial, this
301will show you everything you need to know to begin.
302@xref{Demonstration of Calc}.
303
304The tutorial chapter walks you through the various parts of Calc
305with lots of hands-on examples and explanations. If you are new
306to Calc and you have some time, try going through at least the
307beginning of the tutorial. The tutorial includes about 70 exercises
308with answers. These exercises give you some guided practice with
309Calc, as well as pointing out some interesting and unusual ways
310to use its features.
311
312The reference section discusses Calc in complete depth. You can read
313the reference from start to finish if you want to learn every aspect
314of Calc. Or, you can look in the table of contents or the Concept
315Index to find the parts of the manual that discuss the things you
316need to know.
317
318@cindex Marginal notes
319Every Calc keyboard command is listed in the Calc Summary, and also
320in the Key Index. Algebraic functions, @kbd{M-x} commands, and
321variables also have their own indices.
322@texline Each
323@infoline In the printed manual, each
324paragraph that is referenced in the Key or Function Index is marked
325in the margin with its index entry.
326
327@c [fix-ref Help Commands]
328You can access this manual on-line at any time within Calc by
329pressing the @kbd{h i} key sequence. Outside of the Calc window,
330you can press @kbd{C-x * i} to read the manual on-line. Also, you
331can jump directly to the Tutorial by pressing @kbd{h t} or @kbd{C-x * t},
332or to the Summary by pressing @kbd{h s} or @kbd{C-x * s}. Within Calc,
333you can also go to the part of the manual describing any Calc key,
334function, or variable using @w{@kbd{h k}}, @kbd{h f}, or @kbd{h v},
335respectively. @xref{Help Commands}.
336
337@ifnottex
338The Calc manual can be printed, but because the manual is so large, you
339should only make a printed copy if you really need it. To print the
340manual, you will need the @TeX{} typesetting program (this is a free
341program by Donald Knuth at Stanford University) as well as the
342@file{texindex} program and @file{texinfo.tex} file, both of which can
343be obtained from the FSF as part of the @code{texinfo} package.
344To print the Calc manual in one huge tome, you will need the
345source code to this manual, @file{calc.texi}, available as part of the
346Emacs source. Once you have this file, type @kbd{texi2dvi calc.texi}.
347Alternatively, change to the @file{man} subdirectory of the Emacs
348source distribution, and type @kbd{make calc.dvi}. (Don't worry if you
349get some ``overfull box'' warnings while @TeX{} runs.)
350The result will be a device-independent output file called
351@file{calc.dvi}, which you must print in whatever way is right
352for your system. On many systems, the command is
353
354@example
355lpr -d calc.dvi
356@end example
357
358@noindent
359or
360
361@example
362dvips calc.dvi
363@end example
364@end ifnottex
365@c Printed copies of this manual are also available from the Free Software
366@c Foundation.
367
368@node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started
369@section Notations Used in This Manual
370
371@noindent
372This section describes the various notations that are used
373throughout the Calc manual.
374
375In keystroke sequences, uppercase letters mean you must hold down
376the shift key while typing the letter. Keys pressed with Control
377held down are shown as @kbd{C-x}. Keys pressed with Meta held down
378are shown as @kbd{M-x}. Other notations are @key{RET} for the
379Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key,
380@key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key.
381The @key{DEL} key is called Backspace on some keyboards, it is
382whatever key you would use to correct a simple typing error when
383regularly using Emacs.
384
385(If you don't have the @key{LFD} or @key{TAB} keys on your keyboard,
386the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively.
387If you don't have a Meta key, look for Alt or Extend Char. You can
388also press @key{ESC} or @kbd{C-[} first to get the same effect, so
389that @kbd{M-x}, @kbd{@key{ESC} x}, and @kbd{C-[ x} are all equivalent.)
390
391Sometimes the @key{RET} key is not shown when it is ``obvious''
392that you must press @key{RET} to proceed. For example, the @key{RET}
393is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}.
394
395Commands are generally shown like this: @kbd{p} (@code{calc-precision})
396or @kbd{C-x * k} (@code{calc-keypad}). This means that the command is
397normally used by pressing the @kbd{p} key or @kbd{C-x * k} key sequence,
398but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}.
399
400Commands that correspond to functions in algebraic notation
401are written: @kbd{C} (@code{calc-cos}) [@code{cos}]. This means
402the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that
403the corresponding function in an algebraic-style formula would
404be @samp{cos(@var{x})}.
405
406A few commands don't have key equivalents: @code{calc-sincos}
407[@code{sincos}].
408
409@node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started
410@section A Demonstration of Calc
411
412@noindent
413@cindex Demonstration of Calc
414This section will show some typical small problems being solved with
415Calc. The focus is more on demonstration than explanation, but
416everything you see here will be covered more thoroughly in the
417Tutorial.
418
419To begin, start Emacs if necessary (usually the command @code{emacs}
420does this), and type @kbd{C-x * c} to start the
421Calculator. (You can also use @kbd{M-x calc} if this doesn't work.
422@xref{Starting Calc}, for various ways of starting the Calculator.)
423
424Be sure to type all the sample input exactly, especially noting the
425difference between lower-case and upper-case letters. Remember,
426@key{RET}, @key{TAB}, @key{DEL}, and @key{SPC} are the Return, Tab,
427Delete, and Space keys.
428
429@strong{RPN calculation.} In RPN, you type the input number(s) first,
430then the command to operate on the numbers.
431
432@noindent
433Type @kbd{2 @key{RET} 3 + Q} to compute
434@texline @math{\sqrt{2+3} = 2.2360679775}.
435@infoline the square root of 2+3, which is 2.2360679775.
436
437@noindent
438Type @kbd{P 2 ^} to compute
439@texline @math{\pi^2 = 9.86960440109}.
440@infoline the value of `pi' squared, 9.86960440109.
441
442@noindent
443Type @key{TAB} to exchange the order of these two results.
444
445@noindent
446Type @kbd{- I H S} to subtract these results and compute the Inverse
447Hyperbolic sine of the difference, 2.72996136574.
448
449@noindent
450Type @key{DEL} to erase this result.
451
452@strong{Algebraic calculation.} You can also enter calculations using
453conventional ``algebraic'' notation. To enter an algebraic formula,
454use the apostrophe key.
455
456@noindent
457Type @kbd{' sqrt(2+3) @key{RET}} to compute
458@texline @math{\sqrt{2+3}}.
459@infoline the square root of 2+3.
460
461@noindent
462Type @kbd{' pi^2 @key{RET}} to enter
463@texline @math{\pi^2}.
464@infoline `pi' squared.
465To evaluate this symbolic formula as a number, type @kbd{=}.
466
467@noindent
468Type @kbd{' arcsinh($ - $$) @key{RET}} to subtract the second-most-recent
469result from the most-recent and compute the Inverse Hyperbolic sine.
470
471@strong{Keypad mode.} If you are using the X window system, press
472@w{@kbd{C-x * k}} to get Keypad mode. (If you don't use X, skip to
473the next section.)
474
475@noindent
476Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT}
477``buttons'' using your left mouse button.
478
479@noindent
480Click on @key{PI}, @key{2}, and @tfn{y^x}.
481
482@noindent
483Click on @key{INV}, then @key{ENTER} to swap the two results.
484
485@noindent
486Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}.
487
488@noindent
489Click on @key{<-} to erase the result, then click @key{OFF} to turn
490the Keypad Calculator off.
491
492@strong{Grabbing data.} Type @kbd{C-x * x} if necessary to exit Calc.
493Now select the following numbers as an Emacs region: ``Mark'' the
494front of the list by typing @kbd{C-@key{SPC}} or @kbd{C-@@} there,
495then move to the other end of the list. (Either get this list from
496the on-line copy of this manual, accessed by @w{@kbd{C-x * i}}, or just
497type these numbers into a scratch file.) Now type @kbd{C-x * g} to
498``grab'' these numbers into Calc.
499
500@example
501@group
5021.23 1.97
5031.6 2
5041.19 1.08
505@end group
506@end example
507
508@noindent
509The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.''
510Type @w{@kbd{V R +}} to compute the sum of these numbers.
511
512@noindent
513Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute
514the product of the numbers.
515
516@noindent
517You can also grab data as a rectangular matrix. Place the cursor on
518the upper-leftmost @samp{1} and set the mark, then move to just after
519the lower-right @samp{8} and press @kbd{C-x * r}.
520
521@noindent
522Type @kbd{v t} to transpose this
523@texline @math{3\times2}
524@infoline 3x2
525matrix into a
526@texline @math{2\times3}
527@infoline 2x3
528matrix. Type @w{@kbd{v u}} to unpack the rows into two separate
529vectors. Now type @w{@kbd{V R + @key{TAB} V R +}} to compute the sums
530of the two original columns. (There is also a special
531grab-and-sum-columns command, @kbd{C-x * :}.)
532
533@strong{Units conversion.} Units are entered algebraically.
534Type @w{@kbd{' 43 mi/hr @key{RET}}} to enter the quantity 43 miles-per-hour.
535Type @w{@kbd{u c km/hr @key{RET}}}. Type @w{@kbd{u c m/s @key{RET}}}.
536
537@strong{Date arithmetic.} Type @kbd{t N} to get the current date and
538time. Type @kbd{90 +} to find the date 90 days from now. Type
539@kbd{' <25 dec 87> @key{RET}} to enter a date, then @kbd{- 7 /} to see how
540many weeks have passed since then.
541
542@strong{Algebra.} Algebraic entries can also include formulas
543or equations involving variables. Type @kbd{@w{' [x + y} = a, x y = 1] @key{RET}}
544to enter a pair of equations involving three variables.
545(Note the leading apostrophe in this example; also, note that the space
546between @samp{x y} is required.) Type @w{@kbd{a S x,y @key{RET}}} to solve
547these equations for the variables @expr{x} and @expr{y}.
548
549@noindent
550Type @kbd{d B} to view the solutions in more readable notation.
551Type @w{@kbd{d C}} to view them in C language notation, @kbd{d T}
552to view them in the notation for the @TeX{} typesetting system,
553and @kbd{d L} to view them in the notation for the La@TeX{} typesetting
554system. Type @kbd{d N} to return to normal notation.
555
556@noindent
557Type @kbd{7.5}, then @kbd{s l a @key{RET}} to let @expr{a = 7.5} in these formulas.
558(That's a letter @kbd{l}, not a numeral @kbd{1}.)
559
560@ifnotinfo
561@strong{Help functions.} You can read about any command in the on-line
562manual. Type @kbd{C-x * c} to return to Calc after each of these
563commands: @kbd{h k t N} to read about the @kbd{t N} command,
564@kbd{h f sqrt @key{RET}} to read about the @code{sqrt} function, and
565@kbd{h s} to read the Calc summary.
566@end ifnotinfo
567@ifinfo
568@strong{Help functions.} You can read about any command in the on-line
569manual. Remember to type the letter @kbd{l}, then @kbd{C-x * c}, to
570return here after each of these commands: @w{@kbd{h k t N}} to read
571about the @w{@kbd{t N}} command, @kbd{h f sqrt @key{RET}} to read about the
572@code{sqrt} function, and @kbd{h s} to read the Calc summary.
573@end ifinfo
574
575Press @key{DEL} repeatedly to remove any leftover results from the stack.
576To exit from Calc, press @kbd{q} or @kbd{C-x * c} again.
577
578@node Using Calc, History and Acknowledgements, Demonstration of Calc, Getting Started
579@section Using Calc
580
581@noindent
582Calc has several user interfaces that are specialized for
583different kinds of tasks. As well as Calc's standard interface,
584there are Quick mode, Keypad mode, and Embedded mode.
585
586@menu
587* Starting Calc::
588* The Standard Interface::
589* Quick Mode Overview::
590* Keypad Mode Overview::
591* Standalone Operation::
592* Embedded Mode Overview::
593* Other C-x * Commands::
594@end menu
595
596@node Starting Calc, The Standard Interface, Using Calc, Using Calc
597@subsection Starting Calc
598
599@noindent
600On most systems, you can type @kbd{C-x *} to start the Calculator.
601The key sequence @kbd{C-x *} is bound to the command @code{calc-dispatch},
602which can be rebound if convenient (@pxref{Customizing Calc}).
603
604When you press @kbd{C-x *}, Emacs waits for you to press a second key to
605complete the command. In this case, you will follow @kbd{C-x *} with a
606letter (upper- or lower-case, it doesn't matter for @kbd{C-x *}) that says
607which Calc interface you want to use.
608
609To get Calc's standard interface, type @kbd{C-x * c}. To get
610Keypad mode, type @kbd{C-x * k}. Type @kbd{C-x * ?} to get a brief
611list of the available options, and type a second @kbd{?} to get
612a complete list.
613
614To ease typing, @kbd{C-x * *} also works to start Calc. It starts the
615same interface (either @kbd{C-x * c} or @w{@kbd{C-x * k}}) that you last
616used, selecting the @kbd{C-x * c} interface by default.
617
618If @kbd{C-x *} doesn't work for you, you can always type explicit
619commands like @kbd{M-x calc} (for the standard user interface) or
620@w{@kbd{M-x calc-keypad}} (for Keypad mode). First type @kbd{M-x}
621(that's Meta with the letter @kbd{x}), then, at the prompt,
622type the full command (like @kbd{calc-keypad}) and press Return.
623
624The same commands (like @kbd{C-x * c} or @kbd{C-x * *}) that start
625the Calculator also turn it off if it is already on.
626
627@node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc
628@subsection The Standard Calc Interface
629
630@noindent
631@cindex Standard user interface
632Calc's standard interface acts like a traditional RPN calculator,
633operated by the normal Emacs keyboard. When you type @kbd{C-x * c}
634to start the Calculator, the Emacs screen splits into two windows
635with the file you were editing on top and Calc on the bottom.
636
637@smallexample
638@group
639
640...
641--**-Emacs: myfile (Fundamental)----All----------------------
642--- Emacs Calculator Mode --- |Emacs Calculator Trail
6432: 17.3 | 17.3
6441: -5 | 3
645 . | 2
646 | 4
647 | * 8
648 | ->-5
649 |
92e15881 650--%*-Calc: 12 Deg (Calculator)----All----- --%*- *Calc Trail*
4009494e
GM
651@end group
652@end smallexample
653
654In this figure, the mode-line for @file{myfile} has moved up and the
655``Calculator'' window has appeared below it. As you can see, Calc
656actually makes two windows side-by-side. The lefthand one is
657called the @dfn{stack window} and the righthand one is called the
658@dfn{trail window.} The stack holds the numbers involved in the
659calculation you are currently performing. The trail holds a complete
660record of all calculations you have done. In a desk calculator with
661a printer, the trail corresponds to the paper tape that records what
662you do.
663
664In this case, the trail shows that four numbers (17.3, 3, 2, and 4)
665were first entered into the Calculator, then the 2 and 4 were
666multiplied to get 8, then the 3 and 8 were subtracted to get @mathit{-5}.
667(The @samp{>} symbol shows that this was the most recent calculation.)
668The net result is the two numbers 17.3 and @mathit{-5} sitting on the stack.
669
670Most Calculator commands deal explicitly with the stack only, but
671there is a set of commands that allow you to search back through
672the trail and retrieve any previous result.
673
674Calc commands use the digits, letters, and punctuation keys.
675Shifted (i.e., upper-case) letters are different from lowercase
676letters. Some letters are @dfn{prefix} keys that begin two-letter
677commands. For example, @kbd{e} means ``enter exponent'' and shifted
678@kbd{E} means @expr{e^x}. With the @kbd{d} (``display modes'') prefix
679the letter ``e'' takes on very different meanings: @kbd{d e} means
680``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.''
681
682There is nothing stopping you from switching out of the Calc
683window and back into your editing window, say by using the Emacs
684@w{@kbd{C-x o}} (@code{other-window}) command. When the cursor is
685inside a regular window, Emacs acts just like normal. When the
686cursor is in the Calc stack or trail windows, keys are interpreted
687as Calc commands.
688
689When you quit by pressing @kbd{C-x * c} a second time, the Calculator
690windows go away but the actual Stack and Trail are not gone, just
691hidden. When you press @kbd{C-x * c} once again you will get the
692same stack and trail contents you had when you last used the
693Calculator.
694
695The Calculator does not remember its state between Emacs sessions.
696Thus if you quit Emacs and start it again, @kbd{C-x * c} will give you
697a fresh stack and trail. There is a command (@kbd{m m}) that lets
698you save your favorite mode settings between sessions, though.
699One of the things it saves is which user interface (standard or
700Keypad) you last used; otherwise, a freshly started Emacs will
701always treat @kbd{C-x * *} the same as @kbd{C-x * c}.
702
703The @kbd{q} key is another equivalent way to turn the Calculator off.
704
705If you type @kbd{C-x * b} first and then @kbd{C-x * c}, you get a
706full-screen version of Calc (@code{full-calc}) in which the stack and
707trail windows are still side-by-side but are now as tall as the whole
708Emacs screen. When you press @kbd{q} or @kbd{C-x * c} again to quit,
709the file you were editing before reappears. The @kbd{C-x * b} key
710switches back and forth between ``big'' full-screen mode and the
711normal partial-screen mode.
712
713Finally, @kbd{C-x * o} (@code{calc-other-window}) is like @kbd{C-x * c}
714except that the Calc window is not selected. The buffer you were
715editing before remains selected instead. @kbd{C-x * o} is a handy
716way to switch out of Calc momentarily to edit your file; type
717@kbd{C-x * c} to switch back into Calc when you are done.
718
719@node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc
720@subsection Quick Mode (Overview)
721
722@noindent
723@dfn{Quick mode} is a quick way to use Calc when you don't need the
724full complexity of the stack and trail. To use it, type @kbd{C-x * q}
725(@code{quick-calc}) in any regular editing buffer.
726
727Quick mode is very simple: It prompts you to type any formula in
728standard algebraic notation (like @samp{4 - 2/3}) and then displays
729the result at the bottom of the Emacs screen (@mathit{3.33333333333}
730in this case). You are then back in the same editing buffer you
731were in before, ready to continue editing or to type @kbd{C-x * q}
732again to do another quick calculation. The result of the calculation
733will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command
734at this point will yank the result into your editing buffer.
735
736Calc mode settings affect Quick mode, too, though you will have to
737go into regular Calc (with @kbd{C-x * c}) to change the mode settings.
738
739@c [fix-ref Quick Calculator mode]
740@xref{Quick Calculator}, for further information.
741
742@node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc
743@subsection Keypad Mode (Overview)
744
745@noindent
746@dfn{Keypad mode} is a mouse-based interface to the Calculator.
747It is designed for use with terminals that support a mouse. If you
748don't have a mouse, you will have to operate Keypad mode with your
749arrow keys (which is probably more trouble than it's worth).
750
751Type @kbd{C-x * k} to turn Keypad mode on or off. Once again you
752get two new windows, this time on the righthand side of the screen
753instead of at the bottom. The upper window is the familiar Calc
754Stack; the lower window is a picture of a typical calculator keypad.
755
756@tex
757\dimen0=\pagetotal%
758\advance \dimen0 by 24\baselineskip%
759\ifdim \dimen0>\pagegoal \vfill\eject \fi%
760\medskip
761@end tex
762@smallexample
763@group
764|--- Emacs Calculator Mode ---
765|2: 17.3
766|1: -5
767| .
92e15881 768|--%*-Calc: 12 Deg (Calcul
4009494e
GM
769|----+-----Calc 2.1------+----1
770|FLR |CEIL|RND |TRNC|CLN2|FLT |
771|----+----+----+----+----+----|
772| LN |EXP | |ABS |IDIV|MOD |
773|----+----+----+----+----+----|
774|SIN |COS |TAN |SQRT|y^x |1/x |
775|----+----+----+----+----+----|
776| ENTER |+/- |EEX |UNDO| <- |
777|-----+---+-+--+--+-+---++----|
778| INV | 7 | 8 | 9 | / |
779|-----+-----+-----+-----+-----|
780| HYP | 4 | 5 | 6 | * |
781|-----+-----+-----+-----+-----|
782|EXEC | 1 | 2 | 3 | - |
783|-----+-----+-----+-----+-----|
784| OFF | 0 | . | PI | + |
785|-----+-----+-----+-----+-----+
786@end group
787@end smallexample
788
789Keypad mode is much easier for beginners to learn, because there
790is no need to memorize lots of obscure key sequences. But not all
791commands in regular Calc are available on the Keypad. You can
792always switch the cursor into the Calc stack window to use
793standard Calc commands if you need. Serious Calc users, though,
794often find they prefer the standard interface over Keypad mode.
795
796To operate the Calculator, just click on the ``buttons'' of the
797keypad using your left mouse button. To enter the two numbers
798shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to
799add them together you would then click @kbd{+} (to get 12.3 on
800the stack).
801
802If you click the right mouse button, the top three rows of the
803keypad change to show other sets of commands, such as advanced
804math functions, vector operations, and operations on binary
805numbers.
806
807Because Keypad mode doesn't use the regular keyboard, Calc leaves
808the cursor in your original editing buffer. You can type in
809this buffer in the usual way while also clicking on the Calculator
810keypad. One advantage of Keypad mode is that you don't need an
811explicit command to switch between editing and calculating.
812
813If you press @kbd{C-x * b} first, you get a full-screen Keypad mode
814(@code{full-calc-keypad}) with three windows: The keypad in the lower
815left, the stack in the lower right, and the trail on top.
816
817@c [fix-ref Keypad Mode]
818@xref{Keypad Mode}, for further information.
819
820@node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc
821@subsection Standalone Operation
822
823@noindent
824@cindex Standalone Operation
825If you are not in Emacs at the moment but you wish to use Calc,
826you must start Emacs first. If all you want is to run Calc, you
827can give the commands:
828
829@example
830emacs -f full-calc
831@end example
832
833@noindent
834or
835
836@example
837emacs -f full-calc-keypad
838@end example
839
840@noindent
841which run a full-screen Calculator (as if by @kbd{C-x * b C-x * c}) or
842a full-screen X-based Calculator (as if by @kbd{C-x * b C-x * k}).
843In standalone operation, quitting the Calculator (by pressing
844@kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs
845itself.
846
847@node Embedded Mode Overview, Other C-x * Commands, Standalone Operation, Using Calc
848@subsection Embedded Mode (Overview)
849
850@noindent
851@dfn{Embedded mode} is a way to use Calc directly from inside an
852editing buffer. Suppose you have a formula written as part of a
853document like this:
854
855@smallexample
856@group
857The derivative of
858
859 ln(ln(x))
860
861is
862@end group
863@end smallexample
864
865@noindent
866and you wish to have Calc compute and format the derivative for
867you and store this derivative in the buffer automatically. To
868do this with Embedded mode, first copy the formula down to where
869you want the result to be:
870
871@smallexample
872@group
873The derivative of
874
875 ln(ln(x))
876
877is
878
879 ln(ln(x))
880@end group
881@end smallexample
882
883Now, move the cursor onto this new formula and press @kbd{C-x * e}.
884Calc will read the formula (using the surrounding blank lines to
885tell how much text to read), then push this formula (invisibly)
886onto the Calc stack. The cursor will stay on the formula in the
887editing buffer, but the buffer's mode line will change to look
888like the Calc mode line (with mode indicators like @samp{12 Deg}
889and so on). Even though you are still in your editing buffer,
890the keyboard now acts like the Calc keyboard, and any new result
891you get is copied from the stack back into the buffer. To take
892the derivative, you would type @kbd{a d x @key{RET}}.
893
894@smallexample
895@group
896The derivative of
897
898 ln(ln(x))
899
900is
901
9021 / ln(x) x
903@end group
904@end smallexample
905
906To make this look nicer, you might want to press @kbd{d =} to center
907the formula, and even @kbd{d B} to use Big display mode.
908
909@smallexample
910@group
911The derivative of
912
913 ln(ln(x))
914
915is
916% [calc-mode: justify: center]
917% [calc-mode: language: big]
918
919 1
920 -------
921 ln(x) x
922@end group
923@end smallexample
924
925Calc has added annotations to the file to help it remember the modes
926that were used for this formula. They are formatted like comments
927in the @TeX{} typesetting language, just in case you are using @TeX{} or
928La@TeX{}. (In this example @TeX{} is not being used, so you might want
929to move these comments up to the top of the file or otherwise put them
930out of the way.)
931
932As an extra flourish, we can add an equation number using a
933righthand label: Type @kbd{d @} (1) @key{RET}}.
934
935@smallexample
936@group
937% [calc-mode: justify: center]
938% [calc-mode: language: big]
939% [calc-mode: right-label: " (1)"]
940
941 1
942 ------- (1)
943 ln(x) x
944@end group
945@end smallexample
946
947To leave Embedded mode, type @kbd{C-x * e} again. The mode line
948and keyboard will revert to the way they were before.
949
950The related command @kbd{C-x * w} operates on a single word, which
951generally means a single number, inside text. It uses any
952non-numeric characters rather than blank lines to delimit the
953formula it reads. Here's an example of its use:
954
955@smallexample
956A slope of one-third corresponds to an angle of 1 degrees.
957@end smallexample
958
959Place the cursor on the @samp{1}, then type @kbd{C-x * w} to enable
960Embedded mode on that number. Now type @kbd{3 /} (to get one-third),
961and @kbd{I T} (the Inverse Tangent converts a slope into an angle),
962then @w{@kbd{C-x * w}} again to exit Embedded mode.
963
964@smallexample
965A slope of one-third corresponds to an angle of 18.4349488229 degrees.
966@end smallexample
967
968@c [fix-ref Embedded Mode]
969@xref{Embedded Mode}, for full details.
970
971@node Other C-x * Commands, , Embedded Mode Overview, Using Calc
972@subsection Other @kbd{C-x *} Commands
973
974@noindent
975Two more Calc-related commands are @kbd{C-x * g} and @kbd{C-x * r},
976which ``grab'' data from a selected region of a buffer into the
977Calculator. The region is defined in the usual Emacs way, by
978a ``mark'' placed at one end of the region, and the Emacs
979cursor or ``point'' placed at the other.
980
981The @kbd{C-x * g} command reads the region in the usual left-to-right,
982top-to-bottom order. The result is packaged into a Calc vector
983of numbers and placed on the stack. Calc (in its standard
984user interface) is then started. Type @kbd{v u} if you want
985to unpack this vector into separate numbers on the stack. Also,
986@kbd{C-u C-x * g} interprets the region as a single number or
987formula.
988
989The @kbd{C-x * r} command reads a rectangle, with the point and
990mark defining opposite corners of the rectangle. The result
991is a matrix of numbers on the Calculator stack.
992
993Complementary to these is @kbd{C-x * y}, which ``yanks'' the
994value at the top of the Calc stack back into an editing buffer.
995If you type @w{@kbd{C-x * y}} while in such a buffer, the value is
996yanked at the current position. If you type @kbd{C-x * y} while
997in the Calc buffer, Calc makes an educated guess as to which
998editing buffer you want to use. The Calc window does not have
999to be visible in order to use this command, as long as there
1000is something on the Calc stack.
1001
1002Here, for reference, is the complete list of @kbd{C-x *} commands.
1003The shift, control, and meta keys are ignored for the keystroke
1004following @kbd{C-x *}.
1005
1006@noindent
1007Commands for turning Calc on and off:
1008
1009@table @kbd
1010@item *
1011Turn Calc on or off, employing the same user interface as last time.
1012
1013@item =, +, -, /, \, &, #
1014Alternatives for @kbd{*}.
1015
1016@item C
1017Turn Calc on or off using its standard bottom-of-the-screen
1018interface. If Calc is already turned on but the cursor is not
1019in the Calc window, move the cursor into the window.
1020
1021@item O
1022Same as @kbd{C}, but don't select the new Calc window. If
1023Calc is already turned on and the cursor is in the Calc window,
1024move it out of that window.
1025
1026@item B
1027Control whether @kbd{C-x * c} and @kbd{C-x * k} use the full screen.
1028
1029@item Q
1030Use Quick mode for a single short calculation.
1031
1032@item K
1033Turn Calc Keypad mode on or off.
1034
1035@item E
1036Turn Calc Embedded mode on or off at the current formula.
1037
1038@item J
1039Turn Calc Embedded mode on or off, select the interesting part.
1040
1041@item W
1042Turn Calc Embedded mode on or off at the current word (number).
1043
1044@item Z
1045Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command.
1046
1047@item X
1048Quit Calc; turn off standard, Keypad, or Embedded mode if on.
1049(This is like @kbd{q} or @key{OFF} inside of Calc.)
1050@end table
1051@iftex
1052@sp 2
1053@end iftex
1054
1055@noindent
1056Commands for moving data into and out of the Calculator:
1057
1058@table @kbd
1059@item G
1060Grab the region into the Calculator as a vector.
1061
1062@item R
1063Grab the rectangular region into the Calculator as a matrix.
1064
1065@item :
1066Grab the rectangular region and compute the sums of its columns.
1067
1068@item _
1069Grab the rectangular region and compute the sums of its rows.
1070
1071@item Y
1072Yank a value from the Calculator into the current editing buffer.
1073@end table
1074@iftex
1075@sp 2
1076@end iftex
1077
1078@noindent
1079Commands for use with Embedded mode:
1080
1081@table @kbd
1082@item A
1083``Activate'' the current buffer. Locate all formulas that
1084contain @samp{:=} or @samp{=>} symbols and record their locations
1085so that they can be updated automatically as variables are changed.
1086
1087@item D
1088Duplicate the current formula immediately below and select
1089the duplicate.
1090
1091@item F
1092Insert a new formula at the current point.
1093
1094@item N
1095Move the cursor to the next active formula in the buffer.
1096
1097@item P
1098Move the cursor to the previous active formula in the buffer.
1099
1100@item U
1101Update (i.e., as if by the @kbd{=} key) the formula at the current point.
1102
1103@item `
1104Edit (as if by @code{calc-edit}) the formula at the current point.
1105@end table
1106@iftex
1107@sp 2
1108@end iftex
1109
1110@noindent
1111Miscellaneous commands:
1112
1113@table @kbd
1114@item I
1115Run the Emacs Info system to read the Calc manual.
1116(This is the same as @kbd{h i} inside of Calc.)
1117
1118@item T
1119Run the Emacs Info system to read the Calc Tutorial.
1120
1121@item S
1122Run the Emacs Info system to read the Calc Summary.
1123
1124@item L
1125Load Calc entirely into memory. (Normally the various parts
1126are loaded only as they are needed.)
1127
1128@item M
1129Read a region of written keystroke names (like @kbd{C-n a b c @key{RET}})
1130and record them as the current keyboard macro.
1131
1132@item 0
1133(This is the ``zero'' digit key.) Reset the Calculator to
1134its initial state: Empty stack, and initial mode settings.
1135@end table
1136
1137@node History and Acknowledgements, , Using Calc, Getting Started
1138@section History and Acknowledgements
1139
1140@noindent
1141Calc was originally started as a two-week project to occupy a lull
1142in the author's schedule. Basically, a friend asked if I remembered
1143the value of
1144@texline @math{2^{32}}.
1145@infoline @expr{2^32}.
1146I didn't offhand, but I said, ``that's easy, just call up an
1147@code{xcalc}.'' @code{Xcalc} duly reported that the answer to our
1148question was @samp{4.294967e+09}---with no way to see the full ten
1149digits even though we knew they were there in the program's memory! I
1150was so annoyed, I vowed to write a calculator of my own, once and for
1151all.
1152
1153I chose Emacs Lisp, a) because I had always been curious about it
1154and b) because, being only a text editor extension language after
1155all, Emacs Lisp would surely reach its limits long before the project
1156got too far out of hand.
1157
1158To make a long story short, Emacs Lisp turned out to be a distressingly
1159solid implementation of Lisp, and the humble task of calculating
1160turned out to be more open-ended than one might have expected.
1161
1162Emacs Lisp didn't have built-in floating point math (now it does), so
4bb49b43
JB
1163this had to be simulated in software. In fact, Emacs integers would
1164only comfortably fit six decimal digits or so---not enough for a decent
1165calculator. So I had to write my own high-precision integer code as
1166well, and once I had this I figured that arbitrary-size integers were
1167just as easy as large integers. Arbitrary floating-point precision was
1168the logical next step. Also, since the large integer arithmetic was
1169there anyway it seemed only fair to give the user direct access to it,
1170which in turn made it practical to support fractions as well as floats.
1171All these features inspired me to look around for other data types that
1172might be worth having.
4009494e
GM
1173
1174Around this time, my friend Rick Koshi showed me his nifty new HP-28
1175calculator. It allowed the user to manipulate formulas as well as
1176numerical quantities, and it could also operate on matrices. I
1177decided that these would be good for Calc to have, too. And once
1178things had gone this far, I figured I might as well take a look at
1179serious algebra systems for further ideas. Since these systems did
1180far more than I could ever hope to implement, I decided to focus on
1181rewrite rules and other programming features so that users could
1182implement what they needed for themselves.
1183
1184Rick complained that matrices were hard to read, so I put in code to
1185format them in a 2D style. Once these routines were in place, Big mode
1186was obligatory. Gee, what other language modes would be useful?
1187
1188Scott Hemphill and Allen Knutson, two friends with a strong mathematical
1189bent, contributed ideas and algorithms for a number of Calc features
1190including modulo forms, primality testing, and float-to-fraction conversion.
1191
1192Units were added at the eager insistence of Mass Sivilotti. Later,
1193Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable
1194expert assistance with the units table. As far as I can remember, the
1195idea of using algebraic formulas and variables to represent units dates
1196back to an ancient article in Byte magazine about muMath, an early
1197algebra system for microcomputers.
1198
1199Many people have contributed to Calc by reporting bugs and suggesting
1200features, large and small. A few deserve special mention: Tim Peters,
1201who helped develop the ideas that led to the selection commands, rewrite
1202rules, and many other algebra features;
1203@texline Fran\c{c}ois
1204@infoline Francois
1205Pinard, who contributed an early prototype of the Calc Summary appendix
1206as well as providing valuable suggestions in many other areas of Calc;
1207Carl Witty, whose eagle eyes discovered many typographical and factual
1208errors in the Calc manual; Tim Kay, who drove the development of
1209Embedded mode; Ove Ewerlid, who made many suggestions relating to the
1210algebra commands and contributed some code for polynomial operations;
f10d0e80 1211Randal Schwartz, who suggested the @code{calc-eval} function; Juha
4009494e 1212Sarlin, who first worked out how to split Calc into quickly-loading
f10d0e80
JB
1213parts; Bob Weiner, who helped immensely with the Lucid Emacs port; and
1214Robert J. Chassell, who suggested the Calc Tutorial and exercises as
1215well as many other things.
4009494e
GM
1216
1217@cindex Bibliography
1218@cindex Knuth, Art of Computer Programming
1219@cindex Numerical Recipes
1220@c Should these be expanded into more complete references?
1221Among the books used in the development of Calc were Knuth's @emph{Art
1222of Computer Programming} (especially volume II, @emph{Seminumerical
1223Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky,
1224and Vetterling; Bevington's @emph{Data Reduction and Error Analysis
1225for the Physical Sciences}; @emph{Concrete Mathematics} by Graham,
1226Knuth, and Patashnik; Steele's @emph{Common Lisp, the Language}; the
1227@emph{CRC Standard Math Tables} (William H. Beyer, ed.); and
1228Abramowitz and Stegun's venerable @emph{Handbook of Mathematical
1229Functions}. Also, of course, Calc could not have been written without
1230the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil Lewis and
1231Dan LaLiberte.
1232
1233Final thanks go to Richard Stallman, without whose fine implementations
1234of the Emacs editor, language, and environment, Calc would have been
1235finished in two weeks.
1236
1237@c [tutorial]
1238
1239@ifinfo
1240@c This node is accessed by the `C-x * t' command.
1241@node Interactive Tutorial, Tutorial, Getting Started, Top
1242@chapter Tutorial
1243
1244@noindent
1245Some brief instructions on using the Emacs Info system for this tutorial:
1246
1247Press the space bar and Delete keys to go forward and backward in a
1248section by screenfuls (or use the regular Emacs scrolling commands
1249for this).
1250
1251Press @kbd{n} or @kbd{p} to go to the Next or Previous section.
1252If the section has a @dfn{menu}, press a digit key like @kbd{1}
1253or @kbd{2} to go to a sub-section from the menu. Press @kbd{u} to
1254go back up from a sub-section to the menu it is part of.
1255
1256Exercises in the tutorial all have cross-references to the
1257appropriate page of the ``answers'' section. Press @kbd{f}, then
1258the exercise number, to see the answer to an exercise. After
1259you have followed a cross-reference, you can press the letter
1260@kbd{l} to return to where you were before.
1261
1262You can press @kbd{?} at any time for a brief summary of Info commands.
1263
1264Press @kbd{1} now to enter the first section of the Tutorial.
1265
1266@menu
1267* Tutorial::
1268@end menu
1269
1270@node Tutorial, Introduction, Interactive Tutorial, Top
1271@end ifinfo
1272@ifnotinfo
1273@node Tutorial, Introduction, Getting Started, Top
1274@end ifnotinfo
1275@chapter Tutorial
1276
1277@noindent
1278This chapter explains how to use Calc and its many features, in
1279a step-by-step, tutorial way. You are encouraged to run Calc and
1280work along with the examples as you read (@pxref{Starting Calc}).
1281If you are already familiar with advanced calculators, you may wish
1282@c [not-split]
1283to skip on to the rest of this manual.
1284@c [when-split]
1285@c to skip on to volume II of this manual, the @dfn{Calc Reference}.
1286
1287@c [fix-ref Embedded Mode]
1288This tutorial describes the standard user interface of Calc only.
1289The Quick mode and Keypad mode interfaces are fairly
1290self-explanatory. @xref{Embedded Mode}, for a description of
1291the Embedded mode interface.
1292
1293The easiest way to read this tutorial on-line is to have two windows on
1294your Emacs screen, one with Calc and one with the Info system. (If you
1295have a printed copy of the manual you can use that instead.) Press
1296@kbd{C-x * c} to turn Calc on or to switch into the Calc window, and
1297press @kbd{C-x * i} to start the Info system or to switch into its window.
1298
1299This tutorial is designed to be done in sequence. But the rest of this
1300manual does not assume you have gone through the tutorial. The tutorial
1301does not cover everything in the Calculator, but it touches on most
1302general areas.
1303
1304@ifnottex
1305You may wish to print out a copy of the Calc Summary and keep notes on
1306it as you learn Calc. @xref{About This Manual}, to see how to make a
1307printed summary. @xref{Summary}.
1308@end ifnottex
1309@iftex
1310The Calc Summary at the end of the reference manual includes some blank
1311space for your own use. You may wish to keep notes there as you learn
1312Calc.
1313@end iftex
1314
1315@menu
1316* Basic Tutorial::
1317* Arithmetic Tutorial::
1318* Vector/Matrix Tutorial::
1319* Types Tutorial::
1320* Algebra Tutorial::
1321* Programming Tutorial::
1322
1323* Answers to Exercises::
1324@end menu
1325
1326@node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial
1327@section Basic Tutorial
1328
1329@noindent
1330In this section, we learn how RPN and algebraic-style calculations
1331work, how to undo and redo an operation done by mistake, and how
1332to control various modes of the Calculator.
1333
1334@menu
1335* RPN Tutorial:: Basic operations with the stack.
1336* Algebraic Tutorial:: Algebraic entry; variables.
1337* Undo Tutorial:: If you make a mistake: Undo and the trail.
1338* Modes Tutorial:: Common mode-setting commands.
1339@end menu
1340
1341@node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial
1342@subsection RPN Calculations and the Stack
1343
1344@cindex RPN notation
1345@ifnottex
1346@noindent
1347Calc normally uses RPN notation. You may be familiar with the RPN
1348system from Hewlett-Packard calculators, FORTH, or PostScript.
1349(Reverse Polish Notation, RPN, is named after the Polish mathematician
1350Jan Lukasiewicz.)
1351@end ifnottex
1352@tex
1353\noindent
1354Calc normally uses RPN notation. You may be familiar with the RPN
1355system from Hewlett-Packard calculators, FORTH, or PostScript.
1356(Reverse Polish Notation, RPN, is named after the Polish mathematician
1357Jan \L ukasiewicz.)
1358@end tex
1359
1360The central component of an RPN calculator is the @dfn{stack}. A
1361calculator stack is like a stack of dishes. New dishes (numbers) are
1362added at the top of the stack, and numbers are normally only removed
1363from the top of the stack.
1364
1365@cindex Operators
1366@cindex Operands
1367In an operation like @expr{2+3}, the 2 and 3 are called the @dfn{operands}
1368and the @expr{+} is the @dfn{operator}. In an RPN calculator you always
1369enter the operands first, then the operator. Each time you type a
1370number, Calc adds or @dfn{pushes} it onto the top of the Stack.
1371When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate
1372number of operands from the stack and pushes back the result.
1373
1374Thus we could add the numbers 2 and 3 in an RPN calculator by typing:
1375@kbd{2 @key{RET} 3 @key{RET} +}. (The @key{RET} key, Return, corresponds to
1376the @key{ENTER} key on traditional RPN calculators.) Try this now if
1377you wish; type @kbd{C-x * c} to switch into the Calc window (you can type
1378@kbd{C-x * c} again or @kbd{C-x * o} to switch back to the Tutorial window).
1379The first four keystrokes ``push'' the numbers 2 and 3 onto the stack.
1380The @kbd{+} key ``pops'' the top two numbers from the stack, adds them,
1381and pushes the result (5) back onto the stack. Here's how the stack
1382will look at various points throughout the calculation:
1383
1384@smallexample
1385@group
1386 . 1: 2 2: 2 1: 5 .
1387 . 1: 3 .
1388 .
1389
1390 C-x * c 2 @key{RET} 3 @key{RET} + @key{DEL}
1391@end group
1392@end smallexample
1393
1394The @samp{.} symbol is a marker that represents the top of the stack.
1395Note that the ``top'' of the stack is really shown at the bottom of
1396the Stack window. This may seem backwards, but it turns out to be
1397less distracting in regular use.
1398
1399@cindex Stack levels
1400@cindex Levels of stack
1401The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level
1402numbers}. Old RPN calculators always had four stack levels called
1403@expr{x}, @expr{y}, @expr{z}, and @expr{t}. Calc's stack can grow
1404as large as you like, so it uses numbers instead of letters. Some
1405stack-manipulation commands accept a numeric argument that says
1406which stack level to work on. Normal commands like @kbd{+} always
1407work on the top few levels of the stack.
1408
1409@c [fix-ref Truncating the Stack]
1410The Stack buffer is just an Emacs buffer, and you can move around in
1411it using the regular Emacs motion commands. But no matter where the
1412cursor is, even if you have scrolled the @samp{.} marker out of
1413view, most Calc commands always move the cursor back down to level 1
1414before doing anything. It is possible to move the @samp{.} marker
1415upwards through the stack, temporarily ``hiding'' some numbers from
1416commands like @kbd{+}. This is called @dfn{stack truncation} and
1417we will not cover it in this tutorial; @pxref{Truncating the Stack},
1418if you are interested.
1419
1420You don't really need the second @key{RET} in @kbd{2 @key{RET} 3
1421@key{RET} +}. That's because if you type any operator name or
1422other non-numeric key when you are entering a number, the Calculator
1423automatically enters that number and then does the requested command.
1424Thus @kbd{2 @key{RET} 3 +} will work just as well.
1425
1426Examples in this tutorial will often omit @key{RET} even when the
1427stack displays shown would only happen if you did press @key{RET}:
1428
1429@smallexample
1430@group
14311: 2 2: 2 1: 5
1432 . 1: 3 .
1433 .
1434
1435 2 @key{RET} 3 +
1436@end group
1437@end smallexample
1438
1439@noindent
1440Here, after pressing @kbd{3} the stack would really show @samp{1: 2}
1441with @samp{Calc:@: 3} in the minibuffer. In these situations, you can
1442press the optional @key{RET} to see the stack as the figure shows.
1443
1444(@bullet{}) @strong{Exercise 1.} (This tutorial will include exercises
1445at various points. Try them if you wish. Answers to all the exercises
1446are located at the end of the Tutorial chapter. Each exercise will
1447include a cross-reference to its particular answer. If you are
1448reading with the Emacs Info system, press @kbd{f} and the
1449exercise number to go to the answer, then the letter @kbd{l} to
1450return to where you were.)
1451
1452@noindent
1453Here's the first exercise: What will the keystrokes @kbd{1 @key{RET} 2
1454@key{RET} 3 @key{RET} 4 + * -} compute? (@samp{*} is the symbol for
1455multiplication.) Figure it out by hand, then try it with Calc to see
1456if you're right. @xref{RPN Answer 1, 1}. (@bullet{})
1457
1458(@bullet{}) @strong{Exercise 2.} Compute
1459@texline @math{(2\times4) + (7\times9.4) + {5\over4}}
1460@infoline @expr{2*4 + 7*9.5 + 5/4}
1461using the stack. @xref{RPN Answer 2, 2}. (@bullet{})
1462
1463The @key{DEL} key is called Backspace on some keyboards. It is
1464whatever key you would use to correct a simple typing error when
1465regularly using Emacs. The @key{DEL} key pops and throws away the
1466top value on the stack. (You can still get that value back from
1467the Trail if you should need it later on.) There are many places
1468in this tutorial where we assume you have used @key{DEL} to erase the
1469results of the previous example at the beginning of a new example.
1470In the few places where it is really important to use @key{DEL} to
1471clear away old results, the text will remind you to do so.
1472
1473(It won't hurt to let things accumulate on the stack, except that
1474whenever you give a display-mode-changing command Calc will have to
1475spend a long time reformatting such a large stack.)
1476
1477Since the @kbd{-} key is also an operator (it subtracts the top two
1478stack elements), how does one enter a negative number? Calc uses
1479the @kbd{_} (underscore) key to act like the minus sign in a number.
1480So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key
1481will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine.
1482
1483You can also press @kbd{n}, which means ``change sign.'' It changes
1484the number at the top of the stack (or the number being entered)
1485from positive to negative or vice-versa: @kbd{5 n @key{RET}}.
1486
1487@cindex Duplicating a stack entry
1488If you press @key{RET} when you're not entering a number, the effect
1489is to duplicate the top number on the stack. Consider this calculation:
1490
1491@smallexample
1492@group
14931: 3 2: 3 1: 9 2: 9 1: 81
1494 . 1: 3 . 1: 9 .
1495 . .
1496
1497 3 @key{RET} @key{RET} * @key{RET} *
1498@end group
1499@end smallexample
1500
1501@noindent
1502(Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^},
1503to raise 3 to the fourth power.)
1504
1505The space-bar key (denoted @key{SPC} here) performs the same function
1506as @key{RET}; you could replace all three occurrences of @key{RET} in
1507the above example with @key{SPC} and the effect would be the same.
1508
1509@cindex Exchanging stack entries
1510Another stack manipulation key is @key{TAB}. This exchanges the top
1511two stack entries. Suppose you have computed @kbd{2 @key{RET} 3 +}
1512to get 5, and then you realize what you really wanted to compute
1513was @expr{20 / (2+3)}.
1514
1515@smallexample
1516@group
15171: 5 2: 5 2: 20 1: 4
1518 . 1: 20 1: 5 .
1519 . .
1520
1521 2 @key{RET} 3 + 20 @key{TAB} /
1522@end group
1523@end smallexample
1524
1525@noindent
1526Planning ahead, the calculation would have gone like this:
1527
1528@smallexample
1529@group
15301: 20 2: 20 3: 20 2: 20 1: 4
1531 . 1: 2 2: 2 1: 5 .
1532 . 1: 3 .
1533 .
1534
1535 20 @key{RET} 2 @key{RET} 3 + /
1536@end group
1537@end smallexample
1538
1539A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type
1540@key{TAB}). It rotates the top three elements of the stack upward,
1541bringing the object in level 3 to the top.
1542
1543@smallexample
1544@group
15451: 10 2: 10 3: 10 3: 20 3: 30
1546 . 1: 20 2: 20 2: 30 2: 10
1547 . 1: 30 1: 10 1: 20
1548 . . .
1549
1550 10 @key{RET} 20 @key{RET} 30 @key{RET} M-@key{TAB} M-@key{TAB}
1551@end group
1552@end smallexample
1553
1554(@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are
1555on the stack. Figure out how to add one to the number in level 2
1556without affecting the rest of the stack. Also figure out how to add
1557one to the number in level 3. @xref{RPN Answer 3, 3}. (@bullet{})
1558
1559Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two
1560arguments from the stack and push a result. Operations like @kbd{n} and
1561@kbd{Q} (square root) pop a single number and push the result. You can
1562think of them as simply operating on the top element of the stack.
1563
1564@smallexample
1565@group
15661: 3 1: 9 2: 9 1: 25 1: 5
1567 . . 1: 16 . .
1568 .
1569
1570 3 @key{RET} @key{RET} * 4 @key{RET} @key{RET} * + Q
1571@end group
1572@end smallexample
1573
1574@noindent
1575(Note that capital @kbd{Q} means to hold down the Shift key while
1576typing @kbd{q}. Remember, plain unshifted @kbd{q} is the Quit command.)
1577
1578@cindex Pythagorean Theorem
1579Here we've used the Pythagorean Theorem to determine the hypotenuse of a
1580right triangle. Calc actually has a built-in command for that called
1581@kbd{f h}, but let's suppose we can't remember the necessary keystrokes.
1582We can still enter it by its full name using @kbd{M-x} notation:
1583
1584@smallexample
1585@group
15861: 3 2: 3 1: 5
1587 . 1: 4 .
1588 .
1589
1590 3 @key{RET} 4 @key{RET} M-x calc-hypot
1591@end group
1592@end smallexample
1593
1594All Calculator commands begin with the word @samp{calc-}. Since it
1595gets tiring to type this, Calc provides an @kbd{x} key which is just
1596like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-}
1597prefix for you:
1598
1599@smallexample
1600@group
16011: 3 2: 3 1: 5
1602 . 1: 4 .
1603 .
1604
1605 3 @key{RET} 4 @key{RET} x hypot
1606@end group
1607@end smallexample
1608
1609What happens if you take the square root of a negative number?
1610
1611@smallexample
1612@group
16131: 4 1: -4 1: (0, 2)
1614 . . .
1615
1616 4 @key{RET} n Q
1617@end group
1618@end smallexample
1619
1620@noindent
1621The notation @expr{(a, b)} represents a complex number.
1622Complex numbers are more traditionally written @expr{a + b i};
1623Calc can display in this format, too, but for now we'll stick to the
1624@expr{(a, b)} notation.
1625
1626If you don't know how complex numbers work, you can safely ignore this
1627feature. Complex numbers only arise from operations that would be
1628errors in a calculator that didn't have complex numbers. (For example,
1629taking the square root or logarithm of a negative number produces a
1630complex result.)
1631
1632Complex numbers are entered in the notation shown. The @kbd{(} and
1633@kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.''
1634
1635@smallexample
1636@group
16371: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3)
1638 . 1: 2 . 3 .
1639 . .
1640
1641 ( 2 , 3 )
1642@end group
1643@end smallexample
1644
1645You can perform calculations while entering parts of incomplete objects.
1646However, an incomplete object cannot actually participate in a calculation:
1647
1648@smallexample
1649@group
16501: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ...
1651 . 1: 2 2: 2 5 5
1652 . 1: 3 . .
1653 .
1654 (error)
1655 ( 2 @key{RET} 3 + +
1656@end group
1657@end smallexample
1658
1659@noindent
1660Adding 5 to an incomplete object makes no sense, so the last command
1661produces an error message and leaves the stack the same.
1662
1663Incomplete objects can't participate in arithmetic, but they can be
1664moved around by the regular stack commands.
1665
1666@smallexample
1667@group
16682: 2 3: 2 3: 3 1: ( ... 1: (2, 3)
16691: 3 2: 3 2: ( ... 2 .
1670 . 1: ( ... 1: 2 3
1671 . . .
1672
16732 @key{RET} 3 @key{RET} ( M-@key{TAB} M-@key{TAB} )
1674@end group
1675@end smallexample
1676
1677@noindent
1678Note that the @kbd{,} (comma) key did not have to be used here.
1679When you press @kbd{)} all the stack entries between the incomplete
1680entry and the top are collected, so there's never really a reason
1681to use the comma. It's up to you.
1682
1683(@bullet{}) @strong{Exercise 4.} To enter the complex number @expr{(2, 3)},
1684your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}. What happened?
1685(Joe thought of a clever way to correct his mistake in only two
1686keystrokes, but it didn't quite work. Try it to find out why.)
1687@xref{RPN Answer 4, 4}. (@bullet{})
1688
1689Vectors are entered the same way as complex numbers, but with square
1690brackets in place of parentheses. We'll meet vectors again later in
1691the tutorial.
1692
1693Any Emacs command can be given a @dfn{numeric prefix argument} by
1694typing a series of @key{META}-digits beforehand. If @key{META} is
1695awkward for you, you can instead type @kbd{C-u} followed by the
1696necessary digits. Numeric prefix arguments can be negative, as in
1697@kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}. Calc commands use numeric
1698prefix arguments in a variety of ways. For example, a numeric prefix
1699on the @kbd{+} operator adds any number of stack entries at once:
1700
1701@smallexample
1702@group
17031: 10 2: 10 3: 10 3: 10 1: 60
1704 . 1: 20 2: 20 2: 20 .
1705 . 1: 30 1: 30
1706 . .
1707
1708 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u 3 +
1709@end group
1710@end smallexample
1711
1712For stack manipulation commands like @key{RET}, a positive numeric
1713prefix argument operates on the top @var{n} stack entries at once. A
1714negative argument operates on the entry in level @var{n} only. An
1715argument of zero operates on the entire stack. In this example, we copy
1716the second-to-top element of the stack:
1717
1718@smallexample
1719@group
17201: 10 2: 10 3: 10 3: 10 4: 10
1721 . 1: 20 2: 20 2: 20 3: 20
1722 . 1: 30 1: 30 2: 30
1723 . . 1: 20
1724 .
1725
1726 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u -2 @key{RET}
1727@end group
1728@end smallexample
1729
1730@cindex Clearing the stack
1731@cindex Emptying the stack
1732Another common idiom is @kbd{M-0 @key{DEL}}, which clears the stack.
1733(The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the
1734entire stack.)
1735
1736@node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial
1737@subsection Algebraic-Style Calculations
1738
1739@noindent
1740If you are not used to RPN notation, you may prefer to operate the
1741Calculator in Algebraic mode, which is closer to the way
1742non-RPN calculators work. In Algebraic mode, you enter formulas
1743in traditional @expr{2+3} notation.
1744
1745@strong{Warning:} Note that @samp{/} has lower precedence than
1746@samp{*}, so that @samp{a/b*c} is interpreted as @samp{a/(b*c)}. See
1747below for details.
1748
1749You don't really need any special ``mode'' to enter algebraic formulas.
1750You can enter a formula at any time by pressing the apostrophe (@kbd{'})
1751key. Answer the prompt with the desired formula, then press @key{RET}.
1752The formula is evaluated and the result is pushed onto the RPN stack.
1753If you don't want to think in RPN at all, you can enter your whole
1754computation as a formula, read the result from the stack, then press
1755@key{DEL} to delete it from the stack.
1756
1757Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}.
1758The result should be the number 9.
1759
1760Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*},
1761@samp{/}, and @samp{^}. You can use parentheses to make the order
1762of evaluation clear. In the absence of parentheses, @samp{^} is
1763evaluated first, then @samp{*}, then @samp{/}, then finally
1764@samp{+} and @samp{-}. For example, the expression
1765
1766@example
17672 + 3*4*5 / 6*7^8 - 9
1768@end example
1769
1770@noindent
1771is equivalent to
1772
1773@example
17742 + ((3*4*5) / (6*(7^8)) - 9
1775@end example
1776
1777@noindent
1778or, in large mathematical notation,
1779
1780@ifnottex
1781@example
1782@group
1783 3 * 4 * 5
17842 + --------- - 9
1785 8
1786 6 * 7
1787@end group
1788@end example
1789@end ifnottex
1790@tex
1791\turnoffactive
1792\beforedisplay
1793$$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$
1794\afterdisplay
1795@end tex
1796
1797@noindent
1798The result of this expression will be the number @mathit{-6.99999826533}.
1799
1800Calc's order of evaluation is the same as for most computer languages,
1801except that @samp{*} binds more strongly than @samp{/}, as the above
1802example shows. As in normal mathematical notation, the @samp{*} symbol
1803can often be omitted: @samp{2 a} is the same as @samp{2*a}.
1804
1805Operators at the same level are evaluated from left to right, except
1806that @samp{^} is evaluated from right to left. Thus, @samp{2-3-4} is
1807equivalent to @samp{(2-3)-4} or @mathit{-5}, whereas @samp{2^3^4} is equivalent
1808to @samp{2^(3^4)} (a very large integer; try it!).
1809
1810If you tire of typing the apostrophe all the time, there is
1811Algebraic mode, where Calc automatically senses
1812when you are about to type an algebraic expression. To enter this
1813mode, press the two letters @w{@kbd{m a}}. (An @samp{Alg} indicator
1814should appear in the Calc window's mode line.)
1815
1816Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}.
1817
1818In Algebraic mode, when you press any key that would normally begin
1819entering a number (such as a digit, a decimal point, or the @kbd{_}
1820key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins
1821an algebraic entry.
1822
1823Functions which do not have operator symbols like @samp{+} and @samp{*}
1824must be entered in formulas using function-call notation. For example,
1825the function name corresponding to the square-root key @kbd{Q} is
1826@code{sqrt}. To compute a square root in a formula, you would use
1827the notation @samp{sqrt(@var{x})}.
1828
1829Press the apostrophe, then type @kbd{sqrt(5*2) - 3}. The result should
1830be @expr{0.16227766017}.
1831
1832Note that if the formula begins with a function name, you need to use
1833the apostrophe even if you are in Algebraic mode. If you type @kbd{arcsin}
1834out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite
1835command, and the @kbd{csin} will be taken as the name of the rewrite
1836rule to use!
1837
1838Some people prefer to enter complex numbers and vectors in algebraic
1839form because they find RPN entry with incomplete objects to be too
1840distracting, even though they otherwise use Calc as an RPN calculator.
1841
1842Still in Algebraic mode, type:
1843
1844@smallexample
1845@group
18461: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1)
1847 . 1: (1, -2) . 1: 1 .
1848 . .
1849
1850 (2,3) @key{RET} (1,-2) @key{RET} * 1 @key{RET} +
1851@end group
1852@end smallexample
1853
1854Algebraic mode allows us to enter complex numbers without pressing
1855an apostrophe first, but it also means we need to press @key{RET}
1856after every entry, even for a simple number like @expr{1}.
1857
1858(You can type @kbd{C-u m a} to enable a special Incomplete Algebraic
1859mode in which the @kbd{(} and @kbd{[} keys use algebraic entry even
1860though regular numeric keys still use RPN numeric entry. There is also
1861Total Algebraic mode, started by typing @kbd{m t}, in which all
1862normal keys begin algebraic entry. You must then use the @key{META} key
1863to type Calc commands: @kbd{M-m t} to get back out of Total Algebraic
1864mode, @kbd{M-q} to quit, etc.)
1865
1866If you're still in Algebraic mode, press @kbd{m a} again to turn it off.
1867
1868Actual non-RPN calculators use a mixture of algebraic and RPN styles.
1869In general, operators of two numbers (like @kbd{+} and @kbd{*})
1870use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q})
1871use RPN form. Also, a non-RPN calculator allows you to see the
1872intermediate results of a calculation as you go along. You can
1873accomplish this in Calc by performing your calculation as a series
1874of algebraic entries, using the @kbd{$} sign to tie them together.
1875In an algebraic formula, @kbd{$} represents the number on the top
1876of the stack. Here, we perform the calculation
1877@texline @math{\sqrt{2\times4+1}},
1878@infoline @expr{sqrt(2*4+1)},
1879which on a traditional calculator would be done by pressing
1880@kbd{2 * 4 + 1 =} and then the square-root key.
1881
1882@smallexample
1883@group
18841: 8 1: 9 1: 3
1885 . . .
1886
1887 ' 2*4 @key{RET} $+1 @key{RET} Q
1888@end group
1889@end smallexample
1890
1891@noindent
1892Notice that we didn't need to press an apostrophe for the @kbd{$+1},
1893because the dollar sign always begins an algebraic entry.
1894
1895(@bullet{}) @strong{Exercise 1.} How could you get the same effect as
1896pressing @kbd{Q} but using an algebraic entry instead? How about
1897if the @kbd{Q} key on your keyboard were broken?
1898@xref{Algebraic Answer 1, 1}. (@bullet{})
1899
1900The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack
1901entries. For example, @kbd{' $$+$ @key{RET}} is just like typing @kbd{+}.
1902
1903Algebraic formulas can include @dfn{variables}. To store in a
1904variable, press @kbd{s s}, then type the variable name, then press
1905@key{RET}. (There are actually two flavors of store command:
1906@kbd{s s} stores a number in a variable but also leaves the number
1907on the stack, while @w{@kbd{s t}} removes a number from the stack and
1908stores it in the variable.) A variable name should consist of one
1909or more letters or digits, beginning with a letter.
1910
1911@smallexample
1912@group
19131: 17 . 1: a + a^2 1: 306
1914 . . .
1915
1916 17 s t a @key{RET} ' a+a^2 @key{RET} =
1917@end group
1918@end smallexample
1919
1920@noindent
1921The @kbd{=} key @dfn{evaluates} a formula by replacing all its
1922variables by the values that were stored in them.
1923
1924For RPN calculations, you can recall a variable's value on the
1925stack either by entering its name as a formula and pressing @kbd{=},
1926or by using the @kbd{s r} command.
1927
1928@smallexample
1929@group
19301: 17 2: 17 3: 17 2: 17 1: 306
1931 . 1: 17 2: 17 1: 289 .
1932 . 1: 2 .
1933 .
1934
1935 s r a @key{RET} ' a @key{RET} = 2 ^ +
1936@end group
1937@end smallexample
1938
1939If you press a single digit for a variable name (as in @kbd{s t 3}, you
1940get one of ten @dfn{quick variables} @code{q0} through @code{q9}.
1941They are ``quick'' simply because you don't have to type the letter
1942@code{q} or the @key{RET} after their names. In fact, you can type
1943simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for
1944@kbd{t 3} and @w{@kbd{r 3}}.
1945
1946Any variables in an algebraic formula for which you have not stored
1947values are left alone, even when you evaluate the formula.
1948
1949@smallexample
1950@group
19511: 2 a + 2 b 1: 34 + 2 b
1952 . .
1953
1954 ' 2a+2b @key{RET} =
1955@end group
1956@end smallexample
1957
1958Calls to function names which are undefined in Calc are also left
1959alone, as are calls for which the value is undefined.
1960
1961@smallexample
1962@group
19631: 2 + log10(0) + log10(x) + log10(5, 6) + foo(3)
1964 .
1965
1966 ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) @key{RET}
1967@end group
1968@end smallexample
1969
1970@noindent
1971In this example, the first call to @code{log10} works, but the other
1972calls are not evaluated. In the second call, the logarithm is
1973undefined for that value of the argument; in the third, the argument
1974is symbolic, and in the fourth, there are too many arguments. In the
1975fifth case, there is no function called @code{foo}. You will see a
1976``Wrong number of arguments'' message referring to @samp{log10(5,6)}.
1977Press the @kbd{w} (``why'') key to see any other messages that may
1978have arisen from the last calculation. In this case you will get
1979``logarithm of zero,'' then ``number expected: @code{x}''. Calc
1980automatically displays the first message only if the message is
1981sufficiently important; for example, Calc considers ``wrong number
1982of arguments'' and ``logarithm of zero'' to be important enough to
1983report automatically, while a message like ``number expected: @code{x}''
1984will only show up if you explicitly press the @kbd{w} key.
1985
1986(@bullet{}) @strong{Exercise 2.} Joe entered the formula @samp{2 x y},
1987stored 5 in @code{x}, pressed @kbd{=}, and got the expected result,
1988@samp{10 y}. He then tried the same for the formula @samp{2 x (1+y)},
1989expecting @samp{10 (1+y)}, but it didn't work. Why not?
1990@xref{Algebraic Answer 2, 2}. (@bullet{})
1991
1992(@bullet{}) @strong{Exercise 3.} What result would you expect
1993@kbd{1 @key{RET} 0 /} to give? What if you then type @kbd{0 *}?
1994@xref{Algebraic Answer 3, 3}. (@bullet{})
1995
1996One interesting way to work with variables is to use the
1997@dfn{evaluates-to} (@samp{=>}) operator. It works like this:
1998Enter a formula algebraically in the usual way, but follow
1999the formula with an @samp{=>} symbol. (There is also an @kbd{s =}
2000command which builds an @samp{=>} formula using the stack.) On
2001the stack, you will see two copies of the formula with an @samp{=>}
2002between them. The lefthand formula is exactly like you typed it;
2003the righthand formula has been evaluated as if by typing @kbd{=}.
2004
2005@smallexample
2006@group
20072: 2 + 3 => 5 2: 2 + 3 => 5
20081: 2 a + 2 b => 34 + 2 b 1: 2 a + 2 b => 20 + 2 b
2009 . .
2010
2011' 2+3 => @key{RET} ' 2a+2b @key{RET} s = 10 s t a @key{RET}
2012@end group
2013@end smallexample
2014
2015@noindent
2016Notice that the instant we stored a new value in @code{a}, all
2017@samp{=>} operators already on the stack that referred to @expr{a}
2018were updated to use the new value. With @samp{=>}, you can push a
2019set of formulas on the stack, then change the variables experimentally
2020to see the effects on the formulas' values.
2021
2022You can also ``unstore'' a variable when you are through with it:
2023
2024@smallexample
2025@group
20262: 2 + 5 => 5
20271: 2 a + 2 b => 2 a + 2 b
2028 .
2029
2030 s u a @key{RET}
2031@end group
2032@end smallexample
2033
2034We will encounter formulas involving variables and functions again
2035when we discuss the algebra and calculus features of the Calculator.
2036
2037@node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial
2038@subsection Undo and Redo
2039
2040@noindent
2041If you make a mistake, you can usually correct it by pressing shift-@kbd{U},
2042the ``undo'' command. First, clear the stack (@kbd{M-0 @key{DEL}}) and exit
2043and restart Calc (@kbd{C-x * * C-x * *}) to make sure things start off
2044with a clean slate. Now:
2045
2046@smallexample
2047@group
20481: 2 2: 2 1: 8 2: 2 1: 6
2049 . 1: 3 . 1: 3 .
2050 . .
2051
2052 2 @key{RET} 3 ^ U *
2053@end group
2054@end smallexample
2055
2056You can undo any number of times. Calc keeps a complete record of
2057all you have done since you last opened the Calc window. After the
2058above example, you could type:
2059
2060@smallexample
2061@group
20621: 6 2: 2 1: 2 . .
2063 . 1: 3 .
2064 .
2065 (error)
2066 U U U U
2067@end group
2068@end smallexample
2069
2070You can also type @kbd{D} to ``redo'' a command that you have undone
2071mistakenly.
2072
2073@smallexample
2074@group
2075 . 1: 2 2: 2 1: 6 1: 6
2076 . 1: 3 . .
2077 .
2078 (error)
2079 D D D D
2080@end group
2081@end smallexample
2082
2083@noindent
2084It was not possible to redo past the @expr{6}, since that was placed there
2085by something other than an undo command.
2086
2087@cindex Time travel
2088You can think of undo and redo as a sort of ``time machine.'' Press
2089@kbd{U} to go backward in time, @kbd{D} to go forward. If you go
2090backward and do something (like @kbd{*}) then, as any science fiction
2091reader knows, you have changed your future and you cannot go forward
2092again. Thus, the inability to redo past the @expr{6} even though there
2093was an earlier undo command.
2094
2095You can always recall an earlier result using the Trail. We've ignored
2096the trail so far, but it has been faithfully recording everything we
2097did since we loaded the Calculator. If the Trail is not displayed,
2098press @kbd{t d} now to turn it on.
2099
2100Let's try grabbing an earlier result. The @expr{8} we computed was
2101undone by a @kbd{U} command, and was lost even to Redo when we pressed
2102@kbd{*}, but it's still there in the trail. There should be a little
2103@samp{>} arrow (the @dfn{trail pointer}) resting on the last trail
2104entry. If there isn't, press @kbd{t ]} to reset the trail pointer.
2105Now, press @w{@kbd{t p}} to move the arrow onto the line containing
2106@expr{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the
2107stack.
2108
2109If you press @kbd{t ]} again, you will see that even our Yank command
2110went into the trail.
2111
2112Let's go further back in time. Earlier in the tutorial we computed
2113a huge integer using the formula @samp{2^3^4}. We don't remember
2114what it was, but the first digits were ``241''. Press @kbd{t r}
2115(which stands for trail-search-reverse), then type @kbd{241}.
2116The trail cursor will jump back to the next previous occurrence of
2117the string ``241'' in the trail. This is just a regular Emacs
2118incremental search; you can now press @kbd{C-s} or @kbd{C-r} to
2119continue the search forwards or backwards as you like.
2120
2121To finish the search, press @key{RET}. This halts the incremental
2122search and leaves the trail pointer at the thing we found. Now we
2123can type @kbd{t y} to yank that number onto the stack. If we hadn't
2124remembered the ``241'', we could simply have searched for @kbd{2^3^4},
2125then pressed @kbd{@key{RET} t n} to halt and then move to the next item.
2126
2127You may have noticed that all the trail-related commands begin with
2128the letter @kbd{t}. (The store-and-recall commands, on the other hand,
2129all began with @kbd{s}.) Calc has so many commands that there aren't
2130enough keys for all of them, so various commands are grouped into
2131two-letter sequences where the first letter is called the @dfn{prefix}
2132key. If you type a prefix key by accident, you can press @kbd{C-g}
2133to cancel it. (In fact, you can press @kbd{C-g} to cancel almost
2134anything in Emacs.) To get help on a prefix key, press that key
2135followed by @kbd{?}. Some prefixes have several lines of help,
2136so you need to press @kbd{?} repeatedly to see them all.
2137You can also type @kbd{h h} to see all the help at once.
2138
2139Try pressing @kbd{t ?} now. You will see a line of the form,
2140
2141@smallexample
2142trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t-
2143@end smallexample
2144
2145@noindent
2146The word ``trail'' indicates that the @kbd{t} prefix key contains
2147trail-related commands. Each entry on the line shows one command,
2148with a single capital letter showing which letter you press to get
2149that command. We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and
2150@kbd{t y} so far. The @samp{[MORE]} means you can press @kbd{?}
2151again to see more @kbd{t}-prefix commands. Notice that the commands
2152are roughly divided (by semicolons) into related groups.
2153
2154When you are in the help display for a prefix key, the prefix is
2155still active. If you press another key, like @kbd{y} for example,
2156it will be interpreted as a @kbd{t y} command. If all you wanted
2157was to look at the help messages, press @kbd{C-g} afterwards to cancel
2158the prefix.
2159
2160One more way to correct an error is by editing the stack entries.
2161The actual Stack buffer is marked read-only and must not be edited
2162directly, but you can press @kbd{`} (the backquote or accent grave)
2163to edit a stack entry.
2164
2165Try entering @samp{3.141439} now. If this is supposed to represent
2166@cpi{}, it's got several errors. Press @kbd{`} to edit this number.
2167Now use the normal Emacs cursor motion and editing keys to change
2168the second 4 to a 5, and to transpose the 3 and the 9. When you
2169press @key{RET}, the number on the stack will be replaced by your
2170new number. This works for formulas, vectors, and all other types
2171of values you can put on the stack. The @kbd{`} key also works
2172during entry of a number or algebraic formula.
2173
2174@node Modes Tutorial, , Undo Tutorial, Basic Tutorial
2175@subsection Mode-Setting Commands
2176
2177@noindent
2178Calc has many types of @dfn{modes} that affect the way it interprets
2179your commands or the way it displays data. We have already seen one
2180mode, namely Algebraic mode. There are many others, too; we'll
2181try some of the most common ones here.
2182
2183Perhaps the most fundamental mode in Calc is the current @dfn{precision}.
2184Notice the @samp{12} on the Calc window's mode line:
2185
2186@smallexample
92e15881 2187--%*-Calc: 12 Deg (Calculator)----All------
4009494e
GM
2188@end smallexample
2189
2190@noindent
2191Most of the symbols there are Emacs things you don't need to worry
2192about, but the @samp{12} and the @samp{Deg} are mode indicators.
2193The @samp{12} means that calculations should always be carried to
219412 significant figures. That is why, when we type @kbd{1 @key{RET} 7 /},
2195we get @expr{0.142857142857} with exactly 12 digits, not counting
2196leading and trailing zeros.
2197
2198You can set the precision to anything you like by pressing @kbd{p},
2199then entering a suitable number. Try pressing @kbd{p 30 @key{RET}},
2200then doing @kbd{1 @key{RET} 7 /} again:
2201
2202@smallexample
2203@group
22041: 0.142857142857
22052: 0.142857142857142857142857142857
2206 .
2207@end group
2208@end smallexample
2209
2210Although the precision can be set arbitrarily high, Calc always
2211has to have @emph{some} value for the current precision. After
2212all, the true value @expr{1/7} is an infinitely repeating decimal;
2213Calc has to stop somewhere.
2214
2215Of course, calculations are slower the more digits you request.
2216Press @w{@kbd{p 12}} now to set the precision back down to the default.
2217
2218Calculations always use the current precision. For example, even
2219though we have a 30-digit value for @expr{1/7} on the stack, if
2220we use it in a calculation in 12-digit mode it will be rounded
2221down to 12 digits before it is used. Try it; press @key{RET} to
2222duplicate the number, then @w{@kbd{1 +}}. Notice that the @key{RET}
2223key didn't round the number, because it doesn't do any calculation.
2224But the instant we pressed @kbd{+}, the number was rounded down.
2225
2226@smallexample
2227@group
22281: 0.142857142857
22292: 0.142857142857142857142857142857
22303: 1.14285714286
2231 .
2232@end group
2233@end smallexample
2234
2235@noindent
2236In fact, since we added a digit on the left, we had to lose one
2237digit on the right from even the 12-digit value of @expr{1/7}.
2238
2239How did we get more than 12 digits when we computed @samp{2^3^4}? The
2240answer is that Calc makes a distinction between @dfn{integers} and
2241@dfn{floating-point} numbers, or @dfn{floats}. An integer is a number
2242that does not contain a decimal point. There is no such thing as an
2243``infinitely repeating fraction integer,'' so Calc doesn't have to limit
2244itself. If you asked for @samp{2^10000} (don't try this!), you would
2245have to wait a long time but you would eventually get an exact answer.
2246If you ask for @samp{2.^10000}, you will quickly get an answer which is
2247correct only to 12 places. The decimal point tells Calc that it should
2248use floating-point arithmetic to get the answer, not exact integer
2249arithmetic.
2250
2251You can use the @kbd{F} (@code{calc-floor}) command to convert a
2252floating-point value to an integer, and @kbd{c f} (@code{calc-float})
2253to convert an integer to floating-point form.
2254
2255Let's try entering that last calculation:
2256
2257@smallexample
2258@group
22591: 2. 2: 2. 1: 1.99506311689e3010
2260 . 1: 10000 .
2261 .
2262
2263 2.0 @key{RET} 10000 @key{RET} ^
2264@end group
2265@end smallexample
2266
2267@noindent
2268@cindex Scientific notation, entry of
2269Notice the letter @samp{e} in there. It represents ``times ten to the
2270power of,'' and is used by Calc automatically whenever writing the
2271number out fully would introduce more extra zeros than you probably
2272want to see. You can enter numbers in this notation, too.
2273
2274@smallexample
2275@group
22761: 2. 2: 2. 1: 1.99506311678e3010
2277 . 1: 10000. .
2278 .
2279
2280 2.0 @key{RET} 1e4 @key{RET} ^
2281@end group
2282@end smallexample
2283
2284@cindex Round-off errors
2285@noindent
2286Hey, the answer is different! Look closely at the middle columns
2287of the two examples. In the first, the stack contained the
2288exact integer @expr{10000}, but in the second it contained
2289a floating-point value with a decimal point. When you raise a
2290number to an integer power, Calc uses repeated squaring and
2291multiplication to get the answer. When you use a floating-point
2292power, Calc uses logarithms and exponentials. As you can see,
2293a slight error crept in during one of these methods. Which
2294one should we trust? Let's raise the precision a bit and find
2295out:
2296
2297@smallexample
2298@group
2299 . 1: 2. 2: 2. 1: 1.995063116880828e3010
2300 . 1: 10000. .
2301 .
2302
2303 p 16 @key{RET} 2. @key{RET} 1e4 ^ p 12 @key{RET}
2304@end group
2305@end smallexample
2306
2307@noindent
2308@cindex Guard digits
2309Presumably, it doesn't matter whether we do this higher-precision
2310calculation using an integer or floating-point power, since we
2311have added enough ``guard digits'' to trust the first 12 digits
2312no matter what. And the verdict is@dots{} Integer powers were more
2313accurate; in fact, the result was only off by one unit in the
2314last place.
2315
2316@cindex Guard digits
2317Calc does many of its internal calculations to a slightly higher
2318precision, but it doesn't always bump the precision up enough.
2319In each case, Calc added about two digits of precision during
2320its calculation and then rounded back down to 12 digits
2321afterward. In one case, it was enough; in the other, it
2322wasn't. If you really need @var{x} digits of precision, it
2323never hurts to do the calculation with a few extra guard digits.
2324
2325What if we want guard digits but don't want to look at them?
2326We can set the @dfn{float format}. Calc supports four major
2327formats for floating-point numbers, called @dfn{normal},
2328@dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering
2329notation}. You get them by pressing @w{@kbd{d n}}, @kbd{d f},
2330@kbd{d s}, and @kbd{d e}, respectively. In each case, you can
2331supply a numeric prefix argument which says how many digits
2332should be displayed. As an example, let's put a few numbers
2333onto the stack and try some different display modes. First,
2334use @kbd{M-0 @key{DEL}} to clear the stack, then enter the four
2335numbers shown here:
2336
2337@smallexample
2338@group
23394: 12345 4: 12345 4: 12345 4: 12345 4: 12345
23403: 12345. 3: 12300. 3: 1.2345e4 3: 1.23e4 3: 12345.000
23412: 123.45 2: 123. 2: 1.2345e2 2: 1.23e2 2: 123.450
23421: 12.345 1: 12.3 1: 1.2345e1 1: 1.23e1 1: 12.345
2343 . . . . .
2344
2345 d n M-3 d n d s M-3 d s M-3 d f
2346@end group
2347@end smallexample
2348
2349@noindent
2350Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down
2351to three significant digits, but then when we typed @kbd{d s} all
2352five significant figures reappeared. The float format does not
2353affect how numbers are stored, it only affects how they are
2354displayed. Only the current precision governs the actual rounding
2355of numbers in the Calculator's memory.
2356
2357Engineering notation, not shown here, is like scientific notation
2358except the exponent (the power-of-ten part) is always adjusted to be
2359a multiple of three (as in ``kilo,'' ``micro,'' etc.). As a result
2360there will be one, two, or three digits before the decimal point.
2361
2362Whenever you change a display-related mode, Calc redraws everything
2363in the stack. This may be slow if there are many things on the stack,
2364so Calc allows you to type shift-@kbd{H} before any mode command to
2365prevent it from updating the stack. Anything Calc displays after the
2366mode-changing command will appear in the new format.
2367
2368@smallexample
2369@group
23704: 12345 4: 12345 4: 12345 4: 12345 4: 12345
23713: 12345.000 3: 12345.000 3: 12345.000 3: 1.2345e4 3: 12345.
23722: 123.450 2: 123.450 2: 1.2345e1 2: 1.2345e1 2: 123.45
23731: 12.345 1: 1.2345e1 1: 1.2345e2 1: 1.2345e2 1: 12.345
2374 . . . . .
2375
2376 H d s @key{DEL} U @key{TAB} d @key{SPC} d n
2377@end group
2378@end smallexample
2379
2380@noindent
2381Here the @kbd{H d s} command changes to scientific notation but without
2382updating the screen. Deleting the top stack entry and undoing it back
2383causes it to show up in the new format; swapping the top two stack
2384entries reformats both entries. The @kbd{d @key{SPC}} command refreshes the
2385whole stack. The @kbd{d n} command changes back to the normal float
2386format; since it doesn't have an @kbd{H} prefix, it also updates all
2387the stack entries to be in @kbd{d n} format.
2388
2389Notice that the integer @expr{12345} was not affected by any
2390of the float formats. Integers are integers, and are always
2391displayed exactly.
2392
2393@cindex Large numbers, readability
2394Large integers have their own problems. Let's look back at
2395the result of @kbd{2^3^4}.
2396
2397@example
23982417851639229258349412352
2399@end example
2400
2401@noindent
2402Quick---how many digits does this have? Try typing @kbd{d g}:
2403
2404@example
24052,417,851,639,229,258,349,412,352
2406@end example
2407
2408@noindent
2409Now how many digits does this have? It's much easier to tell!
2410We can actually group digits into clumps of any size. Some
2411people prefer @kbd{M-5 d g}:
2412
2413@example
241424178,51639,22925,83494,12352
2415@end example
2416
2417Let's see what happens to floating-point numbers when they are grouped.
2418First, type @kbd{p 25 @key{RET}} to make sure we have enough precision
2419to get ourselves into trouble. Now, type @kbd{1e13 /}:
2420
2421@example
242224,17851,63922.9258349412352
2423@end example
2424
2425@noindent
2426The integer part is grouped but the fractional part isn't. Now try
2427@kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five):
2428
2429@example
243024,17851,63922.92583,49412,352
2431@end example
2432
2433If you find it hard to tell the decimal point from the commas, try
2434changing the grouping character to a space with @kbd{d , @key{SPC}}:
2435
2436@example
243724 17851 63922.92583 49412 352
2438@end example
2439
2440Type @kbd{d , ,} to restore the normal grouping character, then
2441@kbd{d g} again to turn grouping off. Also, press @kbd{p 12} to
2442restore the default precision.
2443
2444Press @kbd{U} enough times to get the original big integer back.
2445(Notice that @kbd{U} does not undo each mode-setting command; if
2446you want to undo a mode-setting command, you have to do it yourself.)
2447Now, type @kbd{d r 16 @key{RET}}:
2448
2449@example
245016#200000000000000000000
2451@end example
2452
2453@noindent
2454The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form.
2455Suddenly it looks pretty simple; this should be no surprise, since we
2456got this number by computing a power of two, and 16 is a power of 2.
2457In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary
2458form:
2459
2460@example
24612#1000000000000000000000000000000000000000000000000000000 @dots{}
2462@end example
2463
2464@noindent
2465We don't have enough space here to show all the zeros! They won't
2466fit on a typical screen, either, so you will have to use horizontal
2467scrolling to see them all. Press @kbd{<} and @kbd{>} to scroll the
2468stack window left and right by half its width. Another way to view
2469something large is to press @kbd{`} (back-quote) to edit the top of
2470stack in a separate window. (Press @kbd{C-c C-c} when you are done.)
2471
2472You can enter non-decimal numbers using the @kbd{#} symbol, too.
2473Let's see what the hexadecimal number @samp{5FE} looks like in
2474binary. Type @kbd{16#5FE} (the letters can be typed in upper or
2475lower case; they will always appear in upper case). It will also
2476help to turn grouping on with @kbd{d g}:
2477
2478@example
24792#101,1111,1110
2480@end example
2481
2482Notice that @kbd{d g} groups by fours by default if the display radix
2483is binary or hexadecimal, but by threes if it is decimal, octal, or any
2484other radix.
2485
2486Now let's see that number in decimal; type @kbd{d r 10}:
2487
2488@example
24891,534
2490@end example
2491
2492Numbers are not @emph{stored} with any particular radix attached. They're
2493just numbers; they can be entered in any radix, and are always displayed
2494in whatever radix you've chosen with @kbd{d r}. The current radix applies
2495to integers, fractions, and floats.
2496
2497@cindex Roundoff errors, in non-decimal numbers
2498(@bullet{}) @strong{Exercise 1.} Your friend Joe tried to enter one-third
2499as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12. He got
2500@samp{3#0.0222222...} (with 25 2's) in the display. When he multiplied
2501that by three, he got @samp{3#0.222222...} instead of the expected
2502@samp{3#1}. Next, Joe entered @samp{3#0.2} and, to his great relief,
2503saw @samp{3#0.2} on the screen. But when he typed @kbd{2 /}, he got
2504@samp{3#0.10000001} (some zeros omitted). What's going on here?
2505@xref{Modes Answer 1, 1}. (@bullet{})
2506
2507@cindex Scientific notation, in non-decimal numbers
2508(@bullet{}) @strong{Exercise 2.} Scientific notation works in non-decimal
2509modes in the natural way (the exponent is a power of the radix instead of
2510a power of ten, although the exponent itself is always written in decimal).
2511Thus @samp{8#1.23e3 = 8#1230.0}. Suppose we have the hexadecimal number
2512@samp{f.e8f} times 16 to the 15th power: We write @samp{16#f.e8fe15}.
2513What is wrong with this picture? What could we write instead that would
2514work better? @xref{Modes Answer 2, 2}. (@bullet{})
2515
2516The @kbd{m} prefix key has another set of modes, relating to the way
2517Calc interprets your inputs and does computations. Whereas @kbd{d}-prefix
2518modes generally affect the way things look, @kbd{m}-prefix modes affect
2519the way they are actually computed.
2520
2521The most popular @kbd{m}-prefix mode is the @dfn{angular mode}. Notice
2522the @samp{Deg} indicator in the mode line. This means that if you use
2523a command that interprets a number as an angle, it will assume the
2524angle is measured in degrees. For example,
2525
2526@smallexample
2527@group
25281: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5
2529 . . . .
2530
2531 45 S 2 ^ c 1
2532@end group
2533@end smallexample
2534
2535@noindent
2536The shift-@kbd{S} command computes the sine of an angle. The sine
2537of 45 degrees is
2538@texline @math{\sqrt{2}/2};
2539@infoline @expr{sqrt(2)/2};
2540squaring this yields @expr{2/4 = 0.5}. However, there has been a slight
2541roundoff error because the representation of
2542@texline @math{\sqrt{2}/2}
2543@infoline @expr{sqrt(2)/2}
2544wasn't exact. The @kbd{c 1} command is a handy way to clean up numbers
2545in this case; it temporarily reduces the precision by one digit while it
2546re-rounds the number on the top of the stack.
2547
2548@cindex Roundoff errors, examples
2549(@bullet{}) @strong{Exercise 3.} Your friend Joe computed the sine
2550of 45 degrees as shown above, then, hoping to avoid an inexact
2551result, he increased the precision to 16 digits before squaring.
2552What happened? @xref{Modes Answer 3, 3}. (@bullet{})
2553
2554To do this calculation in radians, we would type @kbd{m r} first.
2555(The indicator changes to @samp{Rad}.) 45 degrees corresponds to
2556@cpiover{4} radians. To get @cpi{}, press the @kbd{P} key. (Once
2557again, this is a shifted capital @kbd{P}. Remember, unshifted
2558@kbd{p} sets the precision.)
2559
2560@smallexample
2561@group
25621: 3.14159265359 1: 0.785398163398 1: 0.707106781187
2563 . . .
2564
2565 P 4 / m r S
2566@end group
2567@end smallexample
2568
2569Likewise, inverse trigonometric functions generate results in
2570either radians or degrees, depending on the current angular mode.
2571
2572@smallexample
2573@group
25741: 0.707106781187 1: 0.785398163398 1: 45.
2575 . . .
2576
2577 .5 Q m r I S m d U I S
2578@end group
2579@end smallexample
2580
2581@noindent
2582Here we compute the Inverse Sine of
2583@texline @math{\sqrt{0.5}},
2584@infoline @expr{sqrt(0.5)},
2585first in radians, then in degrees.
2586
2587Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees
2588and vice-versa.
2589
2590@smallexample
2591@group
25921: 45 1: 0.785398163397 1: 45.
2593 . . .
2594
2595 45 c r c d
2596@end group
2597@end smallexample
2598
2599Another interesting mode is @dfn{Fraction mode}. Normally,
2600dividing two integers produces a floating-point result if the
2601quotient can't be expressed as an exact integer. Fraction mode
2602causes integer division to produce a fraction, i.e., a rational
2603number, instead.
2604
2605@smallexample
2606@group
26072: 12 1: 1.33333333333 1: 4:3
26081: 9 . .
2609 .
2610
2611 12 @key{RET} 9 / m f U / m f
2612@end group
2613@end smallexample
2614
2615@noindent
2616In the first case, we get an approximate floating-point result.
2617In the second case, we get an exact fractional result (four-thirds).
2618
2619You can enter a fraction at any time using @kbd{:} notation.
2620(Calc uses @kbd{:} instead of @kbd{/} as the fraction separator
2621because @kbd{/} is already used to divide the top two stack
2622elements.) Calculations involving fractions will always
2623produce exact fractional results; Fraction mode only says
2624what to do when dividing two integers.
2625
2626@cindex Fractions vs. floats
2627@cindex Floats vs. fractions
2628(@bullet{}) @strong{Exercise 4.} If fractional arithmetic is exact,
2629why would you ever use floating-point numbers instead?
2630@xref{Modes Answer 4, 4}. (@bullet{})
2631
2632Typing @kbd{m f} doesn't change any existing values in the stack.
2633In the above example, we had to Undo the division and do it over
2634again when we changed to Fraction mode. But if you use the
2635evaluates-to operator you can get commands like @kbd{m f} to
2636recompute for you.
2637
2638@smallexample
2639@group
26401: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3
2641 . . .
2642
2643 ' 12/9 => @key{RET} p 4 @key{RET} m f
2644@end group
2645@end smallexample
2646
2647@noindent
2648In this example, the righthand side of the @samp{=>} operator
2649on the stack is recomputed when we change the precision, then
2650again when we change to Fraction mode. All @samp{=>} expressions
2651on the stack are recomputed every time you change any mode that
2652might affect their values.
2653
2654@node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial
2655@section Arithmetic Tutorial
2656
2657@noindent
2658In this section, we explore the arithmetic and scientific functions
2659available in the Calculator.
2660
2661The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/},
2662and @kbd{^}. Each normally takes two numbers from the top of the stack
2663and pushes back a result. The @kbd{n} and @kbd{&} keys perform
2664change-sign and reciprocal operations, respectively.
2665
2666@smallexample
2667@group
26681: 5 1: 0.2 1: 5. 1: -5. 1: 5.
2669 . . . . .
2670
2671 5 & & n n
2672@end group
2673@end smallexample
2674
2675@cindex Binary operators
2676You can apply a ``binary operator'' like @kbd{+} across any number of
2677stack entries by giving it a numeric prefix. You can also apply it
2678pairwise to several stack elements along with the top one if you use
2679a negative prefix.
2680
2681@smallexample
2682@group
26833: 2 1: 9 3: 2 4: 2 3: 12
26842: 3 . 2: 3 3: 3 2: 13
26851: 4 1: 4 2: 4 1: 14
2686 . . 1: 10 .
2687 .
2688
26892 @key{RET} 3 @key{RET} 4 M-3 + U 10 M-- M-3 +
2690@end group
2691@end smallexample
2692
2693@cindex Unary operators
2694You can apply a ``unary operator'' like @kbd{&} to the top @var{n}
2695stack entries with a numeric prefix, too.
2696
2697@smallexample
2698@group
26993: 2 3: 0.5 3: 0.5
27002: 3 2: 0.333333333333 2: 3.
27011: 4 1: 0.25 1: 4.
2702 . . .
2703
27042 @key{RET} 3 @key{RET} 4 M-3 & M-2 &
2705@end group
2706@end smallexample
2707
2708Notice that the results here are left in floating-point form.
2709We can convert them back to integers by pressing @kbd{F}, the
2710``floor'' function. This function rounds down to the next lower
2711integer. There is also @kbd{R}, which rounds to the nearest
2712integer.
2713
2714@smallexample
2715@group
27167: 2. 7: 2 7: 2
27176: 2.4 6: 2 6: 2
27185: 2.5 5: 2 5: 3
27194: 2.6 4: 2 4: 3
27203: -2. 3: -2 3: -2
27212: -2.4 2: -3 2: -2
27221: -2.6 1: -3 1: -3
2723 . . .
2724
2725 M-7 F U M-7 R
2726@end group
2727@end smallexample
2728
2729Since dividing-and-flooring (i.e., ``integer quotient'') is such a
2730common operation, Calc provides a special command for that purpose, the
2731backslash @kbd{\}. Another common arithmetic operator is @kbd{%}, which
2732computes the remainder that would arise from a @kbd{\} operation, i.e.,
2733the ``modulo'' of two numbers. For example,
2734
2735@smallexample
2736@group
27372: 1234 1: 12 2: 1234 1: 34
27381: 100 . 1: 100 .
2739 . .
2740
27411234 @key{RET} 100 \ U %
2742@end group
2743@end smallexample
2744
2745These commands actually work for any real numbers, not just integers.
2746
2747@smallexample
2748@group
27492: 3.1415 1: 3 2: 3.1415 1: 0.1415
27501: 1 . 1: 1 .
2751 . .
2752
27533.1415 @key{RET} 1 \ U %
2754@end group
2755@end smallexample
2756
2757(@bullet{}) @strong{Exercise 1.} The @kbd{\} command would appear to be a
2758frill, since you could always do the same thing with @kbd{/ F}. Think
2759of a situation where this is not true---@kbd{/ F} would be inadequate.
2760Now think of a way you could get around the problem if Calc didn't
2761provide a @kbd{\} command. @xref{Arithmetic Answer 1, 1}. (@bullet{})
2762
2763We've already seen the @kbd{Q} (square root) and @kbd{S} (sine)
2764commands. Other commands along those lines are @kbd{C} (cosine),
2765@kbd{T} (tangent), @kbd{E} (@expr{e^x}) and @kbd{L} (natural
2766logarithm). These can be modified by the @kbd{I} (inverse) and
2767@kbd{H} (hyperbolic) prefix keys.
2768
2769Let's compute the sine and cosine of an angle, and verify the
2770identity
2771@texline @math{\sin^2x + \cos^2x = 1}.
2772@infoline @expr{sin(x)^2 + cos(x)^2 = 1}.
2773We'll arbitrarily pick @mathit{-64} degrees as a good value for @expr{x}.
2774With the angular mode set to degrees (type @w{@kbd{m d}}), do:
2775
2776@smallexample
2777@group
27782: -64 2: -64 2: -0.89879 2: -0.89879 1: 1.
27791: -64 1: -0.89879 1: -64 1: 0.43837 .
2780 . . . .
2781
2782 64 n @key{RET} @key{RET} S @key{TAB} C f h
2783@end group
2784@end smallexample
2785
2786@noindent
2787(For brevity, we're showing only five digits of the results here.
2788You can of course do these calculations to any precision you like.)
2789
2790Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum
2791of squares, command.
2792
2793Another identity is
2794@texline @math{\displaystyle\tan x = {\sin x \over \cos x}}.
2795@infoline @expr{tan(x) = sin(x) / cos(x)}.
2796@smallexample
2797@group
2798
27992: -0.89879 1: -2.0503 1: -64.
28001: 0.43837 . .
2801 .
2802
2803 U / I T
2804@end group
2805@end smallexample
2806
2807A physical interpretation of this calculation is that if you move
2808@expr{0.89879} units downward and @expr{0.43837} units to the right,
2809your direction of motion is @mathit{-64} degrees from horizontal. Suppose
2810we move in the opposite direction, up and to the left:
2811
2812@smallexample
2813@group
28142: -0.89879 2: 0.89879 1: -2.0503 1: -64.
28151: 0.43837 1: -0.43837 . .
2816 . .
2817
2818 U U M-2 n / I T
2819@end group
2820@end smallexample
2821
2822@noindent
2823How can the angle be the same? The answer is that the @kbd{/} operation
2824loses information about the signs of its inputs. Because the quotient
2825is negative, we know exactly one of the inputs was negative, but we
2826can't tell which one. There is an @kbd{f T} [@code{arctan2}] function which
2827computes the inverse tangent of the quotient of a pair of numbers.
2828Since you feed it the two original numbers, it has enough information
2829to give you a full 360-degree answer.
2830
2831@smallexample
2832@group
28332: 0.89879 1: 116. 3: 116. 2: 116. 1: 180.
28341: -0.43837 . 2: -0.89879 1: -64. .
2835 . 1: 0.43837 .
2836 .
2837
2838 U U f T M-@key{RET} M-2 n f T -
2839@end group
2840@end smallexample
2841
2842@noindent
2843The resulting angles differ by 180 degrees; in other words, they
2844point in opposite directions, just as we would expect.
2845
2846The @key{META}-@key{RET} we used in the third step is the
2847``last-arguments'' command. It is sort of like Undo, except that it
2848restores the arguments of the last command to the stack without removing
2849the command's result. It is useful in situations like this one,
2850where we need to do several operations on the same inputs. We could
2851have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate
2852the top two stack elements right after the @kbd{U U}, then a pair of
2853@kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates.
2854
2855A similar identity is supposed to hold for hyperbolic sines and cosines,
2856except that it is the @emph{difference}
2857@texline @math{\cosh^2x - \sinh^2x}
2858@infoline @expr{cosh(x)^2 - sinh(x)^2}
2859that always equals one. Let's try to verify this identity.
2860
2861@smallexample
2862@group
28632: -64 2: -64 2: -64 2: 9.7192e54 2: 9.7192e54
28641: -64 1: -3.1175e27 1: 9.7192e54 1: -64 1: 9.7192e54
2865 . . . . .
2866
2867 64 n @key{RET} @key{RET} H C 2 ^ @key{TAB} H S 2 ^
2868@end group
2869@end smallexample
2870
2871@noindent
2872@cindex Roundoff errors, examples
2873Something's obviously wrong, because when we subtract these numbers
2874the answer will clearly be zero! But if you think about it, if these
2875numbers @emph{did} differ by one, it would be in the 55th decimal
2876place. The difference we seek has been lost entirely to roundoff
2877error.
2878
2879We could verify this hypothesis by doing the actual calculation with,
2880say, 60 decimal places of precision. This will be slow, but not
2881enormously so. Try it if you wish; sure enough, the answer is
28820.99999, reasonably close to 1.
2883
2884Of course, a more reasonable way to verify the identity is to use
2885a more reasonable value for @expr{x}!
2886
2887@cindex Common logarithm
2888Some Calculator commands use the Hyperbolic prefix for other purposes.
2889The logarithm and exponential functions, for example, work to the base
2890@expr{e} normally but use base-10 instead if you use the Hyperbolic
2891prefix.
2892
2893@smallexample
2894@group
28951: 1000 1: 6.9077 1: 1000 1: 3
2896 . . . .
2897
2898 1000 L U H L
2899@end group
2900@end smallexample
2901
2902@noindent
2903First, we mistakenly compute a natural logarithm. Then we undo
2904and compute a common logarithm instead.
2905
2906The @kbd{B} key computes a general base-@var{b} logarithm for any
2907value of @var{b}.
2908
2909@smallexample
2910@group
29112: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077
29121: 10 . . 1: 2.71828 .
2913 . .
2914
2915 1000 @key{RET} 10 B H E H P B
2916@end group
2917@end smallexample
2918
2919@noindent
2920Here we first use @kbd{B} to compute the base-10 logarithm, then use
2921the ``hyperbolic'' exponential as a cheap hack to recover the number
29221000, then use @kbd{B} again to compute the natural logarithm. Note
2923that @kbd{P} with the hyperbolic prefix pushes the constant @expr{e}
2924onto the stack.
2925
2926You may have noticed that both times we took the base-10 logarithm
2927of 1000, we got an exact integer result. Calc always tries to give
2928an exact rational result for calculations involving rational numbers
2929where possible. But when we used @kbd{H E}, the result was a
2930floating-point number for no apparent reason. In fact, if we had
2931computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an
2932exact integer 1000. But the @kbd{H E} command is rigged to generate
2933a floating-point result all of the time so that @kbd{1000 H E} will
2934not waste time computing a thousand-digit integer when all you
2935probably wanted was @samp{1e1000}.
2936
2937(@bullet{}) @strong{Exercise 2.} Find a pair of integer inputs to
2938the @kbd{B} command for which Calc could find an exact rational
2939result but doesn't. @xref{Arithmetic Answer 2, 2}. (@bullet{})
2940
2941The Calculator also has a set of functions relating to combinatorics
2942and statistics. You may be familiar with the @dfn{factorial} function,
2943which computes the product of all the integers up to a given number.
2944
2945@smallexample
2946@group
29471: 100 1: 93326215443... 1: 100. 1: 9.3326e157
2948 . . . .
2949
2950 100 ! U c f !
2951@end group
2952@end smallexample
2953
2954@noindent
2955Recall, the @kbd{c f} command converts the integer or fraction at the
2956top of the stack to floating-point format. If you take the factorial
2957of a floating-point number, you get a floating-point result
2958accurate to the current precision. But if you give @kbd{!} an
2959exact integer, you get an exact integer result (158 digits long
2960in this case).
2961
2962If you take the factorial of a non-integer, Calc uses a generalized
2963factorial function defined in terms of Euler's Gamma function
2964@texline @math{\Gamma(n)}
2965@infoline @expr{gamma(n)}
2966(which is itself available as the @kbd{f g} command).
2967
2968@smallexample
2969@group
29703: 4. 3: 24. 1: 5.5 1: 52.342777847
29712: 4.5 2: 52.3427777847 . .
29721: 5. 1: 120.
2973 . .
2974
2975 M-3 ! M-0 @key{DEL} 5.5 f g
2976@end group
2977@end smallexample
2978
2979@noindent
2980Here we verify the identity
2981@texline @math{n! = \Gamma(n+1)}.
2982@infoline @expr{@var{n}!@: = gamma(@var{n}+1)}.
2983
2984The binomial coefficient @var{n}-choose-@var{m}
2985@texline or @math{\displaystyle {n \choose m}}
2986is defined by
2987@texline @math{\displaystyle {n! \over m! \, (n-m)!}}
2988@infoline @expr{n!@: / m!@: (n-m)!}
2989for all reals @expr{n} and @expr{m}. The intermediate results in this
2990formula can become quite large even if the final result is small; the
2991@kbd{k c} command computes a binomial coefficient in a way that avoids
2992large intermediate values.
2993
2994The @kbd{k} prefix key defines several common functions out of
2995combinatorics and number theory. Here we compute the binomial
2996coefficient 30-choose-20, then determine its prime factorization.
2997
2998@smallexample
2999@group
30002: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29]
30011: 20 . .
3002 .
3003
3004 30 @key{RET} 20 k c k f
3005@end group
3006@end smallexample
3007
3008@noindent
a8b14149
JB
3009You can verify these prime factors by using @kbd{V R *} to multiply
3010together the elements of this vector. The result is the original
3011number, 30045015.
4009494e
GM
3012
3013@cindex Hash tables
3014Suppose a program you are writing needs a hash table with at least
301510000 entries. It's best to use a prime number as the actual size
3016of a hash table. Calc can compute the next prime number after 10000:
3017
3018@smallexample
3019@group
30201: 10000 1: 10007 1: 9973
3021 . . .
3022
3023 10000 k n I k n
3024@end group
3025@end smallexample
3026
3027@noindent
3028Just for kicks we've also computed the next prime @emph{less} than
302910000.
3030
3031@c [fix-ref Financial Functions]
3032@xref{Financial Functions}, for a description of the Calculator
3033commands that deal with business and financial calculations (functions
3034like @code{pv}, @code{rate}, and @code{sln}).
3035
3036@c [fix-ref Binary Number Functions]
3037@xref{Binary Functions}, to read about the commands for operating
3038on binary numbers (like @code{and}, @code{xor}, and @code{lsh}).
3039
3040@node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
3041@section Vector/Matrix Tutorial
3042
3043@noindent
3044A @dfn{vector} is a list of numbers or other Calc data objects.
3045Calc provides a large set of commands that operate on vectors. Some
3046are familiar operations from vector analysis. Others simply treat
3047a vector as a list of objects.
3048
3049@menu
3050* Vector Analysis Tutorial::
3051* Matrix Tutorial::
3052* List Tutorial::
3053@end menu
3054
3055@node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
3056@subsection Vector Analysis
3057
3058@noindent
3059If you add two vectors, the result is a vector of the sums of the
3060elements, taken pairwise.
3061
3062@smallexample
3063@group
30641: [1, 2, 3] 2: [1, 2, 3] 1: [8, 8, 3]
3065 . 1: [7, 6, 0] .
3066 .
3067
3068 [1,2,3] s 1 [7 6 0] s 2 +
3069@end group
3070@end smallexample
3071
3072@noindent
3073Note that we can separate the vector elements with either commas or
3074spaces. This is true whether we are using incomplete vectors or
3075algebraic entry. The @kbd{s 1} and @kbd{s 2} commands save these
3076vectors so we can easily reuse them later.
3077
3078If you multiply two vectors, the result is the sum of the products
3079of the elements taken pairwise. This is called the @dfn{dot product}
3080of the vectors.
3081
3082@smallexample
3083@group
30842: [1, 2, 3] 1: 19
30851: [7, 6, 0] .
3086 .
3087
3088 r 1 r 2 *
3089@end group
3090@end smallexample
3091
3092@cindex Dot product
3093The dot product of two vectors is equal to the product of their
3094lengths times the cosine of the angle between them. (Here the vector
3095is interpreted as a line from the origin @expr{(0,0,0)} to the
3096specified point in three-dimensional space.) The @kbd{A}
3097(absolute value) command can be used to compute the length of a
3098vector.
3099
3100@smallexample
3101@group
31023: 19 3: 19 1: 0.550782 1: 56.579
31032: [1, 2, 3] 2: 3.741657 . .
31041: [7, 6, 0] 1: 9.219544
3105 . .
3106
3107 M-@key{RET} M-2 A * / I C
3108@end group
3109@end smallexample
3110
3111@noindent
3112First we recall the arguments to the dot product command, then
3113we compute the absolute values of the top two stack entries to
3114obtain the lengths of the vectors, then we divide the dot product
3115by the product of the lengths to get the cosine of the angle.
3116The inverse cosine finds that the angle between the vectors
3117is about 56 degrees.
3118
3119@cindex Cross product
3120@cindex Perpendicular vectors
3121The @dfn{cross product} of two vectors is a vector whose length
3122is the product of the lengths of the inputs times the sine of the
3123angle between them, and whose direction is perpendicular to both
3124input vectors. Unlike the dot product, the cross product is
3125defined only for three-dimensional vectors. Let's double-check
3126our computation of the angle using the cross product.
3127
3128@smallexample
3129@group
31302: [1, 2, 3] 3: [-18, 21, -8] 1: [-0.52, 0.61, -0.23] 1: 56.579
31311: [7, 6, 0] 2: [1, 2, 3] . .
3132 . 1: [7, 6, 0]
3133 .
3134
3135 r 1 r 2 V C s 3 M-@key{RET} M-2 A * / A I S
3136@end group
3137@end smallexample
3138
3139@noindent
3140First we recall the original vectors and compute their cross product,
3141which we also store for later reference. Now we divide the vector
3142by the product of the lengths of the original vectors. The length of
3143this vector should be the sine of the angle; sure enough, it is!
3144
3145@c [fix-ref General Mode Commands]
3146Vector-related commands generally begin with the @kbd{v} prefix key.
3147Some are uppercase letters and some are lowercase. To make it easier
3148to type these commands, the shift-@kbd{V} prefix key acts the same as
3149the @kbd{v} key. (@xref{General Mode Commands}, for a way to make all
3150prefix keys have this property.)
3151
3152If we take the dot product of two perpendicular vectors we expect
3153to get zero, since the cosine of 90 degrees is zero. Let's check
3154that the cross product is indeed perpendicular to both inputs:
3155
3156@smallexample
3157@group
31582: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0
31591: [-18, 21, -8] . 1: [-18, 21, -8] .
3160 . .
3161
3162 r 1 r 3 * @key{DEL} r 2 r 3 *
3163@end group
3164@end smallexample
3165
3166@cindex Normalizing a vector
3167@cindex Unit vectors
3168(@bullet{}) @strong{Exercise 1.} Given a vector on the top of the
3169stack, what keystrokes would you use to @dfn{normalize} the
3170vector, i.e., to reduce its length to one without changing its
3171direction? @xref{Vector Answer 1, 1}. (@bullet{})
3172
3173(@bullet{}) @strong{Exercise 2.} Suppose a certain particle can be
3174at any of several positions along a ruler. You have a list of
3175those positions in the form of a vector, and another list of the
3176probabilities for the particle to be at the corresponding positions.
3177Find the average position of the particle.
3178@xref{Vector Answer 2, 2}. (@bullet{})
3179
3180@node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
3181@subsection Matrices
3182
3183@noindent
3184A @dfn{matrix} is just a vector of vectors, all the same length.
3185This means you can enter a matrix using nested brackets. You can
3186also use the semicolon character to enter a matrix. We'll show
3187both methods here:
3188
3189@smallexample
3190@group
31911: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3192 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3193 . .
3194
3195 [[1 2 3] [4 5 6]] ' [1 2 3; 4 5 6] @key{RET}
3196@end group
3197@end smallexample
3198
3199@noindent
3200We'll be using this matrix again, so type @kbd{s 4} to save it now.
3201
3202Note that semicolons work with incomplete vectors, but they work
3203better in algebraic entry. That's why we use the apostrophe in
3204the second example.
3205
3206When two matrices are multiplied, the lefthand matrix must have
3207the same number of columns as the righthand matrix has rows.
3208Row @expr{i}, column @expr{j} of the result is effectively the
3209dot product of row @expr{i} of the left matrix by column @expr{j}
3210of the right matrix.
3211
3212If we try to duplicate this matrix and multiply it by itself,
3213the dimensions are wrong and the multiplication cannot take place:
3214
3215@smallexample
3216@group
32171: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ]
3218 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3219 .
3220
3221 @key{RET} *
3222@end group
3223@end smallexample
3224
3225@noindent
3226Though rather hard to read, this is a formula which shows the product
3227of two matrices. The @samp{*} function, having invalid arguments, has
3228been left in symbolic form.
3229
3230We can multiply the matrices if we @dfn{transpose} one of them first.
3231
3232@smallexample
3233@group
32342: [ [ 1, 2, 3 ] 1: [ [ 14, 32 ] 1: [ [ 17, 22, 27 ]
3235 [ 4, 5, 6 ] ] [ 32, 77 ] ] [ 22, 29, 36 ]
32361: [ [ 1, 4 ] . [ 27, 36, 45 ] ]
3237 [ 2, 5 ] .
3238 [ 3, 6 ] ]
3239 .
3240
3241 U v t * U @key{TAB} *
3242@end group
3243@end smallexample
3244
3245Matrix multiplication is not commutative; indeed, switching the
3246order of the operands can even change the dimensions of the result
3247matrix, as happened here!
3248
3249If you multiply a plain vector by a matrix, it is treated as a
3250single row or column depending on which side of the matrix it is
3251on. The result is a plain vector which should also be interpreted
3252as a row or column as appropriate.
3253
3254@smallexample
3255@group
32562: [ [ 1, 2, 3 ] 1: [14, 32]
3257 [ 4, 5, 6 ] ] .
32581: [1, 2, 3]
3259 .
3260
3261 r 4 r 1 *
3262@end group
3263@end smallexample
3264
3265Multiplying in the other order wouldn't work because the number of
3266rows in the matrix is different from the number of elements in the
3267vector.
3268
3269(@bullet{}) @strong{Exercise 1.} Use @samp{*} to sum along the rows
3270of the above
3271@texline @math{2\times3}
3272@infoline 2x3
3273matrix to get @expr{[6, 15]}. Now use @samp{*} to sum along the columns
3274to get @expr{[5, 7, 9]}.
3275@xref{Matrix Answer 1, 1}. (@bullet{})
3276
3277@cindex Identity matrix
3278An @dfn{identity matrix} is a square matrix with ones along the
3279diagonal and zeros elsewhere. It has the property that multiplication
3280by an identity matrix, on the left or on the right, always produces
3281the original matrix.
3282
3283@smallexample
3284@group
32851: [ [ 1, 2, 3 ] 2: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3286 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3287 . 1: [ [ 1, 0, 0 ] .
3288 [ 0, 1, 0 ]
3289 [ 0, 0, 1 ] ]
3290 .
3291
3292 r 4 v i 3 @key{RET} *
3293@end group
3294@end smallexample
3295
3296If a matrix is square, it is often possible to find its @dfn{inverse},
3297that is, a matrix which, when multiplied by the original matrix, yields
3298an identity matrix. The @kbd{&} (reciprocal) key also computes the
3299inverse of a matrix.
3300
3301@smallexample
3302@group
33031: [ [ 1, 2, 3 ] 1: [ [ -2.4, 1.2, -0.2 ]
3304 [ 4, 5, 6 ] [ 2.8, -1.4, 0.4 ]
3305 [ 7, 6, 0 ] ] [ -0.73333, 0.53333, -0.2 ] ]
3306 . .
3307
3308 r 4 r 2 | s 5 &
3309@end group
3310@end smallexample
3311
3312@noindent
3313The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
3314matrices together. Here we have used it to add a new row onto
3315our matrix to make it square.
3316
3317We can multiply these two matrices in either order to get an identity.
3318
3319@smallexample
3320@group
33211: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ]
3322 [ 0., 1., 0. ] [ 0., 1., 0. ]
3323 [ 0., 0., 1. ] ] [ 0., 0., 1. ] ]
3324 . .
3325
3326 M-@key{RET} * U @key{TAB} *
3327@end group
3328@end smallexample
3329
3330@cindex Systems of linear equations
3331@cindex Linear equations, systems of
3332Matrix inverses are related to systems of linear equations in algebra.
3333Suppose we had the following set of equations:
3334
3335@ifnottex
3336@group
3337@example
3338 a + 2b + 3c = 6
3339 4a + 5b + 6c = 2
3340 7a + 6b = 3
3341@end example
3342@end group
3343@end ifnottex
3344@tex
3345\turnoffactive
3346\beforedisplayh
3347$$ \openup1\jot \tabskip=0pt plus1fil
3348\halign to\displaywidth{\tabskip=0pt
3349 $\hfil#$&$\hfil{}#{}$&
3350 $\hfil#$&$\hfil{}#{}$&
3351 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3352 a&+&2b&+&3c&=6 \cr
3353 4a&+&5b&+&6c&=2 \cr
3354 7a&+&6b& & &=3 \cr}
3355$$
3356\afterdisplayh
3357@end tex
3358
3359@noindent
3360This can be cast into the matrix equation,
3361
3362@ifnottex
3363@group
3364@example
3365 [ [ 1, 2, 3 ] [ [ a ] [ [ 6 ]
3366 [ 4, 5, 6 ] * [ b ] = [ 2 ]
3367 [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ]
3368@end example
3369@end group
3370@end ifnottex
3371@tex
3372\turnoffactive
3373\beforedisplay
3374$$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 }
3375 \times
3376 \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 }
3377$$
3378\afterdisplay
3379@end tex
3380
3381We can solve this system of equations by multiplying both sides by the
3382inverse of the matrix. Calc can do this all in one step:
3383
3384@smallexample
3385@group
33862: [6, 2, 3] 1: [-12.6, 15.2, -3.93333]
33871: [ [ 1, 2, 3 ] .
3388 [ 4, 5, 6 ]
3389 [ 7, 6, 0 ] ]
3390 .
3391
3392 [6,2,3] r 5 /
3393@end group
3394@end smallexample
3395
3396@noindent
3397The result is the @expr{[a, b, c]} vector that solves the equations.
3398(Dividing by a square matrix is equivalent to multiplying by its
3399inverse.)
3400
3401Let's verify this solution:
3402
3403@smallexample
3404@group
34052: [ [ 1, 2, 3 ] 1: [6., 2., 3.]
3406 [ 4, 5, 6 ] .
3407 [ 7, 6, 0 ] ]
34081: [-12.6, 15.2, -3.93333]
3409 .
3410
3411 r 5 @key{TAB} *
3412@end group
3413@end smallexample
3414
3415@noindent
3416Note that we had to be careful about the order in which we multiplied
3417the matrix and vector. If we multiplied in the other order, Calc would
3418assume the vector was a row vector in order to make the dimensions
3419come out right, and the answer would be incorrect. If you
3420don't feel safe letting Calc take either interpretation of your
3421vectors, use explicit
3422@texline @math{N\times1}
3423@infoline Nx1
3424or
3425@texline @math{1\times N}
3426@infoline 1xN
3427matrices instead. In this case, you would enter the original column
3428vector as @samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}.
3429
3430(@bullet{}) @strong{Exercise 2.} Algebraic entry allows you to make
3431vectors and matrices that include variables. Solve the following
3432system of equations to get expressions for @expr{x} and @expr{y}
3433in terms of @expr{a} and @expr{b}.
3434
3435@ifnottex
3436@group
3437@example
3438 x + a y = 6
3439 x + b y = 10
3440@end example
3441@end group
3442@end ifnottex
3443@tex
3444\turnoffactive
3445\beforedisplay
3446$$ \eqalign{ x &+ a y = 6 \cr
3447 x &+ b y = 10}
3448$$
3449\afterdisplay
3450@end tex
3451
3452@noindent
3453@xref{Matrix Answer 2, 2}. (@bullet{})
3454
3455@cindex Least-squares for over-determined systems
3456@cindex Over-determined systems of equations
3457(@bullet{}) @strong{Exercise 3.} A system of equations is ``over-determined''
3458if it has more equations than variables. It is often the case that
3459there are no values for the variables that will satisfy all the
3460equations at once, but it is still useful to find a set of values
3461which ``nearly'' satisfy all the equations. In terms of matrix equations,
3462you can't solve @expr{A X = B} directly because the matrix @expr{A}
3463is not square for an over-determined system. Matrix inversion works
3464only for square matrices. One common trick is to multiply both sides
3465on the left by the transpose of @expr{A}:
3466@ifnottex
3467@samp{trn(A)*A*X = trn(A)*B}.
3468@end ifnottex
3469@tex
3470\turnoffactive
3471$A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}.
3472@end tex
3473Now
3474@texline @math{A^T A}
3475@infoline @expr{trn(A)*A}
3476is a square matrix so a solution is possible. It turns out that the
3477@expr{X} vector you compute in this way will be a ``least-squares''
3478solution, which can be regarded as the ``closest'' solution to the set
3479of equations. Use Calc to solve the following over-determined
3480system:
3481
3482@ifnottex
3483@group
3484@example
3485 a + 2b + 3c = 6
3486 4a + 5b + 6c = 2
3487 7a + 6b = 3
3488 2a + 4b + 6c = 11
3489@end example
3490@end group
3491@end ifnottex
3492@tex
3493\turnoffactive
3494\beforedisplayh
3495$$ \openup1\jot \tabskip=0pt plus1fil
3496\halign to\displaywidth{\tabskip=0pt
3497 $\hfil#$&$\hfil{}#{}$&
3498 $\hfil#$&$\hfil{}#{}$&
3499 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3500 a&+&2b&+&3c&=6 \cr
3501 4a&+&5b&+&6c&=2 \cr
3502 7a&+&6b& & &=3 \cr
3503 2a&+&4b&+&6c&=11 \cr}
3504$$
3505\afterdisplayh
3506@end tex
3507
3508@noindent
3509@xref{Matrix Answer 3, 3}. (@bullet{})
3510
3511@node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
3512@subsection Vectors as Lists
3513
3514@noindent
3515@cindex Lists
3516Although Calc has a number of features for manipulating vectors and
3517matrices as mathematical objects, you can also treat vectors as
3518simple lists of values. For example, we saw that the @kbd{k f}
3519command returns a vector which is a list of the prime factors of a
3520number.
3521
3522You can pack and unpack stack entries into vectors:
3523
3524@smallexample
3525@group
35263: 10 1: [10, 20, 30] 3: 10
35272: 20 . 2: 20
35281: 30 1: 30
3529 . .
3530
3531 M-3 v p v u
3532@end group
3533@end smallexample
3534
3535You can also build vectors out of consecutive integers, or out
3536of many copies of a given value:
3537
3538@smallexample
3539@group
35401: [1, 2, 3, 4] 2: [1, 2, 3, 4] 2: [1, 2, 3, 4]
3541 . 1: 17 1: [17, 17, 17, 17]
3542 . .
3543
3544 v x 4 @key{RET} 17 v b 4 @key{RET}
3545@end group
3546@end smallexample
3547
3548You can apply an operator to every element of a vector using the
3549@dfn{map} command.
3550
3551@smallexample
3552@group
35531: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68]
3554 . . .
3555
3556 V M * 2 V M ^ V M Q
3557@end group
3558@end smallexample
3559
3560@noindent
3561In the first step, we multiply the vector of integers by the vector
3562of 17's elementwise. In the second step, we raise each element to
3563the power two. (The general rule is that both operands must be
3564vectors of the same length, or else one must be a vector and the
3565other a plain number.) In the final step, we take the square root
3566of each element.
3567
3568(@bullet{}) @strong{Exercise 1.} Compute a vector of powers of two
3569from
3570@texline @math{2^{-4}}
3571@infoline @expr{2^-4}
3572to @expr{2^4}. @xref{List Answer 1, 1}. (@bullet{})
3573
3574You can also @dfn{reduce} a binary operator across a vector.
3575For example, reducing @samp{*} computes the product of all the
3576elements in the vector:
3577
3578@smallexample
3579@group
35801: 123123 1: [3, 7, 11, 13, 41] 1: 123123
3581 . . .
3582
3583 123123 k f V R *
3584@end group
3585@end smallexample
3586
3587@noindent
3588In this example, we decompose 123123 into its prime factors, then
3589multiply those factors together again to yield the original number.
3590
3591We could compute a dot product ``by hand'' using mapping and
3592reduction:
3593
3594@smallexample
3595@group
35962: [1, 2, 3] 1: [7, 12, 0] 1: 19
35971: [7, 6, 0] . .
3598 .
3599
3600 r 1 r 2 V M * V R +
3601@end group
3602@end smallexample
3603
3604@noindent
3605Recalling two vectors from the previous section, we compute the
3606sum of pairwise products of the elements to get the same answer
3607for the dot product as before.
3608
3609A slight variant of vector reduction is the @dfn{accumulate} operation,
3610@kbd{V U}. This produces a vector of the intermediate results from
3611a corresponding reduction. Here we compute a table of factorials:
3612
3613@smallexample
3614@group
36151: [1, 2, 3, 4, 5, 6] 1: [1, 2, 6, 24, 120, 720]
3616 . .
3617
3618 v x 6 @key{RET} V U *
3619@end group
3620@end smallexample
3621
3622Calc allows vectors to grow as large as you like, although it gets
3623rather slow if vectors have more than about a hundred elements.
3624Actually, most of the time is spent formatting these large vectors
3625for display, not calculating on them. Try the following experiment
3626(if your computer is very fast you may need to substitute a larger
3627vector size).
3628
3629@smallexample
3630@group
36311: [1, 2, 3, 4, ... 1: [2, 3, 4, 5, ...
3632 . .
3633
3634 v x 500 @key{RET} 1 V M +
3635@end group
3636@end smallexample
3637
3638Now press @kbd{v .} (the letter @kbd{v}, then a period) and try the
3639experiment again. In @kbd{v .} mode, long vectors are displayed
3640``abbreviated'' like this:
3641
3642@smallexample
3643@group
36441: [1, 2, 3, ..., 500] 1: [2, 3, 4, ..., 501]
3645 . .
3646
3647 v x 500 @key{RET} 1 V M +
3648@end group
3649@end smallexample
3650
3651@noindent
3652(where now the @samp{...} is actually part of the Calc display).
3653You will find both operations are now much faster. But notice that
3654even in @w{@kbd{v .}} mode, the full vectors are still shown in the Trail.
3655Type @w{@kbd{t .}} to cause the trail to abbreviate as well, and try the
3656experiment one more time. Operations on long vectors are now quite
3657fast! (But of course if you use @kbd{t .} you will lose the ability
3658to get old vectors back using the @kbd{t y} command.)
3659
3660An easy way to view a full vector when @kbd{v .} mode is active is
3661to press @kbd{`} (back-quote) to edit the vector; editing always works
3662with the full, unabbreviated value.
3663
3664@cindex Least-squares for fitting a straight line
3665@cindex Fitting data to a line
3666@cindex Line, fitting data to
3667@cindex Data, extracting from buffers
3668@cindex Columns of data, extracting
3669As a larger example, let's try to fit a straight line to some data,
3670using the method of least squares. (Calc has a built-in command for
3671least-squares curve fitting, but we'll do it by hand here just to
3672practice working with vectors.) Suppose we have the following list
3673of values in a file we have loaded into Emacs:
3674
3675@smallexample
3676 x y
3677 --- ---
3678 1.34 0.234
3679 1.41 0.298
3680 1.49 0.402
3681 1.56 0.412
3682 1.64 0.466
3683 1.73 0.473
3684 1.82 0.601
3685 1.91 0.519
3686 2.01 0.603
3687 2.11 0.637
3688 2.22 0.645
3689 2.33 0.705
3690 2.45 0.917
3691 2.58 1.009
3692 2.71 0.971
3693 2.85 1.062
3694 3.00 1.148
3695 3.15 1.157
3696 3.32 1.354
3697@end smallexample
3698
3699@noindent
3700If you are reading this tutorial in printed form, you will find it
3701easiest to press @kbd{C-x * i} to enter the on-line Info version of
3702the manual and find this table there. (Press @kbd{g}, then type
3703@kbd{List Tutorial}, to jump straight to this section.)
3704
3705Position the cursor at the upper-left corner of this table, just
3706to the left of the @expr{1.34}. Press @kbd{C-@@} to set the mark.
3707(On your system this may be @kbd{C-2}, @kbd{C-@key{SPC}}, or @kbd{NUL}.)
3708Now position the cursor to the lower-right, just after the @expr{1.354}.
3709You have now defined this region as an Emacs ``rectangle.'' Still
3710in the Info buffer, type @kbd{C-x * r}. This command
3711(@code{calc-grab-rectangle}) will pop you back into the Calculator, with
3712the contents of the rectangle you specified in the form of a matrix.
3713
3714@smallexample
3715@group
37161: [ [ 1.34, 0.234 ]
3717 [ 1.41, 0.298 ]
3718 @dots{}
3719@end group
3720@end smallexample
3721
3722@noindent
3723(You may wish to use @kbd{v .} mode to abbreviate the display of this
3724large matrix.)
3725
3726We want to treat this as a pair of lists. The first step is to
3727transpose this matrix into a pair of rows. Remember, a matrix is
3728just a vector of vectors. So we can unpack the matrix into a pair
3729of row vectors on the stack.
3730
3731@smallexample
3732@group
37331: [ [ 1.34, 1.41, 1.49, ... ] 2: [1.34, 1.41, 1.49, ... ]
3734 [ 0.234, 0.298, 0.402, ... ] ] 1: [0.234, 0.298, 0.402, ... ]
3735 . .
3736
3737 v t v u
3738@end group
3739@end smallexample
3740
3741@noindent
3742Let's store these in quick variables 1 and 2, respectively.
3743
3744@smallexample
3745@group
37461: [1.34, 1.41, 1.49, ... ] .
3747 .
3748
3749 t 2 t 1
3750@end group
3751@end smallexample
3752
3753@noindent
3754(Recall that @kbd{t 2} is a variant of @kbd{s 2} that removes the
3755stored value from the stack.)
3756
3757In a least squares fit, the slope @expr{m} is given by the formula
3758
3759@ifnottex
3760@example
3761m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
3762@end example
3763@end ifnottex
3764@tex
3765\turnoffactive
3766\beforedisplay
3767$$ m = {N \sum x y - \sum x \sum y \over
3768 N \sum x^2 - \left( \sum x \right)^2} $$
3769\afterdisplay
3770@end tex
3771
3772@noindent
3773where
3774@texline @math{\sum x}
3775@infoline @expr{sum(x)}
3776represents the sum of all the values of @expr{x}. While there is an
3777actual @code{sum} function in Calc, it's easier to sum a vector using a
3778simple reduction. First, let's compute the four different sums that
3779this formula uses.
3780
3781@smallexample
3782@group
37831: 41.63 1: 98.0003
3784 . .
3785
3786 r 1 V R + t 3 r 1 2 V M ^ V R + t 4
3787
3788@end group
3789@end smallexample
3790@noindent
3791@smallexample
3792@group
37931: 13.613 1: 33.36554
3794 . .
3795
3796 r 2 V R + t 5 r 1 r 2 V M * V R + t 6
3797@end group
3798@end smallexample
3799
3800@ifnottex
3801@noindent
3802These are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
3803respectively. (We could have used @kbd{*} to compute @samp{sum(x^2)} and
3804@samp{sum(x y)}.)
3805@end ifnottex
3806@tex
3807\turnoffactive
3808These are $\sum x$, $\sum x^2$, $\sum y$, and $\sum x y$,
3809respectively. (We could have used \kbd{*} to compute $\sum x^2$ and
3810$\sum x y$.)
3811@end tex
3812
3813Finally, we also need @expr{N}, the number of data points. This is just
3814the length of either of our lists.
3815
3816@smallexample
3817@group
38181: 19
3819 .
3820
3821 r 1 v l t 7
3822@end group
3823@end smallexample
3824
3825@noindent
3826(That's @kbd{v} followed by a lower-case @kbd{l}.)
3827
3828Now we grind through the formula:
3829
3830@smallexample
3831@group
38321: 633.94526 2: 633.94526 1: 67.23607
3833 . 1: 566.70919 .
3834 .
3835
3836 r 7 r 6 * r 3 r 5 * -
3837
3838@end group
3839@end smallexample
3840@noindent
3841@smallexample
3842@group
38432: 67.23607 3: 67.23607 2: 67.23607 1: 0.52141679
38441: 1862.0057 2: 1862.0057 1: 128.9488 .
3845 . 1: 1733.0569 .
3846 .
3847
3848 r 7 r 4 * r 3 2 ^ - / t 8
3849@end group
3850@end smallexample
3851
3852That gives us the slope @expr{m}. The y-intercept @expr{b} can now
3853be found with the simple formula,
3854
3855@ifnottex
3856@example
3857b = (sum(y) - m sum(x)) / N
3858@end example
3859@end ifnottex
3860@tex
3861\turnoffactive
3862\beforedisplay
3863$$ b = {\sum y - m \sum x \over N} $$
3864\afterdisplay
3865\vskip10pt
3866@end tex
3867
3868@smallexample
3869@group
38701: 13.613 2: 13.613 1: -8.09358 1: -0.425978
3871 . 1: 21.70658 . .
3872 .
3873
3874 r 5 r 8 r 3 * - r 7 / t 9
3875@end group
3876@end smallexample
3877
3878Let's ``plot'' this straight line approximation,
3879@texline @math{y \approx m x + b},
3880@infoline @expr{m x + b},
3881and compare it with the original data.
3882
3883@smallexample
3884@group
38851: [0.699, 0.735, ... ] 1: [0.273, 0.309, ... ]
3886 . .
3887
3888 r 1 r 8 * r 9 + s 0
3889@end group
3890@end smallexample
3891
3892@noindent
3893Notice that multiplying a vector by a constant, and adding a constant
3894to a vector, can be done without mapping commands since these are
3895common operations from vector algebra. As far as Calc is concerned,
3896we've just been doing geometry in 19-dimensional space!
3897
3898We can subtract this vector from our original @expr{y} vector to get
3899a feel for the error of our fit. Let's find the maximum error:
3900
3901@smallexample
3902@group
39031: [0.0387, 0.0112, ... ] 1: [0.0387, 0.0112, ... ] 1: 0.0897
3904 . . .
3905
3906 r 2 - V M A V R X
3907@end group
3908@end smallexample
3909
3910@noindent
3911First we compute a vector of differences, then we take the absolute
3912values of these differences, then we reduce the @code{max} function
3913across the vector. (The @code{max} function is on the two-key sequence
3914@kbd{f x}; because it is so common to use @code{max} in a vector
3915operation, the letters @kbd{X} and @kbd{N} are also accepted for
3916@code{max} and @code{min} in this context. In general, you answer
3917the @kbd{V M} or @kbd{V R} prompt with the actual key sequence that
3918invokes the function you want. You could have typed @kbd{V R f x} or
3919even @kbd{V R x max @key{RET}} if you had preferred.)
3920
3921If your system has the GNUPLOT program, you can see graphs of your
3922data and your straight line to see how well they match. (If you have
3923GNUPLOT 3.0 or higher, the following instructions will work regardless
3924of the kind of display you have. Some GNUPLOT 2.0, non-X-windows systems
3925may require additional steps to view the graphs.)
3926
3927Let's start by plotting the original data. Recall the ``@var{x}'' and ``@var{y}''
3928vectors onto the stack and press @kbd{g f}. This ``fast'' graphing
3929command does everything you need to do for simple, straightforward
3930plotting of data.
3931
3932@smallexample
3933@group
39342: [1.34, 1.41, 1.49, ... ]
39351: [0.234, 0.298, 0.402, ... ]
3936 .
3937
3938 r 1 r 2 g f
3939@end group
3940@end smallexample
3941
3942If all goes well, you will shortly get a new window containing a graph
3943of the data. (If not, contact your GNUPLOT or Calc installer to find
3944out what went wrong.) In the X window system, this will be a separate
3945graphics window. For other kinds of displays, the default is to
3946display the graph in Emacs itself using rough character graphics.
3947Press @kbd{q} when you are done viewing the character graphics.
3948
3949Next, let's add the line we got from our least-squares fit.
3950@ifinfo
3951(If you are reading this tutorial on-line while running Calc, typing
3952@kbd{g a} may cause the tutorial to disappear from its window and be
3953replaced by a buffer named @samp{*Gnuplot Commands*}. The tutorial
3954will reappear when you terminate GNUPLOT by typing @kbd{g q}.)
3955@end ifinfo
3956
3957@smallexample
3958@group
39592: [1.34, 1.41, 1.49, ... ]
39601: [0.273, 0.309, 0.351, ... ]
3961 .
3962
3963 @key{DEL} r 0 g a g p
3964@end group
3965@end smallexample
3966
3967It's not very useful to get symbols to mark the data points on this
3968second curve; you can type @kbd{g S g p} to remove them. Type @kbd{g q}
3969when you are done to remove the X graphics window and terminate GNUPLOT.
3970
3971(@bullet{}) @strong{Exercise 2.} An earlier exercise showed how to do
3972least squares fitting to a general system of equations. Our 19 data
3973points are really 19 equations of the form @expr{y_i = m x_i + b} for
3974different pairs of @expr{(x_i,y_i)}. Use the matrix-transpose method
3975to solve for @expr{m} and @expr{b}, duplicating the above result.
3976@xref{List Answer 2, 2}. (@bullet{})
3977
3978@cindex Geometric mean
3979(@bullet{}) @strong{Exercise 3.} If the input data do not form a
3980rectangle, you can use @w{@kbd{C-x * g}} (@code{calc-grab-region})
3981to grab the data the way Emacs normally works with regions---it reads
3982left-to-right, top-to-bottom, treating line breaks the same as spaces.
3983Use this command to find the geometric mean of the following numbers.
3984(The geometric mean is the @var{n}th root of the product of @var{n} numbers.)
3985
3986@example
39872.3 6 22 15.1 7
3988 15 14 7.5
3989 2.5
3990@end example
3991
3992@noindent
3993The @kbd{C-x * g} command accepts numbers separated by spaces or commas,
3994with or without surrounding vector brackets.
3995@xref{List Answer 3, 3}. (@bullet{})
3996
3997@ifnottex
3998As another example, a theorem about binomial coefficients tells
3999us that the alternating sum of binomial coefficients
4000@var{n}-choose-0 minus @var{n}-choose-1 plus @var{n}-choose-2, and so
4001on up to @var{n}-choose-@var{n},
4002always comes out to zero. Let's verify this
4003for @expr{n=6}.
4004@end ifnottex
4005@tex
4006As another example, a theorem about binomial coefficients tells
4007us that the alternating sum of binomial coefficients
4008${n \choose 0} - {n \choose 1} + {n \choose 2} - \cdots \pm {n \choose n}$
4009always comes out to zero. Let's verify this
4010for \cite{n=6}.
4011@end tex
4012
4013@smallexample
4014@group
40151: [1, 2, 3, 4, 5, 6, 7] 1: [0, 1, 2, 3, 4, 5, 6]
4016 . .
4017
4018 v x 7 @key{RET} 1 -
4019
4020@end group
4021@end smallexample
4022@noindent
4023@smallexample
4024@group
40251: [1, -6, 15, -20, 15, -6, 1] 1: 0
4026 . .
4027
4028 V M ' (-1)^$ choose(6,$) @key{RET} V R +
4029@end group
4030@end smallexample
4031
4032The @kbd{V M '} command prompts you to enter any algebraic expression
4033to define the function to map over the vector. The symbol @samp{$}
4034inside this expression represents the argument to the function.
4035The Calculator applies this formula to each element of the vector,
4036substituting each element's value for the @samp{$} sign(s) in turn.
4037
4038To define a two-argument function, use @samp{$$} for the first
4039argument and @samp{$} for the second: @kbd{V M ' $$-$ @key{RET}} is
4040equivalent to @kbd{V M -}. This is analogous to regular algebraic
4041entry, where @samp{$$} would refer to the next-to-top stack entry
4042and @samp{$} would refer to the top stack entry, and @kbd{' $$-$ @key{RET}}
4043would act exactly like @kbd{-}.
4044
4045Notice that the @kbd{V M '} command has recorded two things in the
4046trail: The result, as usual, and also a funny-looking thing marked
4047@samp{oper} that represents the operator function you typed in.
4048The function is enclosed in @samp{< >} brackets, and the argument is
4049denoted by a @samp{#} sign. If there were several arguments, they
4050would be shown as @samp{#1}, @samp{#2}, and so on. (For example,
4051@kbd{V M ' $$-$} will put the function @samp{<#1 - #2>} on the
4052trail.) This object is a ``nameless function''; you can use nameless
4053@w{@samp{< >}} notation to answer the @kbd{V M '} prompt if you like.
4054Nameless function notation has the interesting, occasionally useful
4055property that a nameless function is not actually evaluated until
4056it is used. For example, @kbd{V M ' $+random(2.0)} evaluates
4057@samp{random(2.0)} once and adds that random number to all elements
4058of the vector, but @kbd{V M ' <#+random(2.0)>} evaluates the
4059@samp{random(2.0)} separately for each vector element.
4060
4061Another group of operators that are often useful with @kbd{V M} are
4062the relational operators: @kbd{a =}, for example, compares two numbers
4063and gives the result 1 if they are equal, or 0 if not. Similarly,
4064@w{@kbd{a <}} checks for one number being less than another.
4065
4066Other useful vector operations include @kbd{v v}, to reverse a
4067vector end-for-end; @kbd{V S}, to sort the elements of a vector
4068into increasing order; and @kbd{v r} and @w{@kbd{v c}}, to extract
4069one row or column of a matrix, or (in both cases) to extract one
4070element of a plain vector. With a negative argument, @kbd{v r}
4071and @kbd{v c} instead delete one row, column, or vector element.
4072
4073@cindex Divisor functions
4074(@bullet{}) @strong{Exercise 4.} The @expr{k}th @dfn{divisor function}
4075@tex
4076$\sigma_k(n)$
4077@end tex
4078is the sum of the @expr{k}th powers of all the divisors of an
4079integer @expr{n}. Figure out a method for computing the divisor
4080function for reasonably small values of @expr{n}. As a test,
4081the 0th and 1st divisor functions of 30 are 8 and 72, respectively.
4082@xref{List Answer 4, 4}. (@bullet{})
4083
4084@cindex Square-free numbers
4085@cindex Duplicate values in a list
4086(@bullet{}) @strong{Exercise 5.} The @kbd{k f} command produces a
4087list of prime factors for a number. Sometimes it is important to
4088know that a number is @dfn{square-free}, i.e., that no prime occurs
4089more than once in its list of prime factors. Find a sequence of
4090keystrokes to tell if a number is square-free; your method should
4091leave 1 on the stack if it is, or 0 if it isn't.
4092@xref{List Answer 5, 5}. (@bullet{})
4093
4094@cindex Triangular lists
4095(@bullet{}) @strong{Exercise 6.} Build a list of lists that looks
4096like the following diagram. (You may wish to use the @kbd{v /}
4097command to enable multi-line display of vectors.)
4098
4099@smallexample
4100@group
41011: [ [1],
4102 [1, 2],
4103 [1, 2, 3],
4104 [1, 2, 3, 4],
4105 [1, 2, 3, 4, 5],
4106 [1, 2, 3, 4, 5, 6] ]
4107@end group
4108@end smallexample
4109
4110@noindent
4111@xref{List Answer 6, 6}. (@bullet{})
4112
4113(@bullet{}) @strong{Exercise 7.} Build the following list of lists.
4114
4115@smallexample
4116@group
41171: [ [0],
4118 [1, 2],
4119 [3, 4, 5],
4120 [6, 7, 8, 9],
4121 [10, 11, 12, 13, 14],
4122 [15, 16, 17, 18, 19, 20] ]
4123@end group
4124@end smallexample
4125
4126@noindent
4127@xref{List Answer 7, 7}. (@bullet{})
4128
4129@cindex Maximizing a function over a list of values
4130@c [fix-ref Numerical Solutions]
4131(@bullet{}) @strong{Exercise 8.} Compute a list of values of Bessel's
4132@texline @math{J_1(x)}
4133@infoline @expr{J1}
4134function @samp{besJ(1,x)} for @expr{x} from 0 to 5 in steps of 0.25.
4135Find the value of @expr{x} (from among the above set of values) for
4136which @samp{besJ(1,x)} is a maximum. Use an ``automatic'' method,
4137i.e., just reading along the list by hand to find the largest value
4138is not allowed! (There is an @kbd{a X} command which does this kind
4139of thing automatically; @pxref{Numerical Solutions}.)
4140@xref{List Answer 8, 8}. (@bullet{})
4141
4142@cindex Digits, vectors of
4143(@bullet{}) @strong{Exercise 9.} You are given an integer in the range
4144@texline @math{0 \le N < 10^m}
4145@infoline @expr{0 <= N < 10^m}
4146for @expr{m=12} (i.e., an integer of less than
4147twelve digits). Convert this integer into a vector of @expr{m}
4148digits, each in the range from 0 to 9. In vector-of-digits notation,
4149add one to this integer to produce a vector of @expr{m+1} digits
4150(since there could be a carry out of the most significant digit).
4151Convert this vector back into a regular integer. A good integer
4152to try is 25129925999. @xref{List Answer 9, 9}. (@bullet{})
4153
4154(@bullet{}) @strong{Exercise 10.} Your friend Joe tried to use
4155@kbd{V R a =} to test if all numbers in a list were equal. What
4156happened? How would you do this test? @xref{List Answer 10, 10}. (@bullet{})
4157
4158(@bullet{}) @strong{Exercise 11.} The area of a circle of radius one
4159is @cpi{}. The area of the
4160@texline @math{2\times2}
4161@infoline 2x2
4162square that encloses that circle is 4. So if we throw @var{n} darts at
4163random points in the square, about @cpiover{4} of them will land inside
4164the circle. This gives us an entertaining way to estimate the value of
4165@cpi{}. The @w{@kbd{k r}}
4166command picks a random number between zero and the value on the stack.
4167We could get a random floating-point number between @mathit{-1} and 1 by typing
4168@w{@kbd{2.0 k r 1 -}}. Build a vector of 100 random @expr{(x,y)} points in
4169this square, then use vector mapping and reduction to count how many
4170points lie inside the unit circle. Hint: Use the @kbd{v b} command.
4171@xref{List Answer 11, 11}. (@bullet{})
4172
4173@cindex Matchstick problem
4174(@bullet{}) @strong{Exercise 12.} The @dfn{matchstick problem} provides
4175another way to calculate @cpi{}. Say you have an infinite field
4176of vertical lines with a spacing of one inch. Toss a one-inch matchstick
4177onto the field. The probability that the matchstick will land crossing
4178a line turns out to be
4179@texline @math{2/\pi}.
4180@infoline @expr{2/pi}.
4181Toss 100 matchsticks to estimate @cpi{}. (If you want still more fun,
4182the probability that the GCD (@w{@kbd{k g}}) of two large integers is
4183one turns out to be
4184@texline @math{6/\pi^2}.
4185@infoline @expr{6/pi^2}.
4186That provides yet another way to estimate @cpi{}.)
4187@xref{List Answer 12, 12}. (@bullet{})
4188
4189(@bullet{}) @strong{Exercise 13.} An algebraic entry of a string in
4190double-quote marks, @samp{"hello"}, creates a vector of the numerical
4191(ASCII) codes of the characters (here, @expr{[104, 101, 108, 108, 111]}).
4192Sometimes it is convenient to compute a @dfn{hash code} of a string,
4193which is just an integer that represents the value of that string.
4194Two equal strings have the same hash code; two different strings
4195@dfn{probably} have different hash codes. (For example, Calc has
4196over 400 function names, but Emacs can quickly find the definition for
4197any given name because it has sorted the functions into ``buckets'' by
4198their hash codes. Sometimes a few names will hash into the same bucket,
4199but it is easier to search among a few names than among all the names.)
4200One popular hash function is computed as follows: First set @expr{h = 0}.
4201Then, for each character from the string in turn, set @expr{h = 3h + c_i}
4202where @expr{c_i} is the character's ASCII code. If we have 511 buckets,
4203we then take the hash code modulo 511 to get the bucket number. Develop a
4204simple command or commands for converting string vectors into hash codes.
4205The hash code for @samp{"Testing, 1, 2, 3"} is 1960915098, which modulo
4206511 is 121. @xref{List Answer 13, 13}. (@bullet{})
4207
4208(@bullet{}) @strong{Exercise 14.} The @kbd{H V R} and @kbd{H V U}
4209commands do nested function evaluations. @kbd{H V U} takes a starting
4210value and a number of steps @var{n} from the stack; it then applies the
4211function you give to the starting value 0, 1, 2, up to @var{n} times
4212and returns a vector of the results. Use this command to create a
4213``random walk'' of 50 steps. Start with the two-dimensional point
4214@expr{(0,0)}; then take one step a random distance between @mathit{-1} and 1
4215in both @expr{x} and @expr{y}; then take another step, and so on. Use the
4216@kbd{g f} command to display this random walk. Now modify your random
4217walk to walk a unit distance, but in a random direction, at each step.
4218(Hint: The @code{sincos} function returns a vector of the cosine and
4219sine of an angle.) @xref{List Answer 14, 14}. (@bullet{})
4220
4221@node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
4222@section Types Tutorial
4223
4224@noindent
4225Calc understands a variety of data types as well as simple numbers.
4226In this section, we'll experiment with each of these types in turn.
4227
4228The numbers we've been using so far have mainly been either @dfn{integers}
4229or @dfn{floats}. We saw that floats are usually a good approximation to
4230the mathematical concept of real numbers, but they are only approximations
4231and are susceptible to roundoff error. Calc also supports @dfn{fractions},
4232which can exactly represent any rational number.
4233
4234@smallexample
4235@group
42361: 3628800 2: 3628800 1: 518400:7 1: 518414:7 1: 7:518414
4237 . 1: 49 . . .
4238 .
4239
4240 10 ! 49 @key{RET} : 2 + &
4241@end group
4242@end smallexample
4243
4244@noindent
4245The @kbd{:} command divides two integers to get a fraction; @kbd{/}
4246would normally divide integers to get a floating-point result.
4247Notice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
4248since the @kbd{:} would otherwise be interpreted as part of a
4249fraction beginning with 49.
4250
4251You can convert between floating-point and fractional format using
4252@kbd{c f} and @kbd{c F}:
4253
4254@smallexample
4255@group
42561: 1.35027217629e-5 1: 7:518414
4257 . .
4258
4259 c f c F
4260@end group
4261@end smallexample
4262
4263The @kbd{c F} command replaces a floating-point number with the
4264``simplest'' fraction whose floating-point representation is the
4265same, to within the current precision.
4266
4267@smallexample
4268@group
42691: 3.14159265359 1: 1146408:364913 1: 3.1416 1: 355:113
4270 . . . .
4271
4272 P c F @key{DEL} p 5 @key{RET} P c F
4273@end group
4274@end smallexample
4275
4276(@bullet{}) @strong{Exercise 1.} A calculation has produced the
4277result 1.26508260337. You suspect it is the square root of the
4278product of @cpi{} and some rational number. Is it? (Be sure
4279to allow for roundoff error!) @xref{Types Answer 1, 1}. (@bullet{})
4280
4281@dfn{Complex numbers} can be stored in both rectangular and polar form.
4282
4283@smallexample
4284@group
42851: -9 1: (0, 3) 1: (3; 90.) 1: (6; 90.) 1: (2.4495; 45.)
4286 . . . . .
4287
4288 9 n Q c p 2 * Q
4289@end group
4290@end smallexample
4291
4292@noindent
4293The square root of @mathit{-9} is by default rendered in rectangular form
4294(@w{@expr{0 + 3i}}), but we can convert it to polar form (3 with a
4295phase angle of 90 degrees). All the usual arithmetic and scientific
4296operations are defined on both types of complex numbers.
4297
4298Another generalized kind of number is @dfn{infinity}. Infinity
4299isn't really a number, but it can sometimes be treated like one.
4300Calc uses the symbol @code{inf} to represent positive infinity,
4301i.e., a value greater than any real number. Naturally, you can
4302also write @samp{-inf} for minus infinity, a value less than any
4303real number. The word @code{inf} can only be input using
4304algebraic entry.
4305
4306@smallexample
4307@group
43082: inf 2: -inf 2: -inf 2: -inf 1: nan
43091: -17 1: -inf 1: -inf 1: inf .
4310 . . . .
4311
4312' inf @key{RET} 17 n * @key{RET} 72 + A +
4313@end group
4314@end smallexample
4315
4316@noindent
4317Since infinity is infinitely large, multiplying it by any finite
4318number (like @mathit{-17}) has no effect, except that since @mathit{-17}
4319is negative, it changes a plus infinity to a minus infinity.
4320(``A huge positive number, multiplied by @mathit{-17}, yields a huge
4321negative number.'') Adding any finite number to infinity also
4322leaves it unchanged. Taking an absolute value gives us plus
4323infinity again. Finally, we add this plus infinity to the minus
4324infinity we had earlier. If you work it out, you might expect
4325the answer to be @mathit{-72} for this. But the 72 has been completely
4326lost next to the infinities; by the time we compute @w{@samp{inf - inf}}
4327the finite difference between them, if any, is undetectable.
4328So we say the result is @dfn{indeterminate}, which Calc writes
4329with the symbol @code{nan} (for Not A Number).
4330
4331Dividing by zero is normally treated as an error, but you can get
4332Calc to write an answer in terms of infinity by pressing @kbd{m i}
4333to turn on Infinite mode.
4334
4335@smallexample
4336@group
43373: nan 2: nan 2: nan 2: nan 1: nan
43382: 1 1: 1 / 0 1: uinf 1: uinf .
43391: 0 . . .
4340 .
4341
4342 1 @key{RET} 0 / m i U / 17 n * +
4343@end group
4344@end smallexample
4345
4346@noindent
4347Dividing by zero normally is left unevaluated, but after @kbd{m i}
4348it instead gives an infinite result. The answer is actually
4349@code{uinf}, ``undirected infinity.'' If you look at a graph of
4350@expr{1 / x} around @w{@expr{x = 0}}, you'll see that it goes toward
4351plus infinity as you approach zero from above, but toward minus
4352infinity as you approach from below. Since we said only @expr{1 / 0},
4353Calc knows that the answer is infinite but not in which direction.
4354That's what @code{uinf} means. Notice that multiplying @code{uinf}
4355by a negative number still leaves plain @code{uinf}; there's no
4356point in saying @samp{-uinf} because the sign of @code{uinf} is
4357unknown anyway. Finally, we add @code{uinf} to our @code{nan},
4358yielding @code{nan} again. It's easy to see that, because
4359@code{nan} means ``totally unknown'' while @code{uinf} means
4360``unknown sign but known to be infinite,'' the more mysterious
4361@code{nan} wins out when it is combined with @code{uinf}, or, for
4362that matter, with anything else.
4363
4364(@bullet{}) @strong{Exercise 2.} Predict what Calc will answer
4365for each of these formulas: @samp{inf / inf}, @samp{exp(inf)},
4366@samp{exp(-inf)}, @samp{sqrt(-inf)}, @samp{sqrt(uinf)},
4367@samp{abs(uinf)}, @samp{ln(0)}.
4368@xref{Types Answer 2, 2}. (@bullet{})
4369
4370(@bullet{}) @strong{Exercise 3.} We saw that @samp{inf - inf = nan},
4371which stands for an unknown value. Can @code{nan} stand for
4372a complex number? Can it stand for infinity?
4373@xref{Types Answer 3, 3}. (@bullet{})
4374
4375@dfn{HMS forms} represent a value in terms of hours, minutes, and
4376seconds.
4377
4378@smallexample
4379@group
43801: 2@@ 30' 0" 1: 3@@ 30' 0" 2: 3@@ 30' 0" 1: 2.
4381 . . 1: 1@@ 45' 0." .
4382 .
4383
4384 2@@ 30' @key{RET} 1 + @key{RET} 2 / /
4385@end group
4386@end smallexample
4387
4388HMS forms can also be used to hold angles in degrees, minutes, and
4389seconds.
4390
4391@smallexample
4392@group
43931: 0.5 1: 26.56505 1: 26@@ 33' 54.18" 1: 0.44721
4394 . . . .
4395
4396 0.5 I T c h S
4397@end group
4398@end smallexample
4399
4400@noindent
4401First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
4402form, then we take the sine of that angle. Note that the trigonometric
4403functions will accept HMS forms directly as input.
4404
4405@cindex Beatles
4406(@bullet{}) @strong{Exercise 4.} The Beatles' @emph{Abbey Road} is
440747 minutes and 26 seconds long, and contains 17 songs. What is the
4408average length of a song on @emph{Abbey Road}? If the Extended Disco
4409Version of @emph{Abbey Road} added 20 seconds to the length of each
4410song, how long would the album be? @xref{Types Answer 4, 4}. (@bullet{})
4411
4412A @dfn{date form} represents a date, or a date and time. Dates must
4413be entered using algebraic entry. Date forms are surrounded by
4414@samp{< >} symbols; most standard formats for dates are recognized.
4415
4416@smallexample
4417@group
44182: <Sun Jan 13, 1991> 1: 2.25
44191: <6:00pm Thu Jan 10, 1991> .
4420 .
4421
4422' <13 Jan 1991>, <1/10/91, 6pm> @key{RET} -
4423@end group
4424@end smallexample
4425
4426@noindent
4427In this example, we enter two dates, then subtract to find the
4428number of days between them. It is also possible to add an
4429HMS form or a number (of days) to a date form to get another
4430date form.
4431
4432@smallexample
4433@group
44341: <4:45:59pm Mon Jan 14, 1991> 1: <2:50:59am Thu Jan 17, 1991>
4435 . .
4436
4437 t N 2 + 10@@ 5' +
4438@end group
4439@end smallexample
4440
4441@c [fix-ref Date Arithmetic]
4442@noindent
4443The @kbd{t N} (``now'') command pushes the current date and time on the
4444stack; then we add two days, ten hours and five minutes to the date and
4445time. Other date-and-time related commands include @kbd{t J}, which
4446does Julian day conversions, @kbd{t W}, which finds the beginning of
4447the week in which a date form lies, and @kbd{t I}, which increments a
4448date by one or several months. @xref{Date Arithmetic}, for more.
4449
4450(@bullet{}) @strong{Exercise 5.} How many days until the next
4451Friday the 13th? @xref{Types Answer 5, 5}. (@bullet{})
4452
4453(@bullet{}) @strong{Exercise 6.} How many leap years will there be
4454between now and the year 10001 A.D.? @xref{Types Answer 6, 6}. (@bullet{})
4455
4456@cindex Slope and angle of a line
4457@cindex Angle and slope of a line
4458An @dfn{error form} represents a mean value with an attached standard
4459deviation, or error estimate. Suppose our measurements indicate that
4460a certain telephone pole is about 30 meters away, with an estimated
4461error of 1 meter, and 8 meters tall, with an estimated error of 0.2
4462meters. What is the slope of a line from here to the top of the
4463pole, and what is the equivalent angle in degrees?
4464
4465@smallexample
4466@group
44671: 8 +/- 0.2 2: 8 +/- 0.2 1: 0.266 +/- 0.011 1: 14.93 +/- 0.594
4468 . 1: 30 +/- 1 . .
4469 .
4470
4471 8 p .2 @key{RET} 30 p 1 / I T
4472@end group
4473@end smallexample
4474
4475@noindent
4476This means that the angle is about 15 degrees, and, assuming our
4477original error estimates were valid standard deviations, there is about
4478a 60% chance that the result is correct within 0.59 degrees.
4479
4480@cindex Torus, volume of
4481(@bullet{}) @strong{Exercise 7.} The volume of a torus (a donut shape) is
4482@texline @math{2 \pi^2 R r^2}
4483@infoline @w{@expr{2 pi^2 R r^2}}
4484where @expr{R} is the radius of the circle that
4485defines the center of the tube and @expr{r} is the radius of the tube
4486itself. Suppose @expr{R} is 20 cm and @expr{r} is 4 cm, each known to
4487within 5 percent. What is the volume and the relative uncertainty of
4488the volume? @xref{Types Answer 7, 7}. (@bullet{})
4489
4490An @dfn{interval form} represents a range of values. While an
4491error form is best for making statistical estimates, intervals give
4492you exact bounds on an answer. Suppose we additionally know that
4493our telephone pole is definitely between 28 and 31 meters away,
4494and that it is between 7.7 and 8.1 meters tall.
4495
4496@smallexample
4497@group
44981: [7.7 .. 8.1] 2: [7.7 .. 8.1] 1: [0.24 .. 0.28] 1: [13.9 .. 16.1]
4499 . 1: [28 .. 31] . .
4500 .
4501
4502 [ 7.7 .. 8.1 ] [ 28 .. 31 ] / I T
4503@end group
4504@end smallexample
4505
4506@noindent
4507If our bounds were correct, then the angle to the top of the pole
4508is sure to lie in the range shown.
4509
4510The square brackets around these intervals indicate that the endpoints
4511themselves are allowable values. In other words, the distance to the
4512telephone pole is between 28 and 31, @emph{inclusive}. You can also
4513make an interval that is exclusive of its endpoints by writing
4514parentheses instead of square brackets. You can even make an interval
4515which is inclusive (``closed'') on one end and exclusive (``open'') on
4516the other.
4517
4518@smallexample
4519@group
45201: [1 .. 10) 1: (0.1 .. 1] 2: (0.1 .. 1] 1: (0.2 .. 3)
4521 . . 1: [2 .. 3) .
4522 .
4523
4524 [ 1 .. 10 ) & [ 2 .. 3 ) *
4525@end group
4526@end smallexample
4527
4528@noindent
4529The Calculator automatically keeps track of which end values should
4530be open and which should be closed. You can also make infinite or
4531semi-infinite intervals by using @samp{-inf} or @samp{inf} for one
4532or both endpoints.
4533
4534(@bullet{}) @strong{Exercise 8.} What answer would you expect from
4535@samp{@w{1 /} @w{(0 .. 10)}}? What about @samp{@w{1 /} @w{(-10 .. 0)}}? What
4536about @samp{@w{1 /} @w{[0 .. 10]}} (where the interval actually includes
4537zero)? What about @samp{@w{1 /} @w{(-10 .. 10)}}?
4538@xref{Types Answer 8, 8}. (@bullet{})
4539
4540(@bullet{}) @strong{Exercise 9.} Two easy ways of squaring a number
4541are @kbd{@key{RET} *} and @w{@kbd{2 ^}}. Normally these produce the same
4542answer. Would you expect this still to hold true for interval forms?
4543If not, which of these will result in a larger interval?
4544@xref{Types Answer 9, 9}. (@bullet{})
4545
4546A @dfn{modulo form} is used for performing arithmetic modulo @var{m}.
4547For example, arithmetic involving time is generally done modulo 12
4548or 24 hours.
4549
4550@smallexample
4551@group
45521: 17 mod 24 1: 3 mod 24 1: 21 mod 24 1: 9 mod 24
4553 . . . .
4554
4555 17 M 24 @key{RET} 10 + n 5 /
4556@end group
4557@end smallexample
4558
4559@noindent
4560In this last step, Calc has divided by 5 modulo 24; i.e., it has found a
4561new number which, when multiplied by 5 modulo 24, produces the original
4562number, 21. If @var{m} is prime and the divisor is not a multiple of
4563@var{m}, it is always possible to find such a number. For non-prime
4564@var{m} like 24, it is only sometimes possible.
4565
4566@smallexample
4567@group
45681: 10 mod 24 1: 16 mod 24 1: 1000000... 1: 16
4569 . . . .
4570
4571 10 M 24 @key{RET} 100 ^ 10 @key{RET} 100 ^ 24 %
4572@end group
4573@end smallexample
4574
4575@noindent
4576These two calculations get the same answer, but the first one is
4577much more efficient because it avoids the huge intermediate value
4578that arises in the second one.
4579
4580@cindex Fermat, primality test of
4581(@bullet{}) @strong{Exercise 10.} A theorem of Pierre de Fermat
4582says that
4583@texline @w{@math{x^{n-1} \bmod n = 1}}
4584@infoline @expr{x^(n-1) mod n = 1}
4585if @expr{n} is a prime number and @expr{x} is an integer less than
4586@expr{n}. If @expr{n} is @emph{not} a prime number, this will
4587@emph{not} be true for most values of @expr{x}. Thus we can test
4588informally if a number is prime by trying this formula for several
4589values of @expr{x}. Use this test to tell whether the following numbers
4590are prime: 811749613, 15485863. @xref{Types Answer 10, 10}. (@bullet{})
4591
4592It is possible to use HMS forms as parts of error forms, intervals,
4593modulo forms, or as the phase part of a polar complex number.
4594For example, the @code{calc-time} command pushes the current time
4595of day on the stack as an HMS/modulo form.
4596
4597@smallexample
4598@group
45991: 17@@ 34' 45" mod 24@@ 0' 0" 1: 6@@ 22' 15" mod 24@@ 0' 0"
4600 . .
4601
4602 x time @key{RET} n
4603@end group
4604@end smallexample
4605
4606@noindent
4607This calculation tells me it is six hours and 22 minutes until midnight.
4608
4609(@bullet{}) @strong{Exercise 11.} A rule of thumb is that one year
4610is about
4611@texline @math{\pi \times 10^7}
4612@infoline @w{@expr{pi * 10^7}}
4613seconds. What time will it be that many seconds from right now?
4614@xref{Types Answer 11, 11}. (@bullet{})
4615
4616(@bullet{}) @strong{Exercise 12.} You are preparing to order packaging
4617for the CD release of the Extended Disco Version of @emph{Abbey Road}.
4618You are told that the songs will actually be anywhere from 20 to 60
4619seconds longer than the originals. One CD can hold about 75 minutes
4620of music. Should you order single or double packages?
4621@xref{Types Answer 12, 12}. (@bullet{})
4622
4623Another kind of data the Calculator can manipulate is numbers with
4624@dfn{units}. This isn't strictly a new data type; it's simply an
4625application of algebraic expressions, where we use variables with
4626suggestive names like @samp{cm} and @samp{in} to represent units
4627like centimeters and inches.
4628
4629@smallexample
4630@group
46311: 2 in 1: 5.08 cm 1: 0.027778 fath 1: 0.0508 m
4632 . . . .
4633
4634 ' 2in @key{RET} u c cm @key{RET} u c fath @key{RET} u b
4635@end group
4636@end smallexample
4637
4638@noindent
4639We enter the quantity ``2 inches'' (actually an algebraic expression
4640which means two times the variable @samp{in}), then we convert it
4641first to centimeters, then to fathoms, then finally to ``base'' units,
4642which in this case means meters.
4643
4644@smallexample
4645@group
46461: 9 acre 1: 3 sqrt(acre) 1: 190.84 m 1: 190.84 m + 30 cm
4647 . . . .
4648
4649 ' 9 acre @key{RET} Q u s ' $+30 cm @key{RET}
4650
4651@end group
4652@end smallexample
4653@noindent
4654@smallexample
4655@group
46561: 191.14 m 1: 36536.3046 m^2 1: 365363046 cm^2
4657 . . .
4658
4659 u s 2 ^ u c cgs
4660@end group
4661@end smallexample
4662
4663@noindent
4664Since units expressions are really just formulas, taking the square
4665root of @samp{acre} is undefined. After all, @code{acre} might be an
4666algebraic variable that you will someday assign a value. We use the
4667``units-simplify'' command to simplify the expression with variables
4668being interpreted as unit names.
4669
4670In the final step, we have converted not to a particular unit, but to a
4671units system. The ``cgs'' system uses centimeters instead of meters
4672as its standard unit of length.
4673
4674There is a wide variety of units defined in the Calculator.
4675
4676@smallexample
4677@group
46781: 55 mph 1: 88.5139 kph 1: 88.5139 km / hr 1: 8.201407e-8 c
4679 . . . .
4680
4681 ' 55 mph @key{RET} u c kph @key{RET} u c km/hr @key{RET} u c c @key{RET}
4682@end group
4683@end smallexample
4684
4685@noindent
4686We express a speed first in miles per hour, then in kilometers per
4687hour, then again using a slightly more explicit notation, then
4688finally in terms of fractions of the speed of light.
4689
4690Temperature conversions are a bit more tricky. There are two ways to
4691interpret ``20 degrees Fahrenheit''---it could mean an actual
4692temperature, or it could mean a change in temperature. For normal
4693units there is no difference, but temperature units have an offset
4694as well as a scale factor and so there must be two explicit commands
4695for them.
4696
4697@smallexample
4698@group
46991: 20 degF 1: 11.1111 degC 1: -20:3 degC 1: -6.666 degC
4700 . . . .
4701
4702 ' 20 degF @key{RET} u c degC @key{RET} U u t degC @key{RET} c f
4703@end group
4704@end smallexample
4705
4706@noindent
4707First we convert a change of 20 degrees Fahrenheit into an equivalent
4708change in degrees Celsius (or Centigrade). Then, we convert the
4709absolute temperature 20 degrees Fahrenheit into Celsius. Since
4710this comes out as an exact fraction, we then convert to floating-point
4711for easier comparison with the other result.
4712
4713For simple unit conversions, you can put a plain number on the stack.
4714Then @kbd{u c} and @kbd{u t} will prompt for both old and new units.
4715When you use this method, you're responsible for remembering which
4716numbers are in which units:
4717
4718@smallexample
4719@group
47201: 55 1: 88.5139 1: 8.201407e-8
4721 . . .
4722
4723 55 u c mph @key{RET} kph @key{RET} u c km/hr @key{RET} c @key{RET}
4724@end group
4725@end smallexample
4726
4727To see a complete list of built-in units, type @kbd{u v}. Press
4728@w{@kbd{C-x * c}} again to re-enter the Calculator when you're done looking
4729at the units table.
4730
4731(@bullet{}) @strong{Exercise 13.} How many seconds are there really
4732in a year? @xref{Types Answer 13, 13}. (@bullet{})
4733
4734@cindex Speed of light
4735(@bullet{}) @strong{Exercise 14.} Supercomputer designs are limited by
4736the speed of light (and of electricity, which is nearly as fast).
4737Suppose a computer has a 4.1 ns (nanosecond) clock cycle, and its
4738cabinet is one meter across. Is speed of light going to be a
4739significant factor in its design? @xref{Types Answer 14, 14}. (@bullet{})
4740
4741(@bullet{}) @strong{Exercise 15.} Sam the Slug normally travels about
4742five yards in an hour. He has obtained a supply of Power Pills; each
4743Power Pill he eats doubles his speed. How many Power Pills can he
4744swallow and still travel legally on most US highways?
4745@xref{Types Answer 15, 15}. (@bullet{})
4746
4747@node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
4748@section Algebra and Calculus Tutorial
4749
4750@noindent
4751This section shows how to use Calc's algebra facilities to solve
4752equations, do simple calculus problems, and manipulate algebraic
4753formulas.
4754
4755@menu
4756* Basic Algebra Tutorial::
4757* Rewrites Tutorial::
4758@end menu
4759
4760@node Basic Algebra Tutorial, Rewrites Tutorial, Algebra Tutorial, Algebra Tutorial
4761@subsection Basic Algebra
4762
4763@noindent
4764If you enter a formula in Algebraic mode that refers to variables,
4765the formula itself is pushed onto the stack. You can manipulate
4766formulas as regular data objects.
4767
4768@smallexample
4769@group
47701: 2 x^2 - 6 1: 6 - 2 x^2 1: (6 - 2 x^2) (3 x^2 + y)
4771 . . .
4772
4773 ' 2x^2-6 @key{RET} n ' 3x^2+y @key{RET} *
4774@end group
4775@end smallexample
4776
4777(@bullet{}) @strong{Exercise 1.} Do @kbd{' x @key{RET} Q 2 ^} and
4778@kbd{' x @key{RET} 2 ^ Q} both wind up with the same result (@samp{x})?
4779Why or why not? @xref{Algebra Answer 1, 1}. (@bullet{})
4780
4781There are also commands for doing common algebraic operations on
4782formulas. Continuing with the formula from the last example,
4783
4784@smallexample
4785@group
47861: 18 x^2 + 6 y - 6 x^4 - 2 x^2 y 1: (18 - 2 y) x^2 - 6 x^4 + 6 y
4787 . .
4788
4789 a x a c x @key{RET}
4790@end group
4791@end smallexample
4792
4793@noindent
4794First we ``expand'' using the distributive law, then we ``collect''
4795terms involving like powers of @expr{x}.
4796
4797Let's find the value of this expression when @expr{x} is 2 and @expr{y}
4798is one-half.
4799
4800@smallexample
4801@group
48021: 17 x^2 - 6 x^4 + 3 1: -25
4803 . .
4804
4805 1:2 s l y @key{RET} 2 s l x @key{RET}
4806@end group
4807@end smallexample
4808
4809@noindent
4810The @kbd{s l} command means ``let''; it takes a number from the top of
4811the stack and temporarily assigns it as the value of the variable
4812you specify. It then evaluates (as if by the @kbd{=} key) the
4813next expression on the stack. After this command, the variable goes
4814back to its original value, if any.
4815
4816(An earlier exercise in this tutorial involved storing a value in the
4817variable @code{x}; if this value is still there, you will have to
4818unstore it with @kbd{s u x @key{RET}} before the above example will work
4819properly.)
4820
4821@cindex Maximum of a function using Calculus
4822Let's find the maximum value of our original expression when @expr{y}
4823is one-half and @expr{x} ranges over all possible values. We can
4824do this by taking the derivative with respect to @expr{x} and examining
4825values of @expr{x} for which the derivative is zero. If the second
4826derivative of the function at that value of @expr{x} is negative,
4827the function has a local maximum there.
4828
4829@smallexample
4830@group
48311: 17 x^2 - 6 x^4 + 3 1: 34 x - 24 x^3
4832 . .
4833
4834 U @key{DEL} s 1 a d x @key{RET} s 2
4835@end group
4836@end smallexample
4837
4838@noindent
4839Well, the derivative is clearly zero when @expr{x} is zero. To find
4840the other root(s), let's divide through by @expr{x} and then solve:
4841
4842@smallexample
4843@group
48441: (34 x - 24 x^3) / x 1: 34 x / x - 24 x^3 / x 1: 34 - 24 x^2
4845 . . .
4846
4847 ' x @key{RET} / a x a s
4848
4849@end group
4850@end smallexample
4851@noindent
4852@smallexample
4853@group
48541: 34 - 24 x^2 = 0 1: x = 1.19023
4855 . .
4856
4857 0 a = s 3 a S x @key{RET}
4858@end group
4859@end smallexample
4860
4861@noindent
4862Notice the use of @kbd{a s} to ``simplify'' the formula. When the
4863default algebraic simplifications don't do enough, you can use
4864@kbd{a s} to tell Calc to spend more time on the job.
4865
4866Now we compute the second derivative and plug in our values of @expr{x}:
4867
4868@smallexample
4869@group
48701: 1.19023 2: 1.19023 2: 1.19023
4871 . 1: 34 x - 24 x^3 1: 34 - 72 x^2
4872 . .
4873
4874 a . r 2 a d x @key{RET} s 4
4875@end group
4876@end smallexample
4877
4878@noindent
4879(The @kbd{a .} command extracts just the righthand side of an equation.
4880Another method would have been to use @kbd{v u} to unpack the equation
4881@w{@samp{x = 1.19}} to @samp{x} and @samp{1.19}, then use @kbd{M-- M-2 @key{DEL}}
4882to delete the @samp{x}.)
4883
4884@smallexample
4885@group
48862: 34 - 72 x^2 1: -68. 2: 34 - 72 x^2 1: 34
48871: 1.19023 . 1: 0 .
4888 . .
4889
4890 @key{TAB} s l x @key{RET} U @key{DEL} 0 s l x @key{RET}
4891@end group
4892@end smallexample
4893
4894@noindent
4895The first of these second derivatives is negative, so we know the function
4896has a maximum value at @expr{x = 1.19023}. (The function also has a
4897local @emph{minimum} at @expr{x = 0}.)
4898
4899When we solved for @expr{x}, we got only one value even though
4900@expr{34 - 24 x^2 = 0} is a quadratic equation that ought to have
4901two solutions. The reason is that @w{@kbd{a S}} normally returns a
4902single ``principal'' solution. If it needs to come up with an
4903arbitrary sign (as occurs in the quadratic formula) it picks @expr{+}.
4904If it needs an arbitrary integer, it picks zero. We can get a full
4905solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
4906
4907@smallexample
4908@group
49091: 34 - 24 x^2 = 0 1: x = 1.19023 s1 1: x = -1.19023
4910 . . .
4911
4912 r 3 H a S x @key{RET} s 5 1 n s l s1 @key{RET}
4913@end group
4914@end smallexample
4915
4916@noindent
4917Calc has invented the variable @samp{s1} to represent an unknown sign;
4918it is supposed to be either @mathit{+1} or @mathit{-1}. Here we have used
4919the ``let'' command to evaluate the expression when the sign is negative.
4920If we plugged this into our second derivative we would get the same,
4921negative, answer, so @expr{x = -1.19023} is also a maximum.
4922
4923To find the actual maximum value, we must plug our two values of @expr{x}
4924into the original formula.
4925
4926@smallexample
4927@group
49282: 17 x^2 - 6 x^4 + 3 1: 24.08333 s1^2 - 12.04166 s1^4 + 3
49291: x = 1.19023 s1 .
4930 .
4931
4932 r 1 r 5 s l @key{RET}
4933@end group
4934@end smallexample
4935
4936@noindent
4937(Here we see another way to use @kbd{s l}; if its input is an equation
4938with a variable on the lefthand side, then @kbd{s l} treats the equation
4939like an assignment to that variable if you don't give a variable name.)
4940
4941It's clear that this will have the same value for either sign of
4942@code{s1}, but let's work it out anyway, just for the exercise:
4943
4944@smallexample
4945@group
49462: [-1, 1] 1: [15.04166, 15.04166]
49471: 24.08333 s1^2 ... .
4948 .
4949
4950 [ 1 n , 1 ] @key{TAB} V M $ @key{RET}
4951@end group
4952@end smallexample
4953
4954@noindent
4955Here we have used a vector mapping operation to evaluate the function
4956at several values of @samp{s1} at once. @kbd{V M $} is like @kbd{V M '}
4957except that it takes the formula from the top of the stack. The
4958formula is interpreted as a function to apply across the vector at the
4959next-to-top stack level. Since a formula on the stack can't contain
4960@samp{$} signs, Calc assumes the variables in the formula stand for
4961different arguments. It prompts you for an @dfn{argument list}, giving
4962the list of all variables in the formula in alphabetical order as the
4963default list. In this case the default is @samp{(s1)}, which is just
4964what we want so we simply press @key{RET} at the prompt.
4965
4966If there had been several different values, we could have used
4967@w{@kbd{V R X}} to find the global maximum.
4968
4969Calc has a built-in @kbd{a P} command that solves an equation using
4970@w{@kbd{H a S}} and returns a vector of all the solutions. It simply
4971automates the job we just did by hand. Applied to our original
4972cubic polynomial, it would produce the vector of solutions
4973@expr{[1.19023, -1.19023, 0]}. (There is also an @kbd{a X} command
4974which finds a local maximum of a function. It uses a numerical search
4975method rather than examining the derivatives, and thus requires you
4976to provide some kind of initial guess to show it where to look.)
4977
4978(@bullet{}) @strong{Exercise 2.} Given a vector of the roots of a
4979polynomial (such as the output of an @kbd{a P} command), what
4980sequence of commands would you use to reconstruct the original
4981polynomial? (The answer will be unique to within a constant
4982multiple; choose the solution where the leading coefficient is one.)
4983@xref{Algebra Answer 2, 2}. (@bullet{})
4984
4985The @kbd{m s} command enables Symbolic mode, in which formulas
4986like @samp{sqrt(5)} that can't be evaluated exactly are left in
4987symbolic form rather than giving a floating-point approximate answer.
4988Fraction mode (@kbd{m f}) is also useful when doing algebra.
4989
4990@smallexample
4991@group
49922: 34 x - 24 x^3 2: 34 x - 24 x^3
49931: 34 x - 24 x^3 1: [sqrt(51) / 6, sqrt(51) / -6, 0]
4994 . .
4995
4996 r 2 @key{RET} m s m f a P x @key{RET}
4997@end group
4998@end smallexample
4999
5000One more mode that makes reading formulas easier is Big mode.
5001
5002@smallexample
5003@group
5004 3
50052: 34 x - 24 x
5006
5007 ____ ____
5008 V 51 V 51
50091: [-----, -----, 0]
5010 6 -6
5011
5012 .
5013
5014 d B
5015@end group
5016@end smallexample
5017
5018Here things like powers, square roots, and quotients and fractions
5019are displayed in a two-dimensional pictorial form. Calc has other
5020language modes as well, such as C mode, FORTRAN mode, @TeX{} mode
5021and La@TeX{} mode.
5022
5023@smallexample
5024@group
50252: 34*x - 24*pow(x, 3) 2: 34*x - 24*x**3
50261: @{sqrt(51) / 6, sqrt(51) / -6, 0@} 1: /sqrt(51) / 6, sqrt(51) / -6, 0/
5027 . .
5028
5029 d C d F
5030
5031@end group
5032@end smallexample
5033@noindent
5034@smallexample
5035@group
50363: 34 x - 24 x^3
50372: [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
50381: @{2 \over 3@} \sqrt@{5@}
5039 .
5040
5041 d T ' 2 \sqrt@{5@} \over 3 @key{RET}
5042@end group
5043@end smallexample
5044
5045@noindent
5046As you can see, language modes affect both entry and display of
5047formulas. They affect such things as the names used for built-in
5048functions, the set of arithmetic operators and their precedences,
5049and notations for vectors and matrices.
5050
5051Notice that @samp{sqrt(51)} may cause problems with older
5052implementations of C and FORTRAN, which would require something more
5053like @samp{sqrt(51.0)}. It is always wise to check over the formulas
5054produced by the various language modes to make sure they are fully
5055correct.
5056
5057Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes. (You
5058may prefer to remain in Big mode, but all the examples in the tutorial
5059are shown in normal mode.)
5060
5061@cindex Area under a curve
5062What is the area under the portion of this curve from @expr{x = 1} to @expr{2}?
5063This is simply the integral of the function:
5064
5065@smallexample
5066@group
50671: 17 x^2 - 6 x^4 + 3 1: 5.6666 x^3 - 1.2 x^5 + 3 x
5068 . .
5069
5070 r 1 a i x
5071@end group
5072@end smallexample
5073
5074@noindent
5075We want to evaluate this at our two values for @expr{x} and subtract.
5076One way to do it is again with vector mapping and reduction:
5077
5078@smallexample
5079@group
50802: [2, 1] 1: [12.93333, 7.46666] 1: 5.46666
50811: 5.6666 x^3 ... . .
5082
5083 [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
5084@end group
5085@end smallexample
5086
5087(@bullet{}) @strong{Exercise 3.} Find the integral from 1 to @expr{y}
5088of
5089@texline @math{x \sin \pi x}
5090@infoline @w{@expr{x sin(pi x)}}
5091(where the sine is calculated in radians). Find the values of the
5092integral for integers @expr{y} from 1 to 5. @xref{Algebra Answer 3,
50933}. (@bullet{})
5094
5095Calc's integrator can do many simple integrals symbolically, but many
5096others are beyond its capabilities. Suppose we wish to find the area
5097under the curve
5098@texline @math{\sin x \ln x}
5099@infoline @expr{sin(x) ln(x)}
5100over the same range of @expr{x}. If you entered this formula and typed
5101@kbd{a i x @key{RET}} (don't bother to try this), Calc would work for a
5102long time but would be unable to find a solution. In fact, there is no
5103closed-form solution to this integral. Now what do we do?
5104
5105@cindex Integration, numerical
5106@cindex Numerical integration
5107One approach would be to do the integral numerically. It is not hard
5108to do this by hand using vector mapping and reduction. It is rather
5109slow, though, since the sine and logarithm functions take a long time.
5110We can save some time by reducing the working precision.
5111
5112@smallexample
5113@group
51143: 10 1: [1, 1.1, 1.2, ... , 1.8, 1.9]
51152: 1 .
51161: 0.1
5117 .
5118
5119 10 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
5120@end group
5121@end smallexample
5122
5123@noindent
5124(Note that we have used the extended version of @kbd{v x}; we could
5125also have used plain @kbd{v x} as follows: @kbd{v x 10 @key{RET} 9 + .1 *}.)
5126
5127@smallexample
5128@group
51292: [1, 1.1, ... ] 1: [0., 0.084941, 0.16993, ... ]
51301: sin(x) ln(x) .
5131 .
5132
5133 ' sin(x) ln(x) @key{RET} s 1 m r p 5 @key{RET} V M $ @key{RET}
5134
5135@end group
5136@end smallexample
5137@noindent
5138@smallexample
5139@group
51401: 3.4195 0.34195
5141 . .
5142
5143 V R + 0.1 *
5144@end group
5145@end smallexample
5146
5147@noindent
5148(If you got wildly different results, did you remember to switch
5149to Radians mode?)
5150
5151Here we have divided the curve into ten segments of equal width;
5152approximating these segments as rectangular boxes (i.e., assuming
5153the curve is nearly flat at that resolution), we compute the areas
5154of the boxes (height times width), then sum the areas. (It is
5155faster to sum first, then multiply by the width, since the width
5156is the same for every box.)
5157
5158The true value of this integral turns out to be about 0.374, so
5159we're not doing too well. Let's try another approach.
5160
5161@smallexample
5162@group
51631: sin(x) ln(x) 1: 0.84147 x - 0.84147 + 0.11957 (x - 1)^2 - ...
5164 . .
5165
5166 r 1 a t x=1 @key{RET} 4 @key{RET}
5167@end group
5168@end smallexample
5169
5170@noindent
5171Here we have computed the Taylor series expansion of the function
5172about the point @expr{x=1}. We can now integrate this polynomial
5173approximation, since polynomials are easy to integrate.
5174
5175@smallexample
5176@group
51771: 0.42074 x^2 + ... 1: [-0.0446, -0.42073] 1: 0.3761
5178 . . .
5179
5180 a i x @key{RET} [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
5181@end group
5182@end smallexample
5183
5184@noindent
5185Better! By increasing the precision and/or asking for more terms
5186in the Taylor series, we can get a result as accurate as we like.
5187(Taylor series converge better away from singularities in the
5188function such as the one at @code{ln(0)}, so it would also help to
5189expand the series about the points @expr{x=2} or @expr{x=1.5} instead
5190of @expr{x=1}.)
5191
5192@cindex Simpson's rule
5193@cindex Integration by Simpson's rule
5194(@bullet{}) @strong{Exercise 4.} Our first method approximated the
5195curve by stairsteps of width 0.1; the total area was then the sum
5196of the areas of the rectangles under these stairsteps. Our second
5197method approximated the function by a polynomial, which turned out
5198to be a better approximation than stairsteps. A third method is
5199@dfn{Simpson's rule}, which is like the stairstep method except
5200that the steps are not required to be flat. Simpson's rule boils
5201down to the formula,
5202
5203@ifnottex
5204@example
5205(h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
5206 + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
5207@end example
5208@end ifnottex
5209@tex
5210\turnoffactive
5211\beforedisplay
5212$$ \displaylines{
5213 \qquad {h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
5214 \hfill \cr \hfill {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h)) \qquad
5215} $$
5216\afterdisplay
5217@end tex
5218
5219@noindent
5220where @expr{n} (which must be even) is the number of slices and @expr{h}
5221is the width of each slice. These are 10 and 0.1 in our example.
5222For reference, here is the corresponding formula for the stairstep
5223method:
5224
5225@ifnottex
5226@example
5227h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
5228 + f(a+(n-2)*h) + f(a+(n-1)*h))
5229@end example
5230@end ifnottex
5231@tex
5232\turnoffactive
5233\beforedisplay
5234$$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
5235 + f(a+(n-2)h) + f(a+(n-1)h)) $$
5236\afterdisplay
5237@end tex
5238
5239Compute the integral from 1 to 2 of
5240@texline @math{\sin x \ln x}
5241@infoline @expr{sin(x) ln(x)}
5242using Simpson's rule with 10 slices.
5243@xref{Algebra Answer 4, 4}. (@bullet{})
5244
5245Calc has a built-in @kbd{a I} command for doing numerical integration.
5246It uses @dfn{Romberg's method}, which is a more sophisticated cousin
5247of Simpson's rule. In particular, it knows how to keep refining the
5248result until the current precision is satisfied.
5249
5250@c [fix-ref Selecting Sub-Formulas]
5251Aside from the commands we've seen so far, Calc also provides a
5252large set of commands for operating on parts of formulas. You
5253indicate the desired sub-formula by placing the cursor on any part
5254of the formula before giving a @dfn{selection} command. Selections won't
5255be covered in the tutorial; @pxref{Selecting Subformulas}, for
5256details and examples.
5257
5258@c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
5259@c to 2^((n-1)*(r-1)).
5260
5261@node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
5262@subsection Rewrite Rules
5263
5264@noindent
5265No matter how many built-in commands Calc provided for doing algebra,
5266there would always be something you wanted to do that Calc didn't have
5267in its repertoire. So Calc also provides a @dfn{rewrite rule} system
5268that you can use to define your own algebraic manipulations.
5269
5270Suppose we want to simplify this trigonometric formula:
5271
5272@smallexample
5273@group
52741: 1 / cos(x) - sin(x) tan(x)
5275 .
5276
5277 ' 1/cos(x) - sin(x) tan(x) @key{RET} s 1
5278@end group
5279@end smallexample
5280
5281@noindent
5282If we were simplifying this by hand, we'd probably replace the
5283@samp{tan} with a @samp{sin/cos} first, then combine over a common
5284denominator. There is no Calc command to do the former; the @kbd{a n}
5285algebra command will do the latter but we'll do both with rewrite
5286rules just for practice.
5287
5288Rewrite rules are written with the @samp{:=} symbol.
5289
5290@smallexample
5291@group
52921: 1 / cos(x) - sin(x)^2 / cos(x)
5293 .
5294
5295 a r tan(a) := sin(a)/cos(a) @key{RET}
5296@end group
5297@end smallexample
5298
5299@noindent
5300(The ``assignment operator'' @samp{:=} has several uses in Calc. All
5301by itself the formula @samp{tan(a) := sin(a)/cos(a)} doesn't do anything,
5302but when it is given to the @kbd{a r} command, that command interprets
5303it as a rewrite rule.)
5304
5305The lefthand side, @samp{tan(a)}, is called the @dfn{pattern} of the
5306rewrite rule. Calc searches the formula on the stack for parts that
5307match the pattern. Variables in a rewrite pattern are called
5308@dfn{meta-variables}, and when matching the pattern each meta-variable
5309can match any sub-formula. Here, the meta-variable @samp{a} matched
5310the actual variable @samp{x}.
5311
5312When the pattern part of a rewrite rule matches a part of the formula,
5313that part is replaced by the righthand side with all the meta-variables
5314substituted with the things they matched. So the result is
5315@samp{sin(x) / cos(x)}. Calc's normal algebraic simplifications then
5316mix this in with the rest of the original formula.
5317
5318To merge over a common denominator, we can use another simple rule:
5319
5320@smallexample
5321@group
53221: (1 - sin(x)^2) / cos(x)
5323 .
5324
5325 a r a/x + b/x := (a+b)/x @key{RET}
5326@end group
5327@end smallexample
5328
5329This rule points out several interesting features of rewrite patterns.
5330First, if a meta-variable appears several times in a pattern, it must
5331match the same thing everywhere. This rule detects common denominators
5332because the same meta-variable @samp{x} is used in both of the
5333denominators.
5334
5335Second, meta-variable names are independent from variables in the
5336target formula. Notice that the meta-variable @samp{x} here matches
5337the subformula @samp{cos(x)}; Calc never confuses the two meanings of
5338@samp{x}.
5339
5340And third, rewrite patterns know a little bit about the algebraic
5341properties of formulas. The pattern called for a sum of two quotients;
5342Calc was able to match a difference of two quotients by matching
5343@samp{a = 1}, @samp{b = -sin(x)^2}, and @samp{x = cos(x)}.
5344
5345@c [fix-ref Algebraic Properties of Rewrite Rules]
5346We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
5347the rule. It would have worked just the same in all cases. (If we
5348really wanted the rule to apply only to @samp{+} or only to @samp{-},
5349we could have used the @code{plain} symbol. @xref{Algebraic Properties
5350of Rewrite Rules}, for some examples of this.)
5351
5352One more rewrite will complete the job. We want to use the identity
5353@samp{sin(x)^2 + cos(x)^2 = 1}, but of course we must first rearrange
5354the identity in a way that matches our formula. The obvious rule
5355would be @samp{@w{1 - sin(x)^2} := cos(x)^2}, but a little thought shows
5356that the rule @samp{sin(x)^2 := 1 - cos(x)^2} will also work. The
5357latter rule has a more general pattern so it will work in many other
5358situations, too.
5359
5360@smallexample
5361@group
53621: (1 + cos(x)^2 - 1) / cos(x) 1: cos(x)
5363 . .
5364
5365 a r sin(x)^2 := 1 - cos(x)^2 @key{RET} a s
5366@end group
5367@end smallexample
5368
5369You may ask, what's the point of using the most general rule if you
5370have to type it in every time anyway? The answer is that Calc allows
5371you to store a rewrite rule in a variable, then give the variable
5372name in the @kbd{a r} command. In fact, this is the preferred way to
5373use rewrites. For one, if you need a rule once you'll most likely
5374need it again later. Also, if the rule doesn't work quite right you
5375can simply Undo, edit the variable, and run the rule again without
5376having to retype it.
5377
5378@smallexample
5379@group
5380' tan(x) := sin(x)/cos(x) @key{RET} s t tsc @key{RET}
5381' a/x + b/x := (a+b)/x @key{RET} s t merge @key{RET}
5382' sin(x)^2 := 1 - cos(x)^2 @key{RET} s t sinsqr @key{RET}
5383
53841: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
5385 . .
5386
5387 r 1 a r tsc @key{RET} a r merge @key{RET} a r sinsqr @key{RET} a s
5388@end group
5389@end smallexample
5390
5391To edit a variable, type @kbd{s e} and the variable name, use regular
5392Emacs editing commands as necessary, then type @kbd{C-c C-c} to store
5393the edited value back into the variable.
5394You can also use @w{@kbd{s e}} to create a new variable if you wish.
5395
5396Notice that the first time you use each rule, Calc puts up a ``compiling''
5397message briefly. The pattern matcher converts rules into a special
5398optimized pattern-matching language rather than using them directly.
5399This allows @kbd{a r} to apply even rather complicated rules very
5400efficiently. If the rule is stored in a variable, Calc compiles it
5401only once and stores the compiled form along with the variable. That's
5402another good reason to store your rules in variables rather than
5403entering them on the fly.
5404
5405(@bullet{}) @strong{Exercise 1.} Type @kbd{m s} to get Symbolic
5406mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
5407Using a rewrite rule, simplify this formula by multiplying the top and
5408bottom by the conjugate @w{@samp{1 - sqrt(2)}}. The result will have
5409to be expanded by the distributive law; do this with another
5410rewrite. @xref{Rewrites Answer 1, 1}. (@bullet{})
5411
5412The @kbd{a r} command can also accept a vector of rewrite rules, or
5413a variable containing a vector of rules.
5414
5415@smallexample
5416@group
54171: [tsc, merge, sinsqr] 1: [tan(x) := sin(x) / cos(x), ... ]
5418 . .
5419
5420 ' [tsc,merge,sinsqr] @key{RET} =
5421
5422@end group
5423@end smallexample
5424@noindent
5425@smallexample
5426@group
54271: 1 / cos(x) - sin(x) tan(x) 1: cos(x)
5428 . .
5429
5430 s t trig @key{RET} r 1 a r trig @key{RET} a s
5431@end group
5432@end smallexample
5433
5434@c [fix-ref Nested Formulas with Rewrite Rules]
5435Calc tries all the rules you give against all parts of the formula,
5436repeating until no further change is possible. (The exact order in
5437which things are tried is rather complex, but for simple rules like
5438the ones we've used here the order doesn't really matter.
5439@xref{Nested Formulas with Rewrite Rules}.)
5440
5441Calc actually repeats only up to 100 times, just in case your rule set
5442has gotten into an infinite loop. You can give a numeric prefix argument
5443to @kbd{a r} to specify any limit. In particular, @kbd{M-1 a r} does
5444only one rewrite at a time.
5445
5446@smallexample
5447@group
54481: 1 / cos(x) - sin(x)^2 / cos(x) 1: (1 - sin(x)^2) / cos(x)
5449 . .
5450
5451 r 1 M-1 a r trig @key{RET} M-1 a r trig @key{RET}
5452@end group
5453@end smallexample
5454
5455You can type @kbd{M-0 a r} if you want no limit at all on the number
5456of rewrites that occur.
5457
5458Rewrite rules can also be @dfn{conditional}. Simply follow the rule
5459with a @samp{::} symbol and the desired condition. For example,
5460
5461@smallexample
5462@group
54631: exp(2 pi i) + exp(3 pi i) + exp(4 pi i)
5464 .
5465
5466 ' exp(2 pi i) + exp(3 pi i) + exp(4 pi i) @key{RET}
5467
5468@end group
5469@end smallexample
5470@noindent
5471@smallexample
5472@group
54731: 1 + exp(3 pi i) + 1
5474 .
5475
5476 a r exp(k pi i) := 1 :: k % 2 = 0 @key{RET}
5477@end group
5478@end smallexample
5479
5480@noindent
5481(Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
5482which will be zero only when @samp{k} is an even integer.)
5483
5484An interesting point is that the variables @samp{pi} and @samp{i}
5485were matched literally rather than acting as meta-variables.
5486This is because they are special-constant variables. The special
5487constants @samp{e}, @samp{phi}, and so on also match literally.
5488A common error with rewrite
5489rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
5490to match any @samp{f} with five arguments but in fact matching
5491only when the fifth argument is literally @samp{e}!
5492
5493@cindex Fibonacci numbers
5494@ignore
5495@starindex
5496@end ignore
5497@tindex fib
5498Rewrite rules provide an interesting way to define your own functions.
5499Suppose we want to define @samp{fib(n)} to produce the @var{n}th
5500Fibonacci number. The first two Fibonacci numbers are each 1;
5501later numbers are formed by summing the two preceding numbers in
5502the sequence. This is easy to express in a set of three rules:
5503
5504@smallexample
5505@group
5506' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] @key{RET} s t fib
5507
55081: fib(7) 1: 13
5509 . .
5510
5511 ' fib(7) @key{RET} a r fib @key{RET}
5512@end group
5513@end smallexample
5514
5515One thing that is guaranteed about the order that rewrites are tried
5516is that, for any given subformula, earlier rules in the rule set will
5517be tried for that subformula before later ones. So even though the
5518first and third rules both match @samp{fib(1)}, we know the first will
5519be used preferentially.
5520
5521This rule set has one dangerous bug: Suppose we apply it to the
5522formula @samp{fib(x)}? (Don't actually try this.) The third rule
5523will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
5524Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
5525fib(x-4)}, and so on, expanding forever. What we really want is to apply
5526the third rule only when @samp{n} is an integer greater than two. Type
5527@w{@kbd{s e fib @key{RET}}}, then edit the third rule to:
5528
5529@smallexample
5530fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
5531@end smallexample
5532
5533@noindent
5534Now:
5535
5536@smallexample
5537@group
55381: fib(6) + fib(x) + fib(0) 1: 8 + fib(x) + fib(0)
5539 . .
5540
5541 ' fib(6)+fib(x)+fib(0) @key{RET} a r fib @key{RET}
5542@end group
5543@end smallexample
5544
5545@noindent
5546We've created a new function, @code{fib}, and a new command,
5547@w{@kbd{a r fib @key{RET}}}, which means ``evaluate all @code{fib} calls in
5548this formula.'' To make things easier still, we can tell Calc to
5549apply these rules automatically by storing them in the special
5550variable @code{EvalRules}.
5551
5552@smallexample
5553@group
55541: [fib(1) := ...] . 1: [8, 13]
5555 . .
5556
5557 s r fib @key{RET} s t EvalRules @key{RET} ' [fib(6), fib(7)] @key{RET}
5558@end group
5559@end smallexample
5560
5561It turns out that this rule set has the problem that it does far
5562more work than it needs to when @samp{n} is large. Consider the
5563first few steps of the computation of @samp{fib(6)}:
5564
5565@smallexample
5566@group
5567fib(6) =
5568fib(5) + fib(4) =
5569fib(4) + fib(3) + fib(3) + fib(2) =
5570fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
5571@end group
5572@end smallexample
5573
5574@noindent
5575Note that @samp{fib(3)} appears three times here. Unless Calc's
5576algebraic simplifier notices the multiple @samp{fib(3)}s and combines
5577them (and, as it happens, it doesn't), this rule set does lots of
5578needless recomputation. To cure the problem, type @code{s e EvalRules}
5579to edit the rules (or just @kbd{s E}, a shorthand command for editing
5580@code{EvalRules}) and add another condition:
5581
5582@smallexample
5583fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
5584@end smallexample
5585
5586@noindent
5587If a @samp{:: remember} condition appears anywhere in a rule, then if
5588that rule succeeds Calc will add another rule that describes that match
5589to the front of the rule set. (Remembering works in any rule set, but
5590for technical reasons it is most effective in @code{EvalRules}.) For
5591example, if the rule rewrites @samp{fib(7)} to something that evaluates
5592to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
5593
5594Type @kbd{' fib(8) @key{RET}} to compute the eighth Fibonacci number, then
5595type @kbd{s E} again to see what has happened to the rule set.
5596
5597With the @code{remember} feature, our rule set can now compute
5598@samp{fib(@var{n})} in just @var{n} steps. In the process it builds
5599up a table of all Fibonacci numbers up to @var{n}. After we have
5600computed the result for a particular @var{n}, we can get it back
5601(and the results for all smaller @var{n}) later in just one step.
5602
5603All Calc operations will run somewhat slower whenever @code{EvalRules}
5604contains any rules. You should type @kbd{s u EvalRules @key{RET}} now to
5605un-store the variable.
5606
5607(@bullet{}) @strong{Exercise 2.} Sometimes it is possible to reformulate
5608a problem to reduce the amount of recursion necessary to solve it.
5609Create a rule that, in about @var{n} simple steps and without recourse
5610to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
5611@samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
5612@var{n}th and @var{n+1}st Fibonacci numbers, respectively. This rule is
5613rather clunky to use, so add a couple more rules to make the ``user
5614interface'' the same as for our first version: enter @samp{fib(@var{n})},
5615get back a plain number. @xref{Rewrites Answer 2, 2}. (@bullet{})
5616
5617There are many more things that rewrites can do. For example, there
5618are @samp{&&&} and @samp{|||} pattern operators that create ``and''
5619and ``or'' combinations of rules. As one really simple example, we
5620could combine our first two Fibonacci rules thusly:
5621
5622@example
5623[fib(1 ||| 2) := 1, fib(n) := ... ]
5624@end example
5625
5626@noindent
5627That means ``@code{fib} of something matching either 1 or 2 rewrites
5628to 1.''
5629
5630You can also make meta-variables optional by enclosing them in @code{opt}.
5631For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
5632@samp{2 + x} or @samp{3 x} or @samp{x}. The pattern @samp{opt(a) + opt(b) x}
5633matches all of these forms, filling in a default of zero for @samp{a}
5634and one for @samp{b}.
5635
5636(@bullet{}) @strong{Exercise 3.} Your friend Joe had @samp{2 + 3 x}
5637on the stack and tried to use the rule
5638@samp{opt(a) + opt(b) x := f(a, b, x)}. What happened?
5639@xref{Rewrites Answer 3, 3}. (@bullet{})
5640
5641(@bullet{}) @strong{Exercise 4.} Starting with a positive integer @expr{a},
5642divide @expr{a} by two if it is even, otherwise compute @expr{3 a + 1}.
5643Now repeat this step over and over. A famous unproved conjecture
5644is that for any starting @expr{a}, the sequence always eventually
5645reaches 1. Given the formula @samp{seq(@var{a}, 0)}, write a set of
5646rules that convert this into @samp{seq(1, @var{n})} where @var{n}
5647is the number of steps it took the sequence to reach the value 1.
5648Now enhance the rules to accept @samp{seq(@var{a})} as a starting
5649configuration, and to stop with just the number @var{n} by itself.
5650Now make the result be a vector of values in the sequence, from @var{a}
5651to 1. (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
5652and @var{y}.) For example, rewriting @samp{seq(6)} should yield the
5653vector @expr{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
5654@xref{Rewrites Answer 4, 4}. (@bullet{})
5655
5656(@bullet{}) @strong{Exercise 5.} Define, using rewrite rules, a function
5657@samp{nterms(@var{x})} that returns the number of terms in the sum
5658@var{x}, or 1 if @var{x} is not a sum. (A @dfn{sum} for our purposes
5659is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
5660so that @expr{2 - 3 (x + y) + x y} is a sum of three terms.)
5661@xref{Rewrites Answer 5, 5}. (@bullet{})
5662
5663(@bullet{}) @strong{Exercise 6.} A Taylor series for a function is an
5664infinite series that exactly equals the value of that function at
5665values of @expr{x} near zero.
5666
5667@ifnottex
5668@example
5669cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
5670@end example
5671@end ifnottex
5672@tex
5673\turnoffactive
5674\beforedisplay
5675$$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
5676\afterdisplay
5677@end tex
5678
5679The @kbd{a t} command produces a @dfn{truncated Taylor series} which
5680is obtained by dropping all the terms higher than, say, @expr{x^2}.
5681Calc represents the truncated Taylor series as a polynomial in @expr{x}.
5682Mathematicians often write a truncated series using a ``big-O'' notation
5683that records what was the lowest term that was truncated.
5684
5685@ifnottex
5686@example
5687cos(x) = 1 - x^2 / 2! + O(x^3)
5688@end example
5689@end ifnottex
5690@tex
5691\turnoffactive
5692\beforedisplay
5693$$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
5694\afterdisplay
5695@end tex
5696
5697@noindent
5698The meaning of @expr{O(x^3)} is ``a quantity which is negligibly small
5699if @expr{x^3} is considered negligibly small as @expr{x} goes to zero.''
5700
5701The exercise is to create rewrite rules that simplify sums and products of
5702power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
5703For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
5704on the stack, we want to be able to type @kbd{*} and get the result
5705@samp{x - 2:3 x^3 + O(x^4)}. Don't worry if the terms of the sum are
5706rearranged or if @kbd{a s} needs to be typed after rewriting. (This one
5707is rather tricky; the solution at the end of this chapter uses 6 rewrite
5708rules. Hint: The @samp{constant(x)} condition tests whether @samp{x} is
5709a number.) @xref{Rewrites Answer 6, 6}. (@bullet{})
5710
5711Just for kicks, try adding the rule @code{2+3 := 6} to @code{EvalRules}.
5712What happens? (Be sure to remove this rule afterward, or you might get
5713a nasty surprise when you use Calc to balance your checkbook!)
5714
5715@xref{Rewrite Rules}, for the whole story on rewrite rules.
5716
5717@node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
5718@section Programming Tutorial
5719
5720@noindent
5721The Calculator is written entirely in Emacs Lisp, a highly extensible
5722language. If you know Lisp, you can program the Calculator to do
5723anything you like. Rewrite rules also work as a powerful programming
5724system. But Lisp and rewrite rules take a while to master, and often
5725all you want to do is define a new function or repeat a command a few
5726times. Calc has features that allow you to do these things easily.
5727
5728One very limited form of programming is defining your own functions.
5729Calc's @kbd{Z F} command allows you to define a function name and
5730key sequence to correspond to any formula. Programming commands use
5731the shift-@kbd{Z} prefix; the user commands they create use the lower
5732case @kbd{z} prefix.
5733
5734@smallexample
5735@group
57361: 1 + x + x^2 / 2 + x^3 / 6 1: 1 + x + x^2 / 2 + x^3 / 6
5737 . .
5738
5739 ' 1 + x + x^2/2! + x^3/3! @key{RET} Z F e myexp @key{RET} @key{RET} @key{RET} y
5740@end group
5741@end smallexample
5742
5743This polynomial is a Taylor series approximation to @samp{exp(x)}.
5744The @kbd{Z F} command asks a number of questions. The above answers
5745say that the key sequence for our function should be @kbd{z e}; the
5746@kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
5747function in algebraic formulas should also be @code{myexp}; the
5748default argument list @samp{(x)} is acceptable; and finally @kbd{y}
5749answers the question ``leave it in symbolic form for non-constant
5750arguments?''
5751
5752@smallexample
5753@group
57541: 1.3495 2: 1.3495 3: 1.3495
5755 . 1: 1.34986 2: 1.34986
5756 . 1: myexp(a + 1)
5757 .
5758
5759 .3 z e .3 E ' a+1 @key{RET} z e
5760@end group
5761@end smallexample
5762
5763@noindent
5764First we call our new @code{exp} approximation with 0.3 as an
5765argument, and compare it with the true @code{exp} function. Then
5766we note that, as requested, if we try to give @kbd{z e} an
5767argument that isn't a plain number, it leaves the @code{myexp}
5768function call in symbolic form. If we had answered @kbd{n} to the
5769final question, @samp{myexp(a + 1)} would have evaluated by plugging
5770in @samp{a + 1} for @samp{x} in the defining formula.
5771
5772@cindex Sine integral Si(x)
5773@ignore
5774@starindex
5775@end ignore
5776@tindex Si
5777(@bullet{}) @strong{Exercise 1.} The ``sine integral'' function
5778@texline @math{{\rm Si}(x)}
5779@infoline @expr{Si(x)}
5780is defined as the integral of @samp{sin(t)/t} for
5781@expr{t = 0} to @expr{x} in radians. (It was invented because this
5782integral has no solution in terms of basic functions; if you give it
5783to Calc's @kbd{a i} command, it will ponder it for a long time and then
5784give up.) We can use the numerical integration command, however,
5785which in algebraic notation is written like @samp{ninteg(f(t), t, 0, x)}
5786with any integrand @samp{f(t)}. Define a @kbd{z s} command and
5787@code{Si} function that implement this. You will need to edit the
5788default argument list a bit. As a test, @samp{Si(1)} should return
57890.946083. (If you don't get this answer, you might want to check that
5790Calc is in Radians mode. Also, @code{ninteg} will run a lot faster if
5791you reduce the precision to, say, six digits beforehand.)
5792@xref{Programming Answer 1, 1}. (@bullet{})
5793
5794The simplest way to do real ``programming'' of Emacs is to define a
5795@dfn{keyboard macro}. A keyboard macro is simply a sequence of
5796keystrokes which Emacs has stored away and can play back on demand.
5797For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
5798you may wish to program a keyboard macro to type this for you.
5799
5800@smallexample
5801@group
58021: y = sqrt(x) 1: x = y^2
5803 . .
5804
5805 ' y=sqrt(x) @key{RET} C-x ( H a S x @key{RET} C-x )
5806
58071: y = cos(x) 1: x = s1 arccos(y) + 2 pi n1
5808 . .
5809
5810 ' y=cos(x) @key{RET} X
5811@end group
5812@end smallexample
5813
5814@noindent
5815When you type @kbd{C-x (}, Emacs begins recording. But it is also
5816still ready to execute your keystrokes, so you're really ``training''
5817Emacs by walking it through the procedure once. When you type
5818@w{@kbd{C-x )}}, the macro is recorded. You can now type @kbd{X} to
5819re-execute the same keystrokes.
5820
5821You can give a name to your macro by typing @kbd{Z K}.
5822
5823@smallexample
5824@group
58251: . 1: y = x^4 1: x = s2 sqrt(s1 sqrt(y))
5826 . .
5827
5828 Z K x @key{RET} ' y=x^4 @key{RET} z x
5829@end group
5830@end smallexample
5831
5832@noindent
5833Notice that we use shift-@kbd{Z} to define the command, and lower-case
5834@kbd{z} to call it up.
5835
5836Keyboard macros can call other macros.
5837
5838@smallexample
5839@group
58401: abs(x) 1: x = s1 y 1: 2 / x 1: x = 2 / y
5841 . . . .
5842
5843 ' abs(x) @key{RET} C-x ( ' y @key{RET} a = z x C-x ) ' 2/x @key{RET} X
5844@end group
5845@end smallexample
5846
5847(@bullet{}) @strong{Exercise 2.} Define a keyboard macro to negate
5848the item in level 3 of the stack, without disturbing the rest of
5849the stack. @xref{Programming Answer 2, 2}. (@bullet{})
5850
5851(@bullet{}) @strong{Exercise 3.} Define keyboard macros to compute
5852the following functions:
5853
5854@enumerate
5855@item
5856Compute
5857@texline @math{\displaystyle{\sin x \over x}},
5858@infoline @expr{sin(x) / x},
5859where @expr{x} is the number on the top of the stack.
5860
5861@item
5862Compute the base-@expr{b} logarithm, just like the @kbd{B} key except
5863the arguments are taken in the opposite order.
5864
5865@item
5866Produce a vector of integers from 1 to the integer on the top of
5867the stack.
5868@end enumerate
5869@noindent
5870@xref{Programming Answer 3, 3}. (@bullet{})
5871
5872(@bullet{}) @strong{Exercise 4.} Define a keyboard macro to compute
5873the average (mean) value of a list of numbers.
5874@xref{Programming Answer 4, 4}. (@bullet{})
5875
5876In many programs, some of the steps must execute several times.
5877Calc has @dfn{looping} commands that allow this. Loops are useful
5878inside keyboard macros, but actually work at any time.
5879
5880@smallexample
5881@group
58821: x^6 2: x^6 1: 360 x^2
5883 . 1: 4 .
5884 .
5885
5886 ' x^6 @key{RET} 4 Z < a d x @key{RET} Z >
5887@end group
5888@end smallexample
5889
5890@noindent
5891Here we have computed the fourth derivative of @expr{x^6} by
5892enclosing a derivative command in a ``repeat loop'' structure.
5893This structure pops a repeat count from the stack, then
5894executes the body of the loop that many times.
5895
5896If you make a mistake while entering the body of the loop,
5897type @w{@kbd{Z C-g}} to cancel the loop command.
5898
5899@cindex Fibonacci numbers
5900Here's another example:
5901
5902@smallexample
5903@group
59043: 1 2: 10946
59052: 1 1: 17711
59061: 20 .
5907 .
5908
59091 @key{RET} @key{RET} 20 Z < @key{TAB} C-j + Z >
5910@end group
5911@end smallexample
5912
5913@noindent
5914The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
5915numbers, respectively. (To see what's going on, try a few repetitions
5916of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
5917key if you have one, makes a copy of the number in level 2.)
5918
5919@cindex Golden ratio
5920@cindex Phi, golden ratio
5921A fascinating property of the Fibonacci numbers is that the @expr{n}th
5922Fibonacci number can be found directly by computing
5923@texline @math{\phi^n / \sqrt{5}}
5924@infoline @expr{phi^n / sqrt(5)}
5925and then rounding to the nearest integer, where
5926@texline @math{\phi} (``phi''),
5927@infoline @expr{phi},
5928the ``golden ratio,'' is
5929@texline @math{(1 + \sqrt{5}) / 2}.
5930@infoline @expr{(1 + sqrt(5)) / 2}.
5931(For convenience, this constant is available from the @code{phi}
5932variable, or the @kbd{I H P} command.)
5933
5934@smallexample
5935@group
59361: 1.61803 1: 24476.0000409 1: 10945.9999817 1: 10946
5937 . . . .
5938
5939 I H P 21 ^ 5 Q / R
5940@end group
5941@end smallexample
5942
5943@cindex Continued fractions
5944(@bullet{}) @strong{Exercise 5.} The @dfn{continued fraction}
5945representation of
5946@texline @math{\phi}
5947@infoline @expr{phi}
5948is
5949@texline @math{1 + 1/(1 + 1/(1 + 1/( \ldots )))}.
5950@infoline @expr{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
5951We can compute an approximate value by carrying this however far
5952and then replacing the innermost
5953@texline @math{1/( \ldots )}
5954@infoline @expr{1/( ...@: )}
5955by 1. Approximate
5956@texline @math{\phi}
5957@infoline @expr{phi}
5958using a twenty-term continued fraction.
5959@xref{Programming Answer 5, 5}. (@bullet{})
5960
5961(@bullet{}) @strong{Exercise 6.} Linear recurrences like the one for
5962Fibonacci numbers can be expressed in terms of matrices. Given a
5963vector @w{@expr{[a, b]}} determine a matrix which, when multiplied by this
5964vector, produces the vector @expr{[b, c]}, where @expr{a}, @expr{b} and
5965@expr{c} are three successive Fibonacci numbers. Now write a program
5966that, given an integer @expr{n}, computes the @expr{n}th Fibonacci number
5967using matrix arithmetic. @xref{Programming Answer 6, 6}. (@bullet{})
5968
5969@cindex Harmonic numbers
5970A more sophisticated kind of loop is the @dfn{for} loop. Suppose
5971we wish to compute the 20th ``harmonic'' number, which is equal to
5972the sum of the reciprocals of the integers from 1 to 20.
5973
5974@smallexample
5975@group
59763: 0 1: 3.597739
59772: 1 .
59781: 20
5979 .
5980
59810 @key{RET} 1 @key{RET} 20 Z ( & + 1 Z )
5982@end group
5983@end smallexample
5984
5985@noindent
5986The ``for'' loop pops two numbers, the lower and upper limits, then
5987repeats the body of the loop as an internal counter increases from
5988the lower limit to the upper one. Just before executing the loop
5989body, it pushes the current loop counter. When the loop body
5990finishes, it pops the ``step,'' i.e., the amount by which to
5991increment the loop counter. As you can see, our loop always
5992uses a step of one.
5993
5994This harmonic number function uses the stack to hold the running
5995total as well as for the various loop housekeeping functions. If
5996you find this disorienting, you can sum in a variable instead:
5997
5998@smallexample
5999@group
60001: 0 2: 1 . 1: 3.597739
6001 . 1: 20 .
6002 .
6003
6004 0 t 7 1 @key{RET} 20 Z ( & s + 7 1 Z ) r 7
6005@end group
6006@end smallexample
6007
6008@noindent
6009The @kbd{s +} command adds the top-of-stack into the value in a
6010variable (and removes that value from the stack).
6011
6012It's worth noting that many jobs that call for a ``for'' loop can
6013also be done more easily by Calc's high-level operations. Two
6014other ways to compute harmonic numbers are to use vector mapping
6015and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
6016or to use the summation command @kbd{a +}. Both of these are
6017probably easier than using loops. However, there are some
6018situations where loops really are the way to go:
6019
6020(@bullet{}) @strong{Exercise 7.} Use a ``for'' loop to find the first
6021harmonic number which is greater than 4.0.
6022@xref{Programming Answer 7, 7}. (@bullet{})
6023
6024Of course, if we're going to be using variables in our programs,
6025we have to worry about the programs clobbering values that the
6026caller was keeping in those same variables. This is easy to
6027fix, though:
6028
6029@smallexample
6030@group
6031 . 1: 0.6667 1: 0.6667 3: 0.6667
6032 . . 2: 3.597739
6033 1: 0.6667
6034 .
6035
6036 Z ` p 4 @key{RET} 2 @key{RET} 3 / s 7 s s a @key{RET} Z ' r 7 s r a @key{RET}
6037@end group
6038@end smallexample
6039
6040@noindent
6041When we type @kbd{Z `} (that's a back-quote character), Calc saves
6042its mode settings and the contents of the ten ``quick variables''
6043for later reference. When we type @kbd{Z '} (that's an apostrophe
6044now), Calc restores those saved values. Thus the @kbd{p 4} and
6045@kbd{s 7} commands have no effect outside this sequence. Wrapping
6046this around the body of a keyboard macro ensures that it doesn't
6047interfere with what the user of the macro was doing. Notice that
6048the contents of the stack, and the values of named variables,
6049survive past the @kbd{Z '} command.
6050
6051@cindex Bernoulli numbers, approximate
6052The @dfn{Bernoulli numbers} are a sequence with the interesting
6053property that all of the odd Bernoulli numbers are zero, and the
6054even ones, while difficult to compute, can be roughly approximated
6055by the formula
6056@texline @math{\displaystyle{2 n! \over (2 \pi)^n}}.
6057@infoline @expr{2 n!@: / (2 pi)^n}.
6058Let's write a keyboard macro to compute (approximate) Bernoulli numbers.
6059(Calc has a command, @kbd{k b}, to compute exact Bernoulli numbers, but
6060this command is very slow for large @expr{n} since the higher Bernoulli
6061numbers are very large fractions.)
6062
6063@smallexample
6064@group
60651: 10 1: 0.0756823
6066 . .
6067
6068 10 C-x ( @key{RET} 2 % Z [ @key{DEL} 0 Z : ' 2 $! / (2 pi)^$ @key{RET} = Z ] C-x )
6069@end group
6070@end smallexample
6071
6072@noindent
6073You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
6074@kbd{Z ]} as ``end-if.'' There is no need for an explicit ``if''
6075command. For the purposes of @w{@kbd{Z [}}, the condition is ``true''
6076if the value it pops from the stack is a nonzero number, or ``false''
6077if it pops zero or something that is not a number (like a formula).
6078Here we take our integer argument modulo 2; this will be nonzero
6079if we're asking for an odd Bernoulli number.
6080
6081The actual tenth Bernoulli number is @expr{5/66}.
6082
6083@smallexample
6084@group
60853: 0.0756823 1: 0 1: 0.25305 1: 0 1: 1.16659
60862: 5:66 . . . .
60871: 0.0757575
6088 .
6089
609010 k b @key{RET} c f M-0 @key{DEL} 11 X @key{DEL} 12 X @key{DEL} 13 X @key{DEL} 14 X
6091@end group
6092@end smallexample
6093
6094Just to exercise loops a bit more, let's compute a table of even
6095Bernoulli numbers.
6096
6097@smallexample
6098@group
60993: [] 1: [0.10132, 0.03079, 0.02340, 0.033197, ...]
61002: 2 .
61011: 30
6102 .
6103
6104 [ ] 2 @key{RET} 30 Z ( X | 2 Z )
6105@end group
6106@end smallexample
6107
6108@noindent
6109The vertical-bar @kbd{|} is the vector-concatenation command. When
6110we execute it, the list we are building will be in stack level 2
6111(initially this is an empty list), and the next Bernoulli number
6112will be in level 1. The effect is to append the Bernoulli number
6113onto the end of the list. (To create a table of exact fractional
6114Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
6115sequence of keystrokes.)
6116
6117With loops and conditionals, you can program essentially anything
6118in Calc. One other command that makes looping easier is @kbd{Z /},
6119which takes a condition from the stack and breaks out of the enclosing
6120loop if the condition is true (non-zero). You can use this to make
6121``while'' and ``until'' style loops.
6122
6123If you make a mistake when entering a keyboard macro, you can edit
6124it using @kbd{Z E}. First, you must attach it to a key with @kbd{Z K}.
6125One technique is to enter a throwaway dummy definition for the macro,
6126then enter the real one in the edit command.
6127
6128@smallexample
6129@group
61301: 3 1: 3 Calc Macro Edit Mode.
6131 . . Original keys: 1 <return> 2 +
6132
6133 1 ;; calc digits
6134 RET ;; calc-enter
6135 2 ;; calc digits
6136 + ;; calc-plus
6137
6138C-x ( 1 @key{RET} 2 + C-x ) Z K h @key{RET} Z E h
6139@end group
6140@end smallexample
6141
6142@noindent
6143A keyboard macro is stored as a pure keystroke sequence. The
6144@file{edmacro} package (invoked by @kbd{Z E}) scans along the
6145macro and tries to decode it back into human-readable steps.
6146Descriptions of the keystrokes are given as comments, which begin with
6147@samp{;;}, and which are ignored when the edited macro is saved.
6148Spaces and line breaks are also ignored when the edited macro is saved.
6149To enter a space into the macro, type @code{SPC}. All the special
6150characters @code{RET}, @code{LFD}, @code{TAB}, @code{SPC}, @code{DEL},
6151and @code{NUL} must be written in all uppercase, as must the prefixes
6152@code{C-} and @code{M-}.
6153
6154Let's edit in a new definition, for computing harmonic numbers.
6155First, erase the four lines of the old definition. Then, type
6156in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
6157to copy it from this page of the Info file; you can of course skip
6158typing the comments, which begin with @samp{;;}).
6159
6160@smallexample
6161Z` ;; calc-kbd-push (Save local values)
61620 ;; calc digits (Push a zero onto the stack)
6163st ;; calc-store-into (Store it in the following variable)
61641 ;; calc quick variable (Quick variable q1)
61651 ;; calc digits (Initial value for the loop)
6166TAB ;; calc-roll-down (Swap initial and final)
6167Z( ;; calc-kbd-for (Begin the "for" loop)
6168& ;; calc-inv (Take the reciprocal)
6169s+ ;; calc-store-plus (Add to the following variable)
61701 ;; calc quick variable (Quick variable q1)
61711 ;; calc digits (The loop step is 1)
6172Z) ;; calc-kbd-end-for (End the "for" loop)
6173sr ;; calc-recall (Recall the final accumulated value)
61741 ;; calc quick variable (Quick variable q1)
6175Z' ;; calc-kbd-pop (Restore values)
6176@end smallexample
6177
6178@noindent
6179Press @kbd{C-c C-c} to finish editing and return to the Calculator.
6180
6181@smallexample
6182@group
61831: 20 1: 3.597739
6184 . .
6185
6186 20 z h
6187@end group
6188@end smallexample
6189
6190The @file{edmacro} package defines a handy @code{read-kbd-macro} command
6191which reads the current region of the current buffer as a sequence of
6192keystroke names, and defines that sequence on the @kbd{X}
6193(and @kbd{C-x e}) key. Because this is so useful, Calc puts this
6194command on the @kbd{C-x * m} key. Try reading in this macro in the
6195following form: Press @kbd{C-@@} (or @kbd{C-@key{SPC}}) at
6196one end of the text below, then type @kbd{C-x * m} at the other.
6197
6198@example
6199@group
6200Z ` 0 t 1
6201 1 TAB
6202 Z ( & s + 1 1 Z )
6203 r 1
6204Z '
6205@end group
6206@end example
6207
6208(@bullet{}) @strong{Exercise 8.} A general algorithm for solving
6209equations numerically is @dfn{Newton's Method}. Given the equation
6210@expr{f(x) = 0} for any function @expr{f}, and an initial guess
6211@expr{x_0} which is reasonably close to the desired solution, apply
6212this formula over and over:
6213
6214@ifnottex
6215@example
6216new_x = x - f(x)/f'(x)
6217@end example
6218@end ifnottex
6219@tex
6220\beforedisplay
6221$$ x_{\rm new} = x - {f(x) \over f'(x)} $$
6222\afterdisplay
6223@end tex
6224
6225@noindent
6226where @expr{f'(x)} is the derivative of @expr{f}. The @expr{x}
6227values will quickly converge to a solution, i.e., eventually
6228@texline @math{x_{\rm new}}
6229@infoline @expr{new_x}
6230and @expr{x} will be equal to within the limits
6231of the current precision. Write a program which takes a formula
6232involving the variable @expr{x}, and an initial guess @expr{x_0},
6233on the stack, and produces a value of @expr{x} for which the formula
6234is zero. Use it to find a solution of
6235@texline @math{\sin(\cos x) = 0.5}
6236@infoline @expr{sin(cos(x)) = 0.5}
6237near @expr{x = 4.5}. (Use angles measured in radians.) Note that
6238the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
6239method when it is able. @xref{Programming Answer 8, 8}. (@bullet{})
6240
6241@cindex Digamma function
6242@cindex Gamma constant, Euler's
6243@cindex Euler's gamma constant
6244(@bullet{}) @strong{Exercise 9.} The @dfn{digamma} function
6245@texline @math{\psi(z) (``psi'')}
6246@infoline @expr{psi(z)}
6247is defined as the derivative of
6248@texline @math{\ln \Gamma(z)}.
6249@infoline @expr{ln(gamma(z))}.
6250For large values of @expr{z}, it can be approximated by the infinite sum
6251
6252@ifnottex
6253@example
6254psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
6255@end example
6256@end ifnottex
6257@tex
6258\beforedisplay
6259$$ \psi(z) \approx \ln z - {1\over2z} -
6260 \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
6261$$
6262\afterdisplay
6263@end tex
6264
6265@noindent
6266where
6267@texline @math{\sum}
6268@infoline @expr{sum}
6269represents the sum over @expr{n} from 1 to infinity
6270(or to some limit high enough to give the desired accuracy), and
6271the @code{bern} function produces (exact) Bernoulli numbers.
6272While this sum is not guaranteed to converge, in practice it is safe.
6273An interesting mathematical constant is Euler's gamma, which is equal
6274to about 0.5772. One way to compute it is by the formula,
6275@texline @math{\gamma = -\psi(1)}.
6276@infoline @expr{gamma = -psi(1)}.
6277Unfortunately, 1 isn't a large enough argument
6278for the above formula to work (5 is a much safer value for @expr{z}).
6279Fortunately, we can compute
6280@texline @math{\psi(1)}
6281@infoline @expr{psi(1)}
6282from
6283@texline @math{\psi(5)}
6284@infoline @expr{psi(5)}
6285using the recurrence
6286@texline @math{\psi(z+1) = \psi(z) + {1 \over z}}.
6287@infoline @expr{psi(z+1) = psi(z) + 1/z}.
6288Your task: Develop a program to compute
6289@texline @math{\psi(z)};
6290@infoline @expr{psi(z)};
6291it should ``pump up'' @expr{z}
6292if necessary to be greater than 5, then use the above summation
6293formula. Use looping commands to compute the sum. Use your function
6294to compute
6295@texline @math{\gamma}
6296@infoline @expr{gamma}
6297to twelve decimal places. (Calc has a built-in command
6298for Euler's constant, @kbd{I P}, which you can use to check your answer.)
6299@xref{Programming Answer 9, 9}. (@bullet{})
6300
6301@cindex Polynomial, list of coefficients
6302(@bullet{}) @strong{Exercise 10.} Given a polynomial in @expr{x} and
6303a number @expr{m} on the stack, where the polynomial is of degree
6304@expr{m} or less (i.e., does not have any terms higher than @expr{x^m}),
6305write a program to convert the polynomial into a list-of-coefficients
6306notation. For example, @expr{5 x^4 + (x + 1)^2} with @expr{m = 6}
6307should produce the list @expr{[1, 2, 1, 0, 5, 0, 0]}. Also develop
6308a way to convert from this form back to the standard algebraic form.
6309@xref{Programming Answer 10, 10}. (@bullet{})
6310
6311@cindex Recursion
6312(@bullet{}) @strong{Exercise 11.} The @dfn{Stirling numbers of the
6313first kind} are defined by the recurrences,
6314
6315@ifnottex
6316@example
6317s(n,n) = 1 for n >= 0,
6318s(n,0) = 0 for n > 0,
6319s(n+1,m) = s(n,m-1) - n s(n,m) for n >= m >= 1.
6320@end example
6321@end ifnottex
6322@tex
6323\turnoffactive
6324\beforedisplay
6325$$ \eqalign{ s(n,n) &= 1 \qquad \hbox{for } n \ge 0, \cr
6326 s(n,0) &= 0 \qquad \hbox{for } n > 0, \cr
6327 s(n+1,m) &= s(n,m-1) - n \, s(n,m) \qquad
6328 \hbox{for } n \ge m \ge 1.}
6329$$
6330\afterdisplay
6331\vskip5pt
6332(These numbers are also sometimes written $\displaystyle{n \brack m}$.)
6333@end tex
6334
6335This can be implemented using a @dfn{recursive} program in Calc; the
6336program must invoke itself in order to calculate the two righthand
6337terms in the general formula. Since it always invokes itself with
6338``simpler'' arguments, it's easy to see that it must eventually finish
6339the computation. Recursion is a little difficult with Emacs keyboard
6340macros since the macro is executed before its definition is complete.
6341So here's the recommended strategy: Create a ``dummy macro'' and assign
6342it to a key with, e.g., @kbd{Z K s}. Now enter the true definition,
6343using the @kbd{z s} command to call itself recursively, then assign it
6344to the same key with @kbd{Z K s}. Now the @kbd{z s} command will run
6345the complete recursive program. (Another way is to use @w{@kbd{Z E}}
6346or @kbd{C-x * m} (@code{read-kbd-macro}) to read the whole macro at once,
6347thus avoiding the ``training'' phase.) The task: Write a program
6348that computes Stirling numbers of the first kind, given @expr{n} and
6349@expr{m} on the stack. Test it with @emph{small} inputs like
6350@expr{s(4,2)}. (There is a built-in command for Stirling numbers,
6351@kbd{k s}, which you can use to check your answers.)
6352@xref{Programming Answer 11, 11}. (@bullet{})
6353
6354The programming commands we've seen in this part of the tutorial
6355are low-level, general-purpose operations. Often you will find
6356that a higher-level function, such as vector mapping or rewrite
6357rules, will do the job much more easily than a detailed, step-by-step
6358program can:
6359
6360(@bullet{}) @strong{Exercise 12.} Write another program for
6361computing Stirling numbers of the first kind, this time using
6362rewrite rules. Once again, @expr{n} and @expr{m} should be taken
6363from the stack. @xref{Programming Answer 12, 12}. (@bullet{})
6364
6365@example
6366
6367@end example
6368This ends the tutorial section of the Calc manual. Now you know enough
6369about Calc to use it effectively for many kinds of calculations. But
6370Calc has many features that were not even touched upon in this tutorial.
6371@c [not-split]
6372The rest of this manual tells the whole story.
6373@c [when-split]
6374@c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
6375
6376@page
6377@node Answers to Exercises, , Programming Tutorial, Tutorial
6378@section Answers to Exercises
6379
6380@noindent
6381This section includes answers to all the exercises in the Calc tutorial.
6382
6383@menu
6384* RPN Answer 1:: 1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -
6385* RPN Answer 2:: 2*4 + 7*9.5 + 5/4
6386* RPN Answer 3:: Operating on levels 2 and 3
6387* RPN Answer 4:: Joe's complex problems
6388* Algebraic Answer 1:: Simulating Q command
6389* Algebraic Answer 2:: Joe's algebraic woes
6390* Algebraic Answer 3:: 1 / 0
6391* Modes Answer 1:: 3#0.1 = 3#0.0222222?
6392* Modes Answer 2:: 16#f.e8fe15
6393* Modes Answer 3:: Joe's rounding bug
6394* Modes Answer 4:: Why floating point?
6395* Arithmetic Answer 1:: Why the \ command?
6396* Arithmetic Answer 2:: Tripping up the B command
6397* Vector Answer 1:: Normalizing a vector
6398* Vector Answer 2:: Average position
6399* Matrix Answer 1:: Row and column sums
6400* Matrix Answer 2:: Symbolic system of equations
6401* Matrix Answer 3:: Over-determined system
6402* List Answer 1:: Powers of two
6403* List Answer 2:: Least-squares fit with matrices
6404* List Answer 3:: Geometric mean
6405* List Answer 4:: Divisor function
6406* List Answer 5:: Duplicate factors
6407* List Answer 6:: Triangular list
6408* List Answer 7:: Another triangular list
6409* List Answer 8:: Maximum of Bessel function
6410* List Answer 9:: Integers the hard way
6411* List Answer 10:: All elements equal
6412* List Answer 11:: Estimating pi with darts
6413* List Answer 12:: Estimating pi with matchsticks
6414* List Answer 13:: Hash codes
6415* List Answer 14:: Random walk
6416* Types Answer 1:: Square root of pi times rational
6417* Types Answer 2:: Infinities
6418* Types Answer 3:: What can "nan" be?
6419* Types Answer 4:: Abbey Road
6420* Types Answer 5:: Friday the 13th
6421* Types Answer 6:: Leap years
6422* Types Answer 7:: Erroneous donut
6423* Types Answer 8:: Dividing intervals
6424* Types Answer 9:: Squaring intervals
6425* Types Answer 10:: Fermat's primality test
6426* Types Answer 11:: pi * 10^7 seconds
6427* Types Answer 12:: Abbey Road on CD
6428* Types Answer 13:: Not quite pi * 10^7 seconds
6429* Types Answer 14:: Supercomputers and c
6430* Types Answer 15:: Sam the Slug
6431* Algebra Answer 1:: Squares and square roots
6432* Algebra Answer 2:: Building polynomial from roots
6433* Algebra Answer 3:: Integral of x sin(pi x)
6434* Algebra Answer 4:: Simpson's rule
6435* Rewrites Answer 1:: Multiplying by conjugate
6436* Rewrites Answer 2:: Alternative fib rule
6437* Rewrites Answer 3:: Rewriting opt(a) + opt(b) x
6438* Rewrites Answer 4:: Sequence of integers
6439* Rewrites Answer 5:: Number of terms in sum
6440* Rewrites Answer 6:: Truncated Taylor series
6441* Programming Answer 1:: Fresnel's C(x)
6442* Programming Answer 2:: Negate third stack element
6443* Programming Answer 3:: Compute sin(x) / x, etc.
6444* Programming Answer 4:: Average value of a list
6445* Programming Answer 5:: Continued fraction phi
6446* Programming Answer 6:: Matrix Fibonacci numbers
6447* Programming Answer 7:: Harmonic number greater than 4
6448* Programming Answer 8:: Newton's method
6449* Programming Answer 9:: Digamma function
6450* Programming Answer 10:: Unpacking a polynomial
6451* Programming Answer 11:: Recursive Stirling numbers
6452* Programming Answer 12:: Stirling numbers with rewrites
6453@end menu
6454
6455@c The following kludgery prevents the individual answers from
6456@c being entered on the table of contents.
6457@tex
6458\global\let\oldwrite=\write
6459\gdef\skipwrite#1#2{\let\write=\oldwrite}
6460\global\let\oldchapternofonts=\chapternofonts
6461\gdef\chapternofonts{\let\write=\skipwrite\oldchapternofonts}
6462@end tex
6463
6464@node RPN Answer 1, RPN Answer 2, Answers to Exercises, Answers to Exercises
6465@subsection RPN Tutorial Exercise 1
6466
6467@noindent
6468@kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -}
6469
6470The result is
6471@texline @math{1 - (2 \times (3 + 4)) = -13}.
6472@infoline @expr{1 - (2 * (3 + 4)) = -13}.
6473
6474@node RPN Answer 2, RPN Answer 3, RPN Answer 1, Answers to Exercises
6475@subsection RPN Tutorial Exercise 2
6476
6477@noindent
6478@texline @math{2\times4 + 7\times9.5 + {5\over4} = 75.75}
6479@infoline @expr{2*4 + 7*9.5 + 5/4 = 75.75}
6480
6481After computing the intermediate term
6482@texline @math{2\times4 = 8},
6483@infoline @expr{2*4 = 8},
6484you can leave that result on the stack while you compute the second
6485term. With both of these results waiting on the stack you can then
6486compute the final term, then press @kbd{+ +} to add everything up.
6487
6488@smallexample
6489@group
64902: 2 1: 8 3: 8 2: 8
64911: 4 . 2: 7 1: 66.5
6492 . 1: 9.5 .
6493 .
6494
6495 2 @key{RET} 4 * 7 @key{RET} 9.5 *
6496
6497@end group
6498@end smallexample
6499@noindent
6500@smallexample
6501@group
65024: 8 3: 8 2: 8 1: 75.75
65033: 66.5 2: 66.5 1: 67.75 .
65042: 5 1: 1.25 .
65051: 4 .
6506 .
6507
6508 5 @key{RET} 4 / + +
6509@end group
6510@end smallexample
6511
6512Alternatively, you could add the first two terms before going on
6513with the third term.
6514
6515@smallexample
6516@group
65172: 8 1: 74.5 3: 74.5 2: 74.5 1: 75.75
65181: 66.5 . 2: 5 1: 1.25 .
6519 . 1: 4 .
6520 .
6521
6522 ... + 5 @key{RET} 4 / +
6523@end group
6524@end smallexample
6525
6526On an old-style RPN calculator this second method would have the
6527advantage of using only three stack levels. But since Calc's stack
6528can grow arbitrarily large this isn't really an issue. Which method
6529you choose is purely a matter of taste.
6530
6531@node RPN Answer 3, RPN Answer 4, RPN Answer 2, Answers to Exercises
6532@subsection RPN Tutorial Exercise 3
6533
6534@noindent
6535The @key{TAB} key provides a way to operate on the number in level 2.
6536
6537@smallexample
6538@group
65393: 10 3: 10 4: 10 3: 10 3: 10
65402: 20 2: 30 3: 30 2: 30 2: 21
65411: 30 1: 20 2: 20 1: 21 1: 30
6542 . . 1: 1 . .
6543 .
6544
6545 @key{TAB} 1 + @key{TAB}
6546@end group
6547@end smallexample
6548
6549Similarly, @kbd{M-@key{TAB}} gives you access to the number in level 3.
6550
6551@smallexample
6552@group
65533: 10 3: 21 3: 21 3: 30 3: 11
65542: 21 2: 30 2: 30 2: 11 2: 21
65551: 30 1: 10 1: 11 1: 21 1: 30
6556 . . . . .
6557
6558 M-@key{TAB} 1 + M-@key{TAB} M-@key{TAB}
6559@end group
6560@end smallexample
6561
6562@node RPN Answer 4, Algebraic Answer 1, RPN Answer 3, Answers to Exercises
6563@subsection RPN Tutorial Exercise 4
6564
6565@noindent
6566Either @kbd{( 2 , 3 )} or @kbd{( 2 @key{SPC} 3 )} would have worked,
6567but using both the comma and the space at once yields:
6568
6569@smallexample
6570@group
65711: ( ... 2: ( ... 1: (2, ... 2: (2, ... 2: (2, ...
6572 . 1: 2 . 1: (2, ... 1: (2, 3)
6573 . . .
6574
6575 ( 2 , @key{SPC} 3 )
6576@end group
6577@end smallexample
6578
6579Joe probably tried to type @kbd{@key{TAB} @key{DEL}} to swap the
6580extra incomplete object to the top of the stack and delete it.
6581But a feature of Calc is that @key{DEL} on an incomplete object
6582deletes just one component out of that object, so he had to press
6583@key{DEL} twice to finish the job.
6584
6585@smallexample
6586@group
65872: (2, ... 2: (2, 3) 2: (2, 3) 1: (2, 3)
65881: (2, 3) 1: (2, ... 1: ( ... .
6589 . . .
6590
6591 @key{TAB} @key{DEL} @key{DEL}
6592@end group
6593@end smallexample
6594
6595(As it turns out, deleting the second-to-top stack entry happens often
6596enough that Calc provides a special key, @kbd{M-@key{DEL}}, to do just that.
6597@kbd{M-@key{DEL}} is just like @kbd{@key{TAB} @key{DEL}}, except that it doesn't exhibit
6598the ``feature'' that tripped poor Joe.)
6599
6600@node Algebraic Answer 1, Algebraic Answer 2, RPN Answer 4, Answers to Exercises
6601@subsection Algebraic Entry Tutorial Exercise 1
6602
6603@noindent
6604Type @kbd{' sqrt($) @key{RET}}.
6605
6606If the @kbd{Q} key is broken, you could use @kbd{' $^0.5 @key{RET}}.
6607Or, RPN style, @kbd{0.5 ^}.
6608
6609(Actually, @samp{$^1:2}, using the fraction one-half as the power, is
6610a closer equivalent, since @samp{9^0.5} yields @expr{3.0} whereas
6611@samp{sqrt(9)} and @samp{9^1:2} yield the exact integer @expr{3}.)
6612
6613@node Algebraic Answer 2, Algebraic Answer 3, Algebraic Answer 1, Answers to Exercises
6614@subsection Algebraic Entry Tutorial Exercise 2
6615
6616@noindent
6617In the formula @samp{2 x (1+y)}, @samp{x} was interpreted as a function
6618name with @samp{1+y} as its argument. Assigning a value to a variable
6619has no relation to a function by the same name. Joe needed to use an
6620explicit @samp{*} symbol here: @samp{2 x*(1+y)}.
6621
6622@node Algebraic Answer 3, Modes Answer 1, Algebraic Answer 2, Answers to Exercises
6623@subsection Algebraic Entry Tutorial Exercise 3
6624
6625@noindent
6626The result from @kbd{1 @key{RET} 0 /} will be the formula @expr{1 / 0}.
6627The ``function'' @samp{/} cannot be evaluated when its second argument
6628is zero, so it is left in symbolic form. When you now type @kbd{0 *},
6629the result will be zero because Calc uses the general rule that ``zero
6630times anything is zero.''
6631
6632@c [fix-ref Infinities]
6633The @kbd{m i} command enables an @dfn{Infinite mode} in which @expr{1 / 0}
6634results in a special symbol that represents ``infinity.'' If you
6635multiply infinity by zero, Calc uses another special new symbol to
6636show that the answer is ``indeterminate.'' @xref{Infinities}, for
6637further discussion of infinite and indeterminate values.
6638
6639@node Modes Answer 1, Modes Answer 2, Algebraic Answer 3, Answers to Exercises
6640@subsection Modes Tutorial Exercise 1
6641
6642@noindent
6643Calc always stores its numbers in decimal, so even though one-third has
6644an exact base-3 representation (@samp{3#0.1}), it is still stored as
66450.3333333 (chopped off after 12 or however many decimal digits) inside
6646the calculator's memory. When this inexact number is converted back
6647to base 3 for display, it may still be slightly inexact. When we
6648multiply this number by 3, we get 0.999999, also an inexact value.
6649
6650When Calc displays a number in base 3, it has to decide how many digits
6651to show. If the current precision is 12 (decimal) digits, that corresponds
6652to @samp{12 / log10(3) = 25.15} base-3 digits. Because 25.15 is not an
6653exact integer, Calc shows only 25 digits, with the result that stored
6654numbers carry a little bit of extra information that may not show up on
6655the screen. When Joe entered @samp{3#0.2}, the stored number 0.666666
6656happened to round to a pleasing value when it lost that last 0.15 of a
6657digit, but it was still inexact in Calc's memory. When he divided by 2,
6658he still got the dreaded inexact value 0.333333. (Actually, he divided
66590.666667 by 2 to get 0.333334, which is why he got something a little
6660higher than @code{3#0.1} instead of a little lower.)
6661
6662If Joe didn't want to be bothered with all this, he could have typed
6663@kbd{M-24 d n} to display with one less digit than the default. (If
6664you give @kbd{d n} a negative argument, it uses default-minus-that,
6665so @kbd{M-- d n} would be an easier way to get the same effect.) Those
6666inexact results would still be lurking there, but they would now be
6667rounded to nice, natural-looking values for display purposes. (Remember,
6668@samp{0.022222} in base 3 is like @samp{0.099999} in base 10; rounding
6669off one digit will round the number up to @samp{0.1}.) Depending on the
6670nature of your work, this hiding of the inexactness may be a benefit or
6671a danger. With the @kbd{d n} command, Calc gives you the choice.
6672
6673Incidentally, another consequence of all this is that if you type
6674@kbd{M-30 d n} to display more digits than are ``really there,''
6675you'll see garbage digits at the end of the number. (In decimal
6676display mode, with decimally-stored numbers, these garbage digits are
6677always zero so they vanish and you don't notice them.) Because Calc
6678rounds off that 0.15 digit, there is the danger that two numbers could
6679be slightly different internally but still look the same. If you feel
6680uneasy about this, set the @kbd{d n} precision to be a little higher
6681than normal; you'll get ugly garbage digits, but you'll always be able
6682to tell two distinct numbers apart.
6683
6684An interesting side note is that most computers store their
6685floating-point numbers in binary, and convert to decimal for display.
6686Thus everyday programs have the same problem: Decimal 0.1 cannot be
6687represented exactly in binary (try it: @kbd{0.1 d 2}), so @samp{0.1 * 10}
6688comes out as an inexact approximation to 1 on some machines (though
6689they generally arrange to hide it from you by rounding off one digit as
6690we did above). Because Calc works in decimal instead of binary, you can
6691be sure that numbers that look exact @emph{are} exact as long as you stay
6692in decimal display mode.
6693
6694It's not hard to show that any number that can be represented exactly
6695in binary, octal, or hexadecimal is also exact in decimal, so the kinds
6696of problems we saw in this exercise are likely to be severe only when
6697you use a relatively unusual radix like 3.
6698
6699@node Modes Answer 2, Modes Answer 3, Modes Answer 1, Answers to Exercises
6700@subsection Modes Tutorial Exercise 2
6701
6702If the radix is 15 or higher, we can't use the letter @samp{e} to mark
6703the exponent because @samp{e} is interpreted as a digit. When Calc
6704needs to display scientific notation in a high radix, it writes
6705@samp{16#F.E8F*16.^15}. You can enter a number like this as an
6706algebraic entry. Also, pressing @kbd{e} without any digits before it
6707normally types @kbd{1e}, but in a high radix it types @kbd{16.^} and
6708puts you in algebraic entry: @kbd{16#f.e8f @key{RET} e 15 @key{RET} *} is another
6709way to enter this number.
6710
6711The reason Calc puts a decimal point in the @samp{16.^} is to prevent
6712huge integers from being generated if the exponent is large (consider
6713@samp{16#1.23*16^1000}, where we compute @samp{16^1000} as a giant
6714exact integer and then throw away most of the digits when we multiply
6715it by the floating-point @samp{16#1.23}). While this wouldn't normally
6716matter for display purposes, it could give you a nasty surprise if you
6717copied that number into a file and later moved it back into Calc.
6718
6719@node Modes Answer 3, Modes Answer 4, Modes Answer 2, Answers to Exercises
6720@subsection Modes Tutorial Exercise 3
6721
6722@noindent
6723The answer he got was @expr{0.5000000000006399}.
6724
6725The problem is not that the square operation is inexact, but that the
6726sine of 45 that was already on the stack was accurate to only 12 places.
6727Arbitrary-precision calculations still only give answers as good as
6728their inputs.
6729
6730The real problem is that there is no 12-digit number which, when
6731squared, comes out to 0.5 exactly. The @kbd{f [} and @kbd{f ]}
6732commands decrease or increase a number by one unit in the last
6733place (according to the current precision). They are useful for
6734determining facts like this.
6735
6736@smallexample
6737@group
67381: 0.707106781187 1: 0.500000000001
6739 . .
6740
6741 45 S 2 ^
6742
6743@end group
6744@end smallexample
6745@noindent
6746@smallexample
6747@group
67481: 0.707106781187 1: 0.707106781186 1: 0.499999999999
6749 . . .
6750
6751 U @key{DEL} f [ 2 ^
6752@end group
6753@end smallexample
6754
6755A high-precision calculation must be carried out in high precision
6756all the way. The only number in the original problem which was known
6757exactly was the quantity 45 degrees, so the precision must be raised
6758before anything is done after the number 45 has been entered in order
6759for the higher precision to be meaningful.
6760
6761@node Modes Answer 4, Arithmetic Answer 1, Modes Answer 3, Answers to Exercises
6762@subsection Modes Tutorial Exercise 4
6763
6764@noindent
6765Many calculations involve real-world quantities, like the width and
6766height of a piece of wood or the volume of a jar. Such quantities
6767can't be measured exactly anyway, and if the data that is input to
6768a calculation is inexact, doing exact arithmetic on it is a waste
6769of time.
6770
6771Fractions become unwieldy after too many calculations have been
6772done with them. For example, the sum of the reciprocals of the
6773integers from 1 to 10 is 7381:2520. The sum from 1 to 30 is
67749304682830147:2329089562800. After a point it will take a long
6775time to add even one more term to this sum, but a floating-point
6776calculation of the sum will not have this problem.
6777
6778Also, rational numbers cannot express the results of all calculations.
6779There is no fractional form for the square root of two, so if you type
6780@w{@kbd{2 Q}}, Calc has no choice but to give you a floating-point answer.
6781
6782@node Arithmetic Answer 1, Arithmetic Answer 2, Modes Answer 4, Answers to Exercises
6783@subsection Arithmetic Tutorial Exercise 1
6784
6785@noindent
6786Dividing two integers that are larger than the current precision may
6787give a floating-point result that is inaccurate even when rounded
6788down to an integer. Consider @expr{123456789 / 2} when the current
6789precision is 6 digits. The true answer is @expr{61728394.5}, but
6790with a precision of 6 this will be rounded to
6791@texline @math{12345700.0/2.0 = 61728500.0}.
6792@infoline @expr{12345700.@: / 2.@: = 61728500.}.
6793The result, when converted to an integer, will be off by 106.
6794
6795Here are two solutions: Raise the precision enough that the
6796floating-point round-off error is strictly to the right of the
6797decimal point. Or, convert to Fraction mode so that @expr{123456789 / 2}
6798produces the exact fraction @expr{123456789:2}, which can be rounded
6799down by the @kbd{F} command without ever switching to floating-point
6800format.
6801
6802@node Arithmetic Answer 2, Vector Answer 1, Arithmetic Answer 1, Answers to Exercises
6803@subsection Arithmetic Tutorial Exercise 2
6804
6805@noindent
6806@kbd{27 @key{RET} 9 B} could give the exact result @expr{3:2}, but it
6807does a floating-point calculation instead and produces @expr{1.5}.
6808
6809Calc will find an exact result for a logarithm if the result is an integer
6810or (when in Fraction mode) the reciprocal of an integer. But there is
6811no efficient way to search the space of all possible rational numbers
6812for an exact answer, so Calc doesn't try.
6813
6814@node Vector Answer 1, Vector Answer 2, Arithmetic Answer 2, Answers to Exercises
6815@subsection Vector Tutorial Exercise 1
6816
6817@noindent
6818Duplicate the vector, compute its length, then divide the vector
6819by its length: @kbd{@key{RET} A /}.
6820
6821@smallexample
6822@group
68231: [1, 2, 3] 2: [1, 2, 3] 1: [0.27, 0.53, 0.80] 1: 1.
6824 . 1: 3.74165738677 . .
6825 .
6826
6827 r 1 @key{RET} A / A
6828@end group
6829@end smallexample
6830
6831The final @kbd{A} command shows that the normalized vector does
6832indeed have unit length.
6833
6834@node Vector Answer 2, Matrix Answer 1, Vector Answer 1, Answers to Exercises
6835@subsection Vector Tutorial Exercise 2
6836
6837@noindent
6838The average position is equal to the sum of the products of the
6839positions times their corresponding probabilities. This is the
6840definition of the dot product operation. So all you need to do
6841is to put the two vectors on the stack and press @kbd{*}.
6842
6843@node Matrix Answer 1, Matrix Answer 2, Vector Answer 2, Answers to Exercises
6844@subsection Matrix Tutorial Exercise 1
6845
6846@noindent
6847The trick is to multiply by a vector of ones. Use @kbd{r 4 [1 1 1] *} to
6848get the row sum. Similarly, use @kbd{[1 1] r 4 *} to get the column sum.
6849
6850@node Matrix Answer 2, Matrix Answer 3, Matrix Answer 1, Answers to Exercises
6851@subsection Matrix Tutorial Exercise 2
6852
6853@ifnottex
6854@example
6855@group
6856 x + a y = 6
6857 x + b y = 10
6858@end group
6859@end example
6860@end ifnottex
6861@tex
6862\turnoffactive
6863\beforedisplay
6864$$ \eqalign{ x &+ a y = 6 \cr
6865 x &+ b y = 10}
6866$$
6867\afterdisplay
6868@end tex
6869
6870Just enter the righthand side vector, then divide by the lefthand side
6871matrix as usual.
6872
6873@smallexample
6874@group
68751: [6, 10] 2: [6, 10] 1: [6 - 4 a / (b - a), 4 / (b - a) ]
6876 . 1: [ [ 1, a ] .
6877 [ 1, b ] ]
6878 .
6879
6880' [6 10] @key{RET} ' [1 a; 1 b] @key{RET} /
6881@end group
6882@end smallexample
6883
6884This can be made more readable using @kbd{d B} to enable Big display
6885mode:
6886
6887@smallexample
6888@group
6889 4 a 4
68901: [6 - -----, -----]
6891 b - a b - a
6892@end group
6893@end smallexample
6894
6895Type @kbd{d N} to return to Normal display mode afterwards.
6896
6897@node Matrix Answer 3, List Answer 1, Matrix Answer 2, Answers to Exercises
6898@subsection Matrix Tutorial Exercise 3
6899
6900@noindent
6901To solve
6902@texline @math{A^T A \, X = A^T B},
6903@infoline @expr{trn(A) * A * X = trn(A) * B},
6904first we compute
6905@texline @math{A' = A^T A}
6906@infoline @expr{A2 = trn(A) * A}
6907and
6908@texline @math{B' = A^T B};
6909@infoline @expr{B2 = trn(A) * B};
6910now, we have a system
6911@texline @math{A' X = B'}
6912@infoline @expr{A2 * X = B2}
6913which we can solve using Calc's @samp{/} command.
6914
6915@ifnottex
6916@example
6917@group
6918 a + 2b + 3c = 6
6919 4a + 5b + 6c = 2
6920 7a + 6b = 3
6921 2a + 4b + 6c = 11
6922@end group
6923@end example
6924@end ifnottex
6925@tex
6926\turnoffactive
6927\beforedisplayh
6928$$ \openup1\jot \tabskip=0pt plus1fil
6929\halign to\displaywidth{\tabskip=0pt
6930 $\hfil#$&$\hfil{}#{}$&
6931 $\hfil#$&$\hfil{}#{}$&
6932 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
6933 a&+&2b&+&3c&=6 \cr
6934 4a&+&5b&+&6c&=2 \cr
6935 7a&+&6b& & &=3 \cr
6936 2a&+&4b&+&6c&=11 \cr}
6937$$
6938\afterdisplayh
6939@end tex
6940
6941The first step is to enter the coefficient matrix. We'll store it in
6942quick variable number 7 for later reference. Next, we compute the
6943@texline @math{B'}
6944@infoline @expr{B2}
6945vector.
6946
6947@smallexample
6948@group
69491: [ [ 1, 2, 3 ] 2: [ [ 1, 4, 7, 2 ] 1: [57, 84, 96]
6950 [ 4, 5, 6 ] [ 2, 5, 6, 4 ] .
6951 [ 7, 6, 0 ] [ 3, 6, 0, 6 ] ]
6952 [ 2, 4, 6 ] ] 1: [6, 2, 3, 11]
6953 . .
6954
6955' [1 2 3; 4 5 6; 7 6 0; 2 4 6] @key{RET} s 7 v t [6 2 3 11] *
6956@end group
6957@end smallexample
6958
6959@noindent
6960Now we compute the matrix
6961@texline @math{A'}
6962@infoline @expr{A2}
6963and divide.
6964
6965@smallexample
6966@group
69672: [57, 84, 96] 1: [-11.64, 14.08, -3.64]
69681: [ [ 70, 72, 39 ] .
6969 [ 72, 81, 60 ]
6970 [ 39, 60, 81 ] ]
6971 .
6972
6973 r 7 v t r 7 * /
6974@end group
6975@end smallexample
6976
6977@noindent
6978(The actual computed answer will be slightly inexact due to
6979round-off error.)
6980
6981Notice that the answers are similar to those for the
6982@texline @math{3\times3}
6983@infoline 3x3
6984system solved in the text. That's because the fourth equation that was
6985added to the system is almost identical to the first one multiplied
6986by two. (If it were identical, we would have gotten the exact same
6987answer since the
6988@texline @math{4\times3}
6989@infoline 4x3
6990system would be equivalent to the original
6991@texline @math{3\times3}
6992@infoline 3x3
6993system.)
6994
6995Since the first and fourth equations aren't quite equivalent, they
6996can't both be satisfied at once. Let's plug our answers back into
6997the original system of equations to see how well they match.
6998
6999@smallexample
7000@group
70012: [-11.64, 14.08, -3.64] 1: [5.6, 2., 3., 11.2]
70021: [ [ 1, 2, 3 ] .
7003 [ 4, 5, 6 ]
7004 [ 7, 6, 0 ]
7005 [ 2, 4, 6 ] ]
7006 .
7007
7008 r 7 @key{TAB} *
7009@end group
7010@end smallexample
7011
7012@noindent
7013This is reasonably close to our original @expr{B} vector,
7014@expr{[6, 2, 3, 11]}.
7015
7016@node List Answer 1, List Answer 2, Matrix Answer 3, Answers to Exercises
7017@subsection List Tutorial Exercise 1
7018
7019@noindent
7020We can use @kbd{v x} to build a vector of integers. This needs to be
7021adjusted to get the range of integers we desire. Mapping @samp{-}
7022across the vector will accomplish this, although it turns out the
7023plain @samp{-} key will work just as well.
7024
7025@smallexample
7026@group
70272: 2 2: 2
70281: [1, 2, 3, 4, 5, 6, 7, 8, 9] 1: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
7029 . .
7030
7031 2 v x 9 @key{RET} 5 V M - or 5 -
7032@end group
7033@end smallexample
7034
7035@noindent
7036Now we use @kbd{V M ^} to map the exponentiation operator across the
7037vector.
7038
7039@smallexample
7040@group
70411: [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
7042 .
7043
7044 V M ^
7045@end group
7046@end smallexample
7047
7048@node List Answer 2, List Answer 3, List Answer 1, Answers to Exercises
7049@subsection List Tutorial Exercise 2
7050
7051@noindent
7052Given @expr{x} and @expr{y} vectors in quick variables 1 and 2 as before,
7053the first job is to form the matrix that describes the problem.
7054
7055@ifnottex
7056@example
7057 m*x + b*1 = y
7058@end example
7059@end ifnottex
7060@tex
7061\turnoffactive
7062\beforedisplay
7063$$ m \times x + b \times 1 = y $$
7064\afterdisplay
7065@end tex
7066
7067Thus we want a
7068@texline @math{19\times2}
7069@infoline 19x2
7070matrix with our @expr{x} vector as one column and
7071ones as the other column. So, first we build the column of ones, then
7072we combine the two columns to form our @expr{A} matrix.
7073
7074@smallexample
7075@group
70762: [1.34, 1.41, 1.49, ... ] 1: [ [ 1.34, 1 ]
70771: [1, 1, 1, ...] [ 1.41, 1 ]
7078 . [ 1.49, 1 ]
7079 @dots{}
7080
7081 r 1 1 v b 19 @key{RET} M-2 v p v t s 3
7082@end group
7083@end smallexample
7084
7085@noindent
7086Now we compute
7087@texline @math{A^T y}
7088@infoline @expr{trn(A) * y}
7089and
7090@texline @math{A^T A}
7091@infoline @expr{trn(A) * A}
7092and divide.
7093
7094@smallexample
7095@group
70961: [33.36554, 13.613] 2: [33.36554, 13.613]
7097 . 1: [ [ 98.0003, 41.63 ]
7098 [ 41.63, 19 ] ]
7099 .
7100
7101 v t r 2 * r 3 v t r 3 *
7102@end group
7103@end smallexample
7104
7105@noindent
7106(Hey, those numbers look familiar!)
7107
7108@smallexample
7109@group
71101: [0.52141679, -0.425978]
7111 .
7112
7113 /
7114@end group
7115@end smallexample
7116
7117Since we were solving equations of the form
7118@texline @math{m \times x + b \times 1 = y},
7119@infoline @expr{m*x + b*1 = y},
7120these numbers should be @expr{m} and @expr{b}, respectively. Sure
7121enough, they agree exactly with the result computed using @kbd{V M} and
7122@kbd{V R}!
7123
7124The moral of this story: @kbd{V M} and @kbd{V R} will probably solve
7125your problem, but there is often an easier way using the higher-level
7126arithmetic functions!
7127
7128@c [fix-ref Curve Fitting]
7129In fact, there is a built-in @kbd{a F} command that does least-squares
7130fits. @xref{Curve Fitting}.
7131
7132@node List Answer 3, List Answer 4, List Answer 2, Answers to Exercises
7133@subsection List Tutorial Exercise 3
7134
7135@noindent
7136Move to one end of the list and press @kbd{C-@@} (or @kbd{C-@key{SPC}} or
7137whatever) to set the mark, then move to the other end of the list
7138and type @w{@kbd{C-x * g}}.
7139
7140@smallexample
7141@group
71421: [2.3, 6, 22, 15.1, 7, 15, 14, 7.5, 2.5]
7143 .
7144@end group
7145@end smallexample
7146
7147To make things interesting, let's assume we don't know at a glance
7148how many numbers are in this list. Then we could type:
7149
7150@smallexample
7151@group
71522: [2.3, 6, 22, ... ] 2: [2.3, 6, 22, ... ]
71531: [2.3, 6, 22, ... ] 1: 126356422.5
7154 . .
7155
7156 @key{RET} V R *
7157
7158@end group
7159@end smallexample
7160@noindent
7161@smallexample
7162@group
71632: 126356422.5 2: 126356422.5 1: 7.94652913734
71641: [2.3, 6, 22, ... ] 1: 9 .
7165 . .
7166
7167 @key{TAB} v l I ^
7168@end group
7169@end smallexample
7170
7171@noindent
7172(The @kbd{I ^} command computes the @var{n}th root of a number.
7173You could also type @kbd{& ^} to take the reciprocal of 9 and
7174then raise the number to that power.)
7175
7176@node List Answer 4, List Answer 5, List Answer 3, Answers to Exercises
7177@subsection List Tutorial Exercise 4
7178
7179@noindent
7180A number @expr{j} is a divisor of @expr{n} if
7181@texline @math{n \mathbin{\hbox{\code{\%}}} j = 0}.
7182@infoline @samp{n % j = 0}.
7183The first step is to get a vector that identifies the divisors.
7184
7185@smallexample
7186@group
71872: 30 2: [0, 0, 0, 2, ...] 1: [1, 1, 1, 0, ...]
71881: [1, 2, 3, 4, ...] 1: 0 .
7189 . .
7190
7191 30 @key{RET} v x 30 @key{RET} s 1 V M % 0 V M a = s 2
7192@end group
7193@end smallexample
7194
7195@noindent
7196This vector has 1's marking divisors of 30 and 0's marking non-divisors.
7197
7198The zeroth divisor function is just the total number of divisors.
7199The first divisor function is the sum of the divisors.
7200
7201@smallexample
7202@group
72031: 8 3: 8 2: 8 2: 8
7204 2: [1, 2, 3, 4, ...] 1: [1, 2, 3, 0, ...] 1: 72
7205 1: [1, 1, 1, 0, ...] . .
7206 .
7207
7208 V R + r 1 r 2 V M * V R +
7209@end group
7210@end smallexample
7211
7212@noindent
7213Once again, the last two steps just compute a dot product for which
7214a simple @kbd{*} would have worked equally well.
7215
7216@node List Answer 5, List Answer 6, List Answer 4, Answers to Exercises
7217@subsection List Tutorial Exercise 5
7218
7219@noindent
7220The obvious first step is to obtain the list of factors with @kbd{k f}.
7221This list will always be in sorted order, so if there are duplicates
7222they will be right next to each other. A suitable method is to compare
7223the list with a copy of itself shifted over by one.
7224
7225@smallexample
7226@group
72271: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19, 0]
7228 . 1: [3, 7, 7, 7, 19, 0] 1: [0, 3, 7, 7, 7, 19]
7229 . .
7230
7231 19551 k f @key{RET} 0 | @key{TAB} 0 @key{TAB} |
7232
7233@end group
7234@end smallexample
7235@noindent
7236@smallexample
7237@group
72381: [0, 0, 1, 1, 0, 0] 1: 2 1: 0
7239 . . .
7240
7241 V M a = V R + 0 a =
7242@end group
7243@end smallexample
7244
7245@noindent
7246Note that we have to arrange for both vectors to have the same length
7247so that the mapping operation works; no prime factor will ever be
7248zero, so adding zeros on the left and right is safe. From then on
7249the job is pretty straightforward.
7250
7251Incidentally, Calc provides the
7252@texline @dfn{M@"obius} @math{\mu}
7253@infoline @dfn{Moebius mu}
7254function which is zero if and only if its argument is square-free. It
7255would be a much more convenient way to do the above test in practice.
7256
7257@node List Answer 6, List Answer 7, List Answer 5, Answers to Exercises
7258@subsection List Tutorial Exercise 6
7259
7260@noindent
7261First use @kbd{v x 6 @key{RET}} to get a list of integers, then @kbd{V M v x}
7262to get a list of lists of integers!
7263
7264@node List Answer 7, List Answer 8, List Answer 6, Answers to Exercises
7265@subsection List Tutorial Exercise 7
7266
7267@noindent
7268Here's one solution. First, compute the triangular list from the previous
7269exercise and type @kbd{1 -} to subtract one from all the elements.
7270
7271@smallexample
7272@group
72731: [ [0],
7274 [0, 1],
7275 [0, 1, 2],
7276 @dots{}
7277
7278 1 -
7279@end group
7280@end smallexample
7281
7282The numbers down the lefthand edge of the list we desire are called
7283the ``triangular numbers'' (now you know why!). The @expr{n}th
7284triangular number is the sum of the integers from 1 to @expr{n}, and
7285can be computed directly by the formula
7286@texline @math{n (n+1) \over 2}.
7287@infoline @expr{n * (n+1) / 2}.
7288
7289@smallexample
7290@group
72912: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
72921: [0, 1, 2, 3, 4, 5] 1: [0, 1, 3, 6, 10, 15]
7293 . .
7294
7295 v x 6 @key{RET} 1 - V M ' $ ($+1)/2 @key{RET}
7296@end group
7297@end smallexample
7298
7299@noindent
7300Adding this list to the above list of lists produces the desired
7301result:
7302
7303@smallexample
7304@group
73051: [ [0],
7306 [1, 2],
7307 [3, 4, 5],
7308 [6, 7, 8, 9],
7309 [10, 11, 12, 13, 14],
7310 [15, 16, 17, 18, 19, 20] ]
7311 .
7312
7313 V M +
7314@end group
7315@end smallexample
7316
7317If we did not know the formula for triangular numbers, we could have
7318computed them using a @kbd{V U +} command. We could also have
7319gotten them the hard way by mapping a reduction across the original
7320triangular list.
7321
7322@smallexample
7323@group
73242: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
73251: [ [0], [0, 1], ... ] 1: [0, 1, 3, 6, 10, 15]
7326 . .
7327
7328 @key{RET} V M V R +
7329@end group
7330@end smallexample
7331
7332@noindent
7333(This means ``map a @kbd{V R +} command across the vector,'' and
7334since each element of the main vector is itself a small vector,
7335@kbd{V R +} computes the sum of its elements.)
7336
7337@node List Answer 8, List Answer 9, List Answer 7, Answers to Exercises
7338@subsection List Tutorial Exercise 8
7339
7340@noindent
7341The first step is to build a list of values of @expr{x}.
7342
7343@smallexample
7344@group
73451: [1, 2, 3, ..., 21] 1: [0, 1, 2, ..., 20] 1: [0, 0.25, 0.5, ..., 5]
7346 . . .
7347
7348 v x 21 @key{RET} 1 - 4 / s 1
7349@end group
7350@end smallexample
7351
7352Next, we compute the Bessel function values.
7353
7354@smallexample
7355@group
73561: [0., 0.124, 0.242, ..., -0.328]
7357 .
7358
7359 V M ' besJ(1,$) @key{RET}
7360@end group
7361@end smallexample
7362
7363@noindent
7364(Another way to do this would be @kbd{1 @key{TAB} V M f j}.)
7365
7366A way to isolate the maximum value is to compute the maximum using
7367@kbd{V R X}, then compare all the Bessel values with that maximum.
7368
7369@smallexample
7370@group
73712: [0., 0.124, 0.242, ... ] 1: [0, 0, 0, ... ] 2: [0, 0, 0, ... ]
73721: 0.5801562 . 1: 1
7373 . .
7374
7375 @key{RET} V R X V M a = @key{RET} V R + @key{DEL}
7376@end group
7377@end smallexample
7378
7379@noindent
7380It's a good idea to verify, as in the last step above, that only
7381one value is equal to the maximum. (After all, a plot of
7382@texline @math{\sin x}
7383@infoline @expr{sin(x)}
7384might have many points all equal to the maximum value, 1.)
7385
7386The vector we have now has a single 1 in the position that indicates
7387the maximum value of @expr{x}. Now it is a simple matter to convert
7388this back into the corresponding value itself.
7389
7390@smallexample
7391@group
73922: [0, 0, 0, ... ] 1: [0, 0., 0., ... ] 1: 1.75
73931: [0, 0.25, 0.5, ... ] . .
7394 .
7395
7396 r 1 V M * V R +
7397@end group
7398@end smallexample
7399
7400If @kbd{a =} had produced more than one @expr{1} value, this method
7401would have given the sum of all maximum @expr{x} values; not very
7402useful! In this case we could have used @kbd{v m} (@code{calc-mask-vector})
7403instead. This command deletes all elements of a ``data'' vector that
7404correspond to zeros in a ``mask'' vector, leaving us with, in this
7405example, a vector of maximum @expr{x} values.
7406
7407The built-in @kbd{a X} command maximizes a function using more
7408efficient methods. Just for illustration, let's use @kbd{a X}
7409to maximize @samp{besJ(1,x)} over this same interval.
7410
7411@smallexample
7412@group
74132: besJ(1, x) 1: [1.84115, 0.581865]
74141: [0 .. 5] .
7415 .
7416
7417' besJ(1,x), [0..5] @key{RET} a X x @key{RET}
7418@end group
7419@end smallexample
7420
7421@noindent
7422The output from @kbd{a X} is a vector containing the value of @expr{x}
7423that maximizes the function, and the function's value at that maximum.
7424As you can see, our simple search got quite close to the right answer.
7425
7426@node List Answer 9, List Answer 10, List Answer 8, Answers to Exercises
7427@subsection List Tutorial Exercise 9
7428
7429@noindent
7430Step one is to convert our integer into vector notation.
7431
7432@smallexample
7433@group
74341: 25129925999 3: 25129925999
7435 . 2: 10
7436 1: [11, 10, 9, ..., 1, 0]
7437 .
7438
7439 25129925999 @key{RET} 10 @key{RET} 12 @key{RET} v x 12 @key{RET} -
7440
7441@end group
7442@end smallexample
7443@noindent
7444@smallexample
7445@group
74461: 25129925999 1: [0, 2, 25, 251, 2512, ... ]
74472: [100000000000, ... ] .
7448 .
7449
7450 V M ^ s 1 V M \
7451@end group
7452@end smallexample
7453
7454@noindent
7455(Recall, the @kbd{\} command computes an integer quotient.)
7456
7457@smallexample
7458@group
74591: [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
7460 .
7461
7462 10 V M % s 2
7463@end group
7464@end smallexample
7465
7466Next we must increment this number. This involves adding one to
7467the last digit, plus handling carries. There is a carry to the
7468left out of a digit if that digit is a nine and all the digits to
7469the right of it are nines.
7470
7471@smallexample
7472@group
74731: [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1] 1: [1, 1, 1, 0, 0, 1, ... ]
7474 . .
7475
7476 9 V M a = v v
7477
7478@end group
7479@end smallexample
7480@noindent
7481@smallexample
7482@group
74831: [1, 1, 1, 0, 0, 0, ... ] 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
7484 . .
7485
7486 V U * v v 1 |
7487@end group
7488@end smallexample
7489
7490@noindent
7491Accumulating @kbd{*} across a vector of ones and zeros will preserve
7492only the initial run of ones. These are the carries into all digits
7493except the rightmost digit. Concatenating a one on the right takes
7494care of aligning the carries properly, and also adding one to the
7495rightmost digit.
7496
7497@smallexample
7498@group
74992: [0, 0, 0, 0, ... ] 1: [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
75001: [0, 0, 2, 5, ... ] .
7501 .
7502
7503 0 r 2 | V M + 10 V M %
7504@end group
7505@end smallexample
7506
7507@noindent
7508Here we have concatenated 0 to the @emph{left} of the original number;
7509this takes care of shifting the carries by one with respect to the
7510digits that generated them.
7511
7512Finally, we must convert this list back into an integer.
7513
7514@smallexample
7515@group
75163: [0, 0, 2, 5, ... ] 2: [0, 0, 2, 5, ... ]
75172: 1000000000000 1: [1000000000000, 100000000000, ... ]
75181: [100000000000, ... ] .
7519 .
7520
7521 10 @key{RET} 12 ^ r 1 |
7522
7523@end group
7524@end smallexample
7525@noindent
7526@smallexample
7527@group
75281: [0, 0, 20000000000, 5000000000, ... ] 1: 25129926000
7529 . .
7530
7531 V M * V R +
7532@end group
7533@end smallexample
7534
7535@noindent
7536Another way to do this final step would be to reduce the formula
7537@w{@samp{10 $$ + $}} across the vector of digits.
7538
7539@smallexample
7540@group
75411: [0, 0, 2, 5, ... ] 1: 25129926000
7542 . .
7543
7544 V R ' 10 $$ + $ @key{RET}
7545@end group
7546@end smallexample
7547
7548@node List Answer 10, List Answer 11, List Answer 9, Answers to Exercises
7549@subsection List Tutorial Exercise 10
7550
7551@noindent
7552For the list @expr{[a, b, c, d]}, the result is @expr{((a = b) = c) = d},
7553which will compare @expr{a} and @expr{b} to produce a 1 or 0, which is
7554then compared with @expr{c} to produce another 1 or 0, which is then
7555compared with @expr{d}. This is not at all what Joe wanted.
7556
7557Here's a more correct method:
7558
7559@smallexample
7560@group
75611: [7, 7, 7, 8, 7] 2: [7, 7, 7, 8, 7]
7562 . 1: 7
7563 .
7564
7565 ' [7,7,7,8,7] @key{RET} @key{RET} v r 1 @key{RET}
7566
7567@end group
7568@end smallexample
7569@noindent
7570@smallexample
7571@group
75721: [1, 1, 1, 0, 1] 1: 0
7573 . .
7574
7575 V M a = V R *
7576@end group
7577@end smallexample
7578
7579@node List Answer 11, List Answer 12, List Answer 10, Answers to Exercises
7580@subsection List Tutorial Exercise 11
7581
7582@noindent
7583The circle of unit radius consists of those points @expr{(x,y)} for which
7584@expr{x^2 + y^2 < 1}. We start by generating a vector of @expr{x^2}
7585and a vector of @expr{y^2}.
7586
7587We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7588commands.
7589
7590@smallexample
7591@group
75922: [2., 2., ..., 2.] 2: [2., 2., ..., 2.]
75931: [2., 2., ..., 2.] 1: [1.16, 1.98, ..., 0.81]
7594 . .
7595
7596 v . t . 2. v b 100 @key{RET} @key{RET} V M k r
7597
7598@end group
7599@end smallexample
7600@noindent
7601@smallexample
7602@group
76032: [2., 2., ..., 2.] 1: [0.026, 0.96, ..., 0.036]
76041: [0.026, 0.96, ..., 0.036] 2: [0.53, 0.81, ..., 0.094]
7605 . .
7606
7607 1 - 2 V M ^ @key{TAB} V M k r 1 - 2 V M ^
7608@end group
7609@end smallexample
7610
7611Now we sum the @expr{x^2} and @expr{y^2} values, compare with 1 to
7612get a vector of 1/0 truth values, then sum the truth values.
7613
7614@smallexample
7615@group
76161: [0.56, 1.78, ..., 0.13] 1: [1, 0, ..., 1] 1: 84
7617 . . .
7618
7619 + 1 V M a < V R +
7620@end group
7621@end smallexample
7622
7623@noindent
7624The ratio @expr{84/100} should approximate the ratio @cpiover{4}.
7625
7626@smallexample
7627@group
76281: 0.84 1: 3.36 2: 3.36 1: 1.0695
7629 . . 1: 3.14159 .
7630
7631 100 / 4 * P /
7632@end group
7633@end smallexample
7634
7635@noindent
7636Our estimate, 3.36, is off by about 7%. We could get a better estimate
7637by taking more points (say, 1000), but it's clear that this method is
7638not very efficient!
7639
7640(Naturally, since this example uses random numbers your own answer
7641will be slightly different from the one shown here!)
7642
7643If you typed @kbd{v .} and @kbd{t .} before, type them again to
7644return to full-sized display of vectors.
7645
7646@node List Answer 12, List Answer 13, List Answer 11, Answers to Exercises
7647@subsection List Tutorial Exercise 12
7648
7649@noindent
7650This problem can be made a lot easier by taking advantage of some
7651symmetries. First of all, after some thought it's clear that the
7652@expr{y} axis can be ignored altogether. Just pick a random @expr{x}
7653component for one end of the match, pick a random direction
7654@texline @math{\theta},
7655@infoline @expr{theta},
7656and see if @expr{x} and
7657@texline @math{x + \cos \theta}
7658@infoline @expr{x + cos(theta)}
7659(which is the @expr{x} coordinate of the other endpoint) cross a line.
7660The lines are at integer coordinates, so this happens when the two
7661numbers surround an integer.
7662
7663Since the two endpoints are equivalent, we may as well choose the leftmost
7664of the two endpoints as @expr{x}. Then @expr{theta} is an angle pointing
7665to the right, in the range -90 to 90 degrees. (We could use radians, but
7666it would feel like cheating to refer to @cpiover{2} radians while trying
7667to estimate @cpi{}!)
7668
7669In fact, since the field of lines is infinite we can choose the
7670coordinates 0 and 1 for the lines on either side of the leftmost
7671endpoint. The rightmost endpoint will be between 0 and 1 if the
7672match does not cross a line, or between 1 and 2 if it does. So:
7673Pick random @expr{x} and
7674@texline @math{\theta},
7675@infoline @expr{theta},
7676compute
7677@texline @math{x + \cos \theta},
7678@infoline @expr{x + cos(theta)},
7679and count how many of the results are greater than one. Simple!
7680
7681We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7682commands.
7683
7684@smallexample
7685@group
76861: [0.52, 0.71, ..., 0.72] 2: [0.52, 0.71, ..., 0.72]
7687 . 1: [78.4, 64.5, ..., -42.9]
7688 .
7689
7690v . t . 1. v b 100 @key{RET} V M k r 180. v b 100 @key{RET} V M k r 90 -
7691@end group
7692@end smallexample
7693
7694@noindent
7695(The next step may be slow, depending on the speed of your computer.)
7696
7697@smallexample
7698@group
76992: [0.52, 0.71, ..., 0.72] 1: [0.72, 1.14, ..., 1.45]
77001: [0.20, 0.43, ..., 0.73] .
7701 .
7702
7703 m d V M C +
7704
7705@end group
7706@end smallexample
7707@noindent
7708@smallexample
7709@group
77101: [0, 1, ..., 1] 1: 0.64 1: 3.125
7711 . . .
7712
7713 1 V M a > V R + 100 / 2 @key{TAB} /
7714@end group
7715@end smallexample
7716
7717Let's try the third method, too. We'll use random integers up to
7718one million. The @kbd{k r} command with an integer argument picks
7719a random integer.
7720
7721@smallexample
7722@group
77232: [1000000, 1000000, ..., 1000000] 2: [78489, 527587, ..., 814975]
77241: [1000000, 1000000, ..., 1000000] 1: [324014, 358783, ..., 955450]
7725 . .
7726
7727 1000000 v b 100 @key{RET} @key{RET} V M k r @key{TAB} V M k r
7728
7729@end group
7730@end smallexample
7731@noindent
7732@smallexample
7733@group
77341: [1, 1, ..., 25] 1: [1, 1, ..., 0] 1: 0.56
7735 . . .
7736
7737 V M k g 1 V M a = V R + 100 /
7738
7739@end group
7740@end smallexample
7741@noindent
7742@smallexample
7743@group
77441: 10.714 1: 3.273
7745 . .
7746
7747 6 @key{TAB} / Q
7748@end group
7749@end smallexample
7750
7751For a proof of this property of the GCD function, see section 4.5.2,
7752exercise 10, of Knuth's @emph{Art of Computer Programming}, volume II.
7753
7754If you typed @kbd{v .} and @kbd{t .} before, type them again to
7755return to full-sized display of vectors.
7756
7757@node List Answer 13, List Answer 14, List Answer 12, Answers to Exercises
7758@subsection List Tutorial Exercise 13
7759
7760@noindent
7761First, we put the string on the stack as a vector of ASCII codes.
7762
7763@smallexample
7764@group
77651: [84, 101, 115, ..., 51]
7766 .
7767
7768 "Testing, 1, 2, 3 @key{RET}
7769@end group
7770@end smallexample
7771
7772@noindent
7773Note that the @kbd{"} key, like @kbd{$}, initiates algebraic entry so
7774there was no need to type an apostrophe. Also, Calc didn't mind that
7775we omitted the closing @kbd{"}. (The same goes for all closing delimiters
7776like @kbd{)} and @kbd{]} at the end of a formula.
7777
7778We'll show two different approaches here. In the first, we note that
7779if the input vector is @expr{[a, b, c, d]}, then the hash code is
7780@expr{3 (3 (3a + b) + c) + d = 27a + 9b + 3c + d}. In other words,
7781it's a sum of descending powers of three times the ASCII codes.
7782
7783@smallexample
7784@group
77852: [84, 101, 115, ..., 51] 2: [84, 101, 115, ..., 51]
77861: 16 1: [15, 14, 13, ..., 0]
7787 . .
7788
7789 @key{RET} v l v x 16 @key{RET} -
7790
7791@end group
7792@end smallexample
7793@noindent
7794@smallexample
7795@group
77962: [84, 101, 115, ..., 51] 1: 1960915098 1: 121
77971: [14348907, ..., 1] . .
7798 .
7799
7800 3 @key{TAB} V M ^ * 511 %
7801@end group
7802@end smallexample
7803
7804@noindent
7805Once again, @kbd{*} elegantly summarizes most of the computation.
7806But there's an even more elegant approach: Reduce the formula
7807@kbd{3 $$ + $} across the vector. Recall that this represents a
7808function of two arguments that computes its first argument times three
7809plus its second argument.
7810
7811@smallexample
7812@group
78131: [84, 101, 115, ..., 51] 1: 1960915098
7814 . .
7815
7816 "Testing, 1, 2, 3 @key{RET} V R ' 3$$+$ @key{RET}
7817@end group
7818@end smallexample
7819
7820@noindent
7821If you did the decimal arithmetic exercise, this will be familiar.
7822Basically, we're turning a base-3 vector of digits into an integer,
7823except that our ``digits'' are much larger than real digits.
7824
7825Instead of typing @kbd{511 %} again to reduce the result, we can be
7826cleverer still and notice that rather than computing a huge integer
7827and taking the modulo at the end, we can take the modulo at each step
7828without affecting the result. While this means there are more
7829arithmetic operations, the numbers we operate on remain small so
7830the operations are faster.
7831
7832@smallexample
7833@group
78341: [84, 101, 115, ..., 51] 1: 121
7835 . .
7836
7837 "Testing, 1, 2, 3 @key{RET} V R ' (3$$+$)%511 @key{RET}
7838@end group
7839@end smallexample
7840
7841Why does this work? Think about a two-step computation:
7842@w{@expr{3 (3a + b) + c}}. Taking a result modulo 511 basically means
7843subtracting off enough 511's to put the result in the desired range.
7844So the result when we take the modulo after every step is,
7845
7846@ifnottex
7847@example
78483 (3 a + b - 511 m) + c - 511 n
7849@end example
7850@end ifnottex
7851@tex
7852\turnoffactive
7853\beforedisplay
7854$$ 3 (3 a + b - 511 m) + c - 511 n $$
7855\afterdisplay
7856@end tex
7857
7858@noindent
7859for some suitable integers @expr{m} and @expr{n}. Expanding out by
7860the distributive law yields
7861
7862@ifnottex
7863@example
78649 a + 3 b + c - 511*3 m - 511 n
7865@end example
7866@end ifnottex
7867@tex
7868\turnoffactive
7869\beforedisplay
7870$$ 9 a + 3 b + c - 511\times3 m - 511 n $$
7871\afterdisplay
7872@end tex
7873
7874@noindent
7875The @expr{m} term in the latter formula is redundant because any
7876contribution it makes could just as easily be made by the @expr{n}
7877term. So we can take it out to get an equivalent formula with
7878@expr{n' = 3m + n},
7879
7880@ifnottex
7881@example
78829 a + 3 b + c - 511 n'
7883@end example
7884@end ifnottex
7885@tex
7886\turnoffactive
7887\beforedisplay
7888$$ 9 a + 3 b + c - 511 n' $$
7889\afterdisplay
7890@end tex
7891
7892@noindent
7893which is just the formula for taking the modulo only at the end of
7894the calculation. Therefore the two methods are essentially the same.
7895
7896Later in the tutorial we will encounter @dfn{modulo forms}, which
7897basically automate the idea of reducing every intermediate result
7898modulo some value @var{m}.
7899
7900@node List Answer 14, Types Answer 1, List Answer 13, Answers to Exercises
7901@subsection List Tutorial Exercise 14
7902
7903We want to use @kbd{H V U} to nest a function which adds a random
7904step to an @expr{(x,y)} coordinate. The function is a bit long, but
7905otherwise the problem is quite straightforward.
7906
7907@smallexample
7908@group
79092: [0, 0] 1: [ [ 0, 0 ]
79101: 50 [ 0.4288, -0.1695 ]
7911 . [ -0.4787, -0.9027 ]
7912 ...
7913
7914 [0,0] 50 H V U ' <# + [random(2.0)-1, random(2.0)-1]> @key{RET}
7915@end group
7916@end smallexample
7917
7918Just as the text recommended, we used @samp{< >} nameless function
7919notation to keep the two @code{random} calls from being evaluated
7920before nesting even begins.
7921
7922We now have a vector of @expr{[x, y]} sub-vectors, which by Calc's
7923rules acts like a matrix. We can transpose this matrix and unpack
7924to get a pair of vectors, @expr{x} and @expr{y}, suitable for graphing.
7925
7926@smallexample
7927@group
79282: [ 0, 0.4288, -0.4787, ... ]
79291: [ 0, -0.1696, -0.9027, ... ]
7930 .
7931
7932 v t v u g f
7933@end group
7934@end smallexample
7935
7936Incidentally, because the @expr{x} and @expr{y} are completely
7937independent in this case, we could have done two separate commands
7938to create our @expr{x} and @expr{y} vectors of numbers directly.
7939
7940To make a random walk of unit steps, we note that @code{sincos} of
7941a random direction exactly gives us an @expr{[x, y]} step of unit
7942length; in fact, the new nesting function is even briefer, though
7943we might want to lower the precision a bit for it.
7944
7945@smallexample
7946@group
79472: [0, 0] 1: [ [ 0, 0 ]
79481: 50 [ 0.1318, 0.9912 ]
7949 . [ -0.5965, 0.3061 ]
7950 ...
7951
7952 [0,0] 50 m d p 6 @key{RET} H V U ' <# + sincos(random(360.0))> @key{RET}
7953@end group
7954@end smallexample
7955
7956Another @kbd{v t v u g f} sequence will graph this new random walk.
7957
7958An interesting twist on these random walk functions would be to use
7959complex numbers instead of 2-vectors to represent points on the plane.
7960In the first example, we'd use something like @samp{random + random*(0,1)},
7961and in the second we could use polar complex numbers with random phase
7962angles. (This exercise was first suggested in this form by Randal
7963Schwartz.)
7964
7965@node Types Answer 1, Types Answer 2, List Answer 14, Answers to Exercises
7966@subsection Types Tutorial Exercise 1
7967
7968@noindent
7969If the number is the square root of @cpi{} times a rational number,
7970then its square, divided by @cpi{}, should be a rational number.
7971
7972@smallexample
7973@group
79741: 1.26508260337 1: 0.509433962268 1: 2486645810:4881193627
7975 . . .
7976
7977 2 ^ P / c F
7978@end group
7979@end smallexample
7980
7981@noindent
7982Technically speaking this is a rational number, but not one that is
7983likely to have arisen in the original problem. More likely, it just
7984happens to be the fraction which most closely represents some
7985irrational number to within 12 digits.
7986
7987But perhaps our result was not quite exact. Let's reduce the
7988precision slightly and try again:
7989
7990@smallexample
7991@group
79921: 0.509433962268 1: 27:53
7993 . .
7994
7995 U p 10 @key{RET} c F
7996@end group
7997@end smallexample
7998
7999@noindent
8000Aha! It's unlikely that an irrational number would equal a fraction
8001this simple to within ten digits, so our original number was probably
8002@texline @math{\sqrt{27 \pi / 53}}.
8003@infoline @expr{sqrt(27 pi / 53)}.
8004
8005Notice that we didn't need to re-round the number when we reduced the
8006precision. Remember, arithmetic operations always round their inputs
8007to the current precision before they begin.
8008
8009@node Types Answer 2, Types Answer 3, Types Answer 1, Answers to Exercises
8010@subsection Types Tutorial Exercise 2
8011
8012@noindent
8013@samp{inf / inf = nan}. Perhaps @samp{1} is the ``obvious'' answer.
8014But if @w{@samp{17 inf = inf}}, then @samp{17 inf / inf = inf / inf = 17}, too.
8015
8016@samp{exp(inf) = inf}. It's tempting to say that the exponential
8017of infinity must be ``bigger'' than ``regular'' infinity, but as
8018far as Calc is concerned all infinities are as just as big.
8019In other words, as @expr{x} goes to infinity, @expr{e^x} also goes
8020to infinity, but the fact the @expr{e^x} grows much faster than
8021@expr{x} is not relevant here.
8022
8023@samp{exp(-inf) = 0}. Here we have a finite answer even though
8024the input is infinite.
8025
8026@samp{sqrt(-inf) = (0, 1) inf}. Remember that @expr{(0, 1)}
8027represents the imaginary number @expr{i}. Here's a derivation:
8028@samp{sqrt(-inf) = @w{sqrt((-1) * inf)} = sqrt(-1) * sqrt(inf)}.
8029The first part is, by definition, @expr{i}; the second is @code{inf}
8030because, once again, all infinities are the same size.
8031
8032@samp{sqrt(uinf) = uinf}. In fact, we do know something about the
8033direction because @code{sqrt} is defined to return a value in the
8034right half of the complex plane. But Calc has no notation for this,
8035so it settles for the conservative answer @code{uinf}.
8036
8037@samp{abs(uinf) = inf}. No matter which direction @expr{x} points,
8038@samp{abs(x)} always points along the positive real axis.
8039
8040@samp{ln(0) = -inf}. Here we have an infinite answer to a finite
8041input. As in the @expr{1 / 0} case, Calc will only use infinities
8042here if you have turned on Infinite mode. Otherwise, it will
8043treat @samp{ln(0)} as an error.
8044
8045@node Types Answer 3, Types Answer 4, Types Answer 2, Answers to Exercises
8046@subsection Types Tutorial Exercise 3
8047
8048@noindent
8049We can make @samp{inf - inf} be any real number we like, say,
8050@expr{a}, just by claiming that we added @expr{a} to the first
8051infinity but not to the second. This is just as true for complex
8052values of @expr{a}, so @code{nan} can stand for a complex number.
8053(And, similarly, @code{uinf} can stand for an infinity that points
8054in any direction in the complex plane, such as @samp{(0, 1) inf}).
8055
8056In fact, we can multiply the first @code{inf} by two. Surely
8057@w{@samp{2 inf - inf = inf}}, but also @samp{2 inf - inf = inf - inf = nan}.
8058So @code{nan} can even stand for infinity. Obviously it's just
8059as easy to make it stand for minus infinity as for plus infinity.
8060
8061The moral of this story is that ``infinity'' is a slippery fish
8062indeed, and Calc tries to handle it by having a very simple model
8063for infinities (only the direction counts, not the ``size''); but
8064Calc is careful to write @code{nan} any time this simple model is
8065unable to tell what the true answer is.
8066
8067@node Types Answer 4, Types Answer 5, Types Answer 3, Answers to Exercises
8068@subsection Types Tutorial Exercise 4
8069
8070@smallexample
8071@group
80722: 0@@ 47' 26" 1: 0@@ 2' 47.411765"
80731: 17 .
8074 .
8075
8076 0@@ 47' 26" @key{RET} 17 /
8077@end group
8078@end smallexample
8079
8080@noindent
8081The average song length is two minutes and 47.4 seconds.
8082
8083@smallexample
8084@group
80852: 0@@ 2' 47.411765" 1: 0@@ 3' 7.411765" 1: 0@@ 53' 6.000005"
80861: 0@@ 0' 20" . .
8087 .
8088
8089 20" + 17 *
8090@end group
8091@end smallexample
8092
8093@noindent
8094The album would be 53 minutes and 6 seconds long.
8095
8096@node Types Answer 5, Types Answer 6, Types Answer 4, Answers to Exercises
8097@subsection Types Tutorial Exercise 5
8098
8099@noindent
8100Let's suppose it's January 14, 1991. The easiest thing to do is
8101to keep trying 13ths of months until Calc reports a Friday.
8102We can do this by manually entering dates, or by using @kbd{t I}:
8103
8104@smallexample
8105@group
81061: <Wed Feb 13, 1991> 1: <Wed Mar 13, 1991> 1: <Sat Apr 13, 1991>
8107 . . .
8108
8109 ' <2/13> @key{RET} @key{DEL} ' <3/13> @key{RET} t I
8110@end group
8111@end smallexample
8112
8113@noindent
8114(Calc assumes the current year if you don't say otherwise.)
8115
8116This is getting tedious---we can keep advancing the date by typing
8117@kbd{t I} over and over again, but let's automate the job by using
8118vector mapping. The @kbd{t I} command actually takes a second
8119``how-many-months'' argument, which defaults to one. This
8120argument is exactly what we want to map over:
8121
8122@smallexample
8123@group
81242: <Sat Apr 13, 1991> 1: [<Mon May 13, 1991>, <Thu Jun 13, 1991>,
81251: [1, 2, 3, 4, 5, 6] <Sat Jul 13, 1991>, <Tue Aug 13, 1991>,
8126 . <Fri Sep 13, 1991>, <Sun Oct 13, 1991>]
8127 .
8128
8129 v x 6 @key{RET} V M t I
8130@end group
8131@end smallexample
8132
8133@noindent
8134Et voil@`a, September 13, 1991 is a Friday.
8135
8136@smallexample
8137@group
81381: 242
8139 .
8140
8141' <sep 13> - <jan 14> @key{RET}
8142@end group
8143@end smallexample
8144
8145@noindent
8146And the answer to our original question: 242 days to go.
8147
8148@node Types Answer 6, Types Answer 7, Types Answer 5, Answers to Exercises
8149@subsection Types Tutorial Exercise 6
8150
8151@noindent
8152The full rule for leap years is that they occur in every year divisible
8153by four, except that they don't occur in years divisible by 100, except
8154that they @emph{do} in years divisible by 400. We could work out the
8155answer by carefully counting the years divisible by four and the
8156exceptions, but there is a much simpler way that works even if we
8157don't know the leap year rule.
8158
8159Let's assume the present year is 1991. Years have 365 days, except
8160that leap years (whenever they occur) have 366 days. So let's count
8161the number of days between now and then, and compare that to the
8162number of years times 365. The number of extra days we find must be
8163equal to the number of leap years there were.
8164
8165@smallexample
8166@group
81671: <Mon Jan 1, 10001> 2: <Mon Jan 1, 10001> 1: 2925593
8168 . 1: <Tue Jan 1, 1991> .
8169 .
8170
8171 ' <jan 1 10001> @key{RET} ' <jan 1 1991> @key{RET} -
8172
8173@end group
8174@end smallexample
8175@noindent
8176@smallexample
8177@group
81783: 2925593 2: 2925593 2: 2925593 1: 1943
81792: 10001 1: 8010 1: 2923650 .
81801: 1991 . .
8181 .
8182
8183 10001 @key{RET} 1991 - 365 * -
8184@end group
8185@end smallexample
8186
8187@c [fix-ref Date Forms]
8188@noindent
8189There will be 1943 leap years before the year 10001. (Assuming,
8190of course, that the algorithm for computing leap years remains
8191unchanged for that long. @xref{Date Forms}, for some interesting
8192background information in that regard.)
8193
8194@node Types Answer 7, Types Answer 8, Types Answer 6, Answers to Exercises
8195@subsection Types Tutorial Exercise 7
8196
8197@noindent
8198The relative errors must be converted to absolute errors so that
8199@samp{+/-} notation may be used.
8200
8201@smallexample
8202@group
82031: 1. 2: 1.
8204 . 1: 0.2
8205 .
8206
8207 20 @key{RET} .05 * 4 @key{RET} .05 *
8208@end group
8209@end smallexample
8210
8211Now we simply chug through the formula.
8212
8213@smallexample
8214@group
82151: 19.7392088022 1: 394.78 +/- 19.739 1: 6316.5 +/- 706.21
8216 . . .
8217
8218 2 P 2 ^ * 20 p 1 * 4 p .2 @key{RET} 2 ^ *
8219@end group
8220@end smallexample
8221
8222It turns out the @kbd{v u} command will unpack an error form as
8223well as a vector. This saves us some retyping of numbers.
8224
8225@smallexample
8226@group
82273: 6316.5 +/- 706.21 2: 6316.5 +/- 706.21
82282: 6316.5 1: 0.1118
82291: 706.21 .
8230 .
8231
8232 @key{RET} v u @key{TAB} /
8233@end group
8234@end smallexample
8235
8236@noindent
8237Thus the volume is 6316 cubic centimeters, within about 11 percent.
8238
8239@node Types Answer 8, Types Answer 9, Types Answer 7, Answers to Exercises
8240@subsection Types Tutorial Exercise 8
8241
8242@noindent
8243The first answer is pretty simple: @samp{1 / (0 .. 10) = (0.1 .. inf)}.
8244Since a number in the interval @samp{(0 .. 10)} can get arbitrarily
8245close to zero, its reciprocal can get arbitrarily large, so the answer
8246is an interval that effectively means, ``any number greater than 0.1''
8247but with no upper bound.
8248
8249The second answer, similarly, is @samp{1 / (-10 .. 0) = (-inf .. -0.1)}.
8250
8251Calc normally treats division by zero as an error, so that the formula
8252@w{@samp{1 / 0}} is left unsimplified. Our third problem,
8253@w{@samp{1 / [0 .. 10]}}, also (potentially) divides by zero because zero
8254is now a member of the interval. So Calc leaves this one unevaluated, too.
8255
8256If you turn on Infinite mode by pressing @kbd{m i}, you will
8257instead get the answer @samp{[0.1 .. inf]}, which includes infinity
8258as a possible value.
8259
8260The fourth calculation, @samp{1 / (-10 .. 10)}, has the same problem.
8261Zero is buried inside the interval, but it's still a possible value.
8262It's not hard to see that the actual result of @samp{1 / (-10 .. 10)}
8263will be either greater than @mathit{0.1}, or less than @mathit{-0.1}. Thus
8264the interval goes from minus infinity to plus infinity, with a ``hole''
8265in it from @mathit{-0.1} to @mathit{0.1}. Calc doesn't have any way to
8266represent this, so it just reports @samp{[-inf .. inf]} as the answer.
8267It may be disappointing to hear ``the answer lies somewhere between
8268minus infinity and plus infinity, inclusive,'' but that's the best
8269that interval arithmetic can do in this case.
8270
8271@node Types Answer 9, Types Answer 10, Types Answer 8, Answers to Exercises
8272@subsection Types Tutorial Exercise 9
8273
8274@smallexample
8275@group
82761: [-3 .. 3] 2: [-3 .. 3] 2: [0 .. 9]
8277 . 1: [0 .. 9] 1: [-9 .. 9]
8278 . .
8279
8280 [ 3 n .. 3 ] @key{RET} 2 ^ @key{TAB} @key{RET} *
8281@end group
8282@end smallexample
8283
8284@noindent
8285In the first case the result says, ``if a number is between @mathit{-3} and
82863, its square is between 0 and 9.'' The second case says, ``the product
8287of two numbers each between @mathit{-3} and 3 is between @mathit{-9} and 9.''
8288
8289An interval form is not a number; it is a symbol that can stand for
8290many different numbers. Two identical-looking interval forms can stand
8291for different numbers.
8292
8293The same issue arises when you try to square an error form.
8294
8295@node Types Answer 10, Types Answer 11, Types Answer 9, Answers to Exercises
8296@subsection Types Tutorial Exercise 10
8297
8298@noindent
8299Testing the first number, we might arbitrarily choose 17 for @expr{x}.
8300
8301@smallexample
8302@group
83031: 17 mod 811749613 2: 17 mod 811749613 1: 533694123 mod 811749613
8304 . 811749612 .
8305 .
8306
8307 17 M 811749613 @key{RET} 811749612 ^
8308@end group
8309@end smallexample
8310
8311@noindent
8312Since 533694123 is (considerably) different from 1, the number 811749613
8313must not be prime.
8314
8315It's awkward to type the number in twice as we did above. There are
8316various ways to avoid this, and algebraic entry is one. In fact, using
8317a vector mapping operation we can perform several tests at once. Let's
8318use this method to test the second number.
8319
8320@smallexample
8321@group
83222: [17, 42, 100000] 1: [1 mod 15485863, 1 mod ... ]
83231: 15485863 .
8324 .
8325
8326 [17 42 100000] 15485863 @key{RET} V M ' ($$ mod $)^($-1) @key{RET}
8327@end group
8328@end smallexample
8329
8330@noindent
8331The result is three ones (modulo @expr{n}), so it's very probable that
833215485863 is prime. (In fact, this number is the millionth prime.)
8333
8334Note that the functions @samp{($$^($-1)) mod $} or @samp{$$^($-1) % $}
8335would have been hopelessly inefficient, since they would have calculated
8336the power using full integer arithmetic.
8337
8338Calc has a @kbd{k p} command that does primality testing. For small
8339numbers it does an exact test; for large numbers it uses a variant
8340of the Fermat test we used here. You can use @kbd{k p} repeatedly
8341to prove that a large integer is prime with any desired probability.
8342
8343@node Types Answer 11, Types Answer 12, Types Answer 10, Answers to Exercises
8344@subsection Types Tutorial Exercise 11
8345
8346@noindent
8347There are several ways to insert a calculated number into an HMS form.
8348One way to convert a number of seconds to an HMS form is simply to
8349multiply the number by an HMS form representing one second:
8350
8351@smallexample
8352@group
83531: 31415926.5359 2: 31415926.5359 1: 8726@@ 38' 46.5359"
8354 . 1: 0@@ 0' 1" .
8355 .
8356
8357 P 1e7 * 0@@ 0' 1" *
8358
8359@end group
8360@end smallexample
8361@noindent
8362@smallexample
8363@group
83642: 8726@@ 38' 46.5359" 1: 6@@ 6' 2.5359" mod 24@@ 0' 0"
83651: 15@@ 27' 16" mod 24@@ 0' 0" .
8366 .
8367
8368 x time @key{RET} +
8369@end group
8370@end smallexample
8371
8372@noindent
8373It will be just after six in the morning.
8374
8375The algebraic @code{hms} function can also be used to build an
8376HMS form:
8377
8378@smallexample
8379@group
83801: hms(0, 0, 10000000. pi) 1: 8726@@ 38' 46.5359"
8381 . .
8382
8383 ' hms(0, 0, 1e7 pi) @key{RET} =
8384@end group
8385@end smallexample
8386
8387@noindent
8388The @kbd{=} key is necessary to evaluate the symbol @samp{pi} to
8389the actual number 3.14159...
8390
8391@node Types Answer 12, Types Answer 13, Types Answer 11, Answers to Exercises
8392@subsection Types Tutorial Exercise 12
8393
8394@noindent
8395As we recall, there are 17 songs of about 2 minutes and 47 seconds
8396each.
8397
8398@smallexample
8399@group
84002: 0@@ 2' 47" 1: [0@@ 3' 7" .. 0@@ 3' 47"]
84011: [0@@ 0' 20" .. 0@@ 1' 0"] .
8402 .
8403
8404 [ 0@@ 20" .. 0@@ 1' ] +
8405
8406@end group
8407@end smallexample
8408@noindent
8409@smallexample
8410@group
84111: [0@@ 52' 59." .. 1@@ 4' 19."]
8412 .
8413
8414 17 *
8415@end group
8416@end smallexample
8417
8418@noindent
8419No matter how long it is, the album will fit nicely on one CD.
8420
8421@node Types Answer 13, Types Answer 14, Types Answer 12, Answers to Exercises
8422@subsection Types Tutorial Exercise 13
8423
8424@noindent
8425Type @kbd{' 1 yr @key{RET} u c s @key{RET}}. The answer is 31557600 seconds.
8426
8427@node Types Answer 14, Types Answer 15, Types Answer 13, Answers to Exercises
8428@subsection Types Tutorial Exercise 14
8429
8430@noindent
8431How long will it take for a signal to get from one end of the computer
8432to the other?
8433
8434@smallexample
8435@group
84361: m / c 1: 3.3356 ns
8437 . .
8438
8439 ' 1 m / c @key{RET} u c ns @key{RET}
8440@end group
8441@end smallexample
8442
8443@noindent
8444(Recall, @samp{c} is a ``unit'' corresponding to the speed of light.)
8445
8446@smallexample
8447@group
84481: 3.3356 ns 1: 0.81356 ns / ns 1: 0.81356
84492: 4.1 ns . .
8450 .
8451
8452 ' 4.1 ns @key{RET} / u s
8453@end group
8454@end smallexample
8455
8456@noindent
8457Thus a signal could take up to 81 percent of a clock cycle just to
8458go from one place to another inside the computer, assuming the signal
8459could actually attain the full speed of light. Pretty tight!
8460
8461@node Types Answer 15, Algebra Answer 1, Types Answer 14, Answers to Exercises
8462@subsection Types Tutorial Exercise 15
8463
8464@noindent
8465The speed limit is 55 miles per hour on most highways. We want to
8466find the ratio of Sam's speed to the US speed limit.
8467
8468@smallexample
8469@group
84701: 55 mph 2: 55 mph 3: 11 hr mph / yd
8471 . 1: 5 yd / hr .
8472 .
8473
8474 ' 55 mph @key{RET} ' 5 yd/hr @key{RET} /
8475@end group
8476@end smallexample
8477
8478The @kbd{u s} command cancels out these units to get a plain
8479number. Now we take the logarithm base two to find the final
8480answer, assuming that each successive pill doubles his speed.
8481
8482@smallexample
8483@group
84841: 19360. 2: 19360. 1: 14.24
8485 . 1: 2 .
8486 .
8487
8488 u s 2 B
8489@end group
8490@end smallexample
8491
8492@noindent
8493Thus Sam can take up to 14 pills without a worry.
8494
8495@node Algebra Answer 1, Algebra Answer 2, Types Answer 15, Answers to Exercises
8496@subsection Algebra Tutorial Exercise 1
8497
8498@noindent
8499@c [fix-ref Declarations]
8500The result @samp{sqrt(x)^2} is simplified back to @expr{x} by the
8501Calculator, but @samp{sqrt(x^2)} is not. (Consider what happens
8502if @w{@expr{x = -4}}.) If @expr{x} is real, this formula could be
8503simplified to @samp{abs(x)}, but for general complex arguments even
8504that is not safe. (@xref{Declarations}, for a way to tell Calc
8505that @expr{x} is known to be real.)
8506
8507@node Algebra Answer 2, Algebra Answer 3, Algebra Answer 1, Answers to Exercises
8508@subsection Algebra Tutorial Exercise 2
8509
8510@noindent
8511Suppose our roots are @expr{[a, b, c]}. We want a polynomial which
8512is zero when @expr{x} is any of these values. The trivial polynomial
8513@expr{x-a} is zero when @expr{x=a}, so the product @expr{(x-a)(x-b)(x-c)}
8514will do the job. We can use @kbd{a c x} to write this in a more
8515familiar form.
8516
8517@smallexample
8518@group
85191: 34 x - 24 x^3 1: [1.19023, -1.19023, 0]
8520 . .
8521
8522 r 2 a P x @key{RET}
8523
8524@end group
8525@end smallexample
8526@noindent
8527@smallexample
8528@group
85291: [x - 1.19023, x + 1.19023, x] 1: (x - 1.19023) (x + 1.19023) x
8530 . .
8531
8532 V M ' x-$ @key{RET} V R *
8533
8534@end group
8535@end smallexample
8536@noindent
8537@smallexample
8538@group
85391: x^3 - 1.41666 x 1: 34 x - 24 x^3
8540 . .
8541
8542 a c x @key{RET} 24 n * a x
8543@end group
8544@end smallexample
8545
8546@noindent
8547Sure enough, our answer (multiplied by a suitable constant) is the
8548same as the original polynomial.
8549
8550@node Algebra Answer 3, Algebra Answer 4, Algebra Answer 2, Answers to Exercises
8551@subsection Algebra Tutorial Exercise 3
8552
8553@smallexample
8554@group
85551: x sin(pi x) 1: (sin(pi x) - pi x cos(pi x)) / pi^2
8556 . .
8557
8558 ' x sin(pi x) @key{RET} m r a i x @key{RET}
8559
8560@end group
8561@end smallexample
8562@noindent
8563@smallexample
8564@group
85651: [y, 1]
85662: (sin(pi x) - pi x cos(pi x)) / pi^2
8567 .
8568
8569 ' [y,1] @key{RET} @key{TAB}
8570
8571@end group
8572@end smallexample
8573@noindent
8574@smallexample
8575@group
85761: [(sin(pi y) - pi y cos(pi y)) / pi^2, (sin(pi) - pi cos(pi)) / pi^2]
8577 .
8578
8579 V M $ @key{RET}
8580
8581@end group
8582@end smallexample
8583@noindent
8584@smallexample
8585@group
85861: (sin(pi y) - pi y cos(pi y)) / pi^2 + (pi cos(pi) - sin(pi)) / pi^2
8587 .
8588
8589 V R -
8590
8591@end group
8592@end smallexample
8593@noindent
8594@smallexample
8595@group
85961: (sin(3.14159 y) - 3.14159 y cos(3.14159 y)) / 9.8696 - 0.3183
8597 .
8598
8599 =
8600
8601@end group
8602@end smallexample
8603@noindent
8604@smallexample
8605@group
86061: [0., -0.95493, 0.63662, -1.5915, 1.2732]
8607 .
8608
8609 v x 5 @key{RET} @key{TAB} V M $ @key{RET}
8610@end group
8611@end smallexample
8612
8613@node Algebra Answer 4, Rewrites Answer 1, Algebra Answer 3, Answers to Exercises
8614@subsection Algebra Tutorial Exercise 4
8615
8616@noindent
8617The hard part is that @kbd{V R +} is no longer sufficient to add up all
8618the contributions from the slices, since the slices have varying
8619coefficients. So first we must come up with a vector of these
8620coefficients. Here's one way:
8621
8622@smallexample
8623@group
86242: -1 2: 3 1: [4, 2, ..., 4]
86251: [1, 2, ..., 9] 1: [-1, 1, ..., -1] .
8626 . .
8627
8628 1 n v x 9 @key{RET} V M ^ 3 @key{TAB} -
8629
8630@end group
8631@end smallexample
8632@noindent
8633@smallexample
8634@group
86351: [4, 2, ..., 4, 1] 1: [1, 4, 2, ..., 4, 1]
8636 . .
8637
8638 1 | 1 @key{TAB} |
8639@end group
8640@end smallexample
8641
8642@noindent
8643Now we compute the function values. Note that for this method we need
8644eleven values, including both endpoints of the desired interval.
8645
8646@smallexample
8647@group
86482: [1, 4, 2, ..., 4, 1]
86491: [1, 1.1, 1.2, ... , 1.8, 1.9, 2.]
8650 .
8651
8652 11 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
8653
8654@end group
8655@end smallexample
8656@noindent
8657@smallexample
8658@group
86592: [1, 4, 2, ..., 4, 1]
86601: [0., 0.084941, 0.16993, ... ]
8661 .
8662
8663 ' sin(x) ln(x) @key{RET} m r p 5 @key{RET} V M $ @key{RET}
8664@end group
8665@end smallexample
8666
8667@noindent
8668Once again this calls for @kbd{V M * V R +}; a simple @kbd{*} does the
8669same thing.
8670
8671@smallexample
8672@group
86731: 11.22 1: 1.122 1: 0.374
8674 . . .
8675
8676 * .1 * 3 /
8677@end group
8678@end smallexample
8679
8680@noindent
8681Wow! That's even better than the result from the Taylor series method.
8682
8683@node Rewrites Answer 1, Rewrites Answer 2, Algebra Answer 4, Answers to Exercises
8684@subsection Rewrites Tutorial Exercise 1
8685
8686@noindent
8687We'll use Big mode to make the formulas more readable.
8688
8689@smallexample
8690@group
8691 ___
8692 2 + V 2
86931: (2 + sqrt(2)) / (1 + sqrt(2)) 1: --------
8694 . ___
8695 1 + V 2
8696
8697 .
8698
8699 ' (2+sqrt(2)) / (1+sqrt(2)) @key{RET} d B
8700@end group
8701@end smallexample
8702
8703@noindent
8704Multiplying by the conjugate helps because @expr{(a+b) (a-b) = a^2 - b^2}.
8705
8706@smallexample
8707@group
8708 ___ ___
87091: (2 + V 2 ) (V 2 - 1)
8710 .
8711
8712 a r a/(b+c) := a*(b-c) / (b^2-c^2) @key{RET}
8713
8714@end group
8715@end smallexample
8716@noindent
8717@smallexample
8718@group
8719 ___ ___
87201: 2 + V 2 - 2 1: V 2
8721 . .
8722
8723 a r a*(b+c) := a*b + a*c a s
8724@end group
8725@end smallexample
8726
8727@noindent
8728(We could have used @kbd{a x} instead of a rewrite rule for the
8729second step.)
8730
8731The multiply-by-conjugate rule turns out to be useful in many
8732different circumstances, such as when the denominator involves
8733sines and cosines or the imaginary constant @code{i}.
8734
8735@node Rewrites Answer 2, Rewrites Answer 3, Rewrites Answer 1, Answers to Exercises
8736@subsection Rewrites Tutorial Exercise 2
8737
8738@noindent
8739Here is the rule set:
8740
8741@smallexample
8742@group
8743[ fib(n) := fib(n, 1, 1) :: integer(n) :: n >= 1,
8744 fib(1, x, y) := x,
8745 fib(n, x, y) := fib(n-1, y, x+y) ]
8746@end group
8747@end smallexample
8748
8749@noindent
8750The first rule turns a one-argument @code{fib} that people like to write
8751into a three-argument @code{fib} that makes computation easier. The
8752second rule converts back from three-argument form once the computation
8753is done. The third rule does the computation itself. It basically
8754says that if @expr{x} and @expr{y} are two consecutive Fibonacci numbers,
8755then @expr{y} and @expr{x+y} are the next (overlapping) pair of Fibonacci
8756numbers.
8757
8758Notice that because the number @expr{n} was ``validated'' by the
8759conditions on the first rule, there is no need to put conditions on
8760the other rules because the rule set would never get that far unless
8761the input were valid. That further speeds computation, since no
8762extra conditions need to be checked at every step.
8763
8764Actually, a user with a nasty sense of humor could enter a bad
8765three-argument @code{fib} call directly, say, @samp{fib(0, 1, 1)},
8766which would get the rules into an infinite loop. One thing that would
8767help keep this from happening by accident would be to use something like
8768@samp{ZzFib} instead of @code{fib} as the name of the three-argument
8769function.
8770
8771@node Rewrites Answer 3, Rewrites Answer 4, Rewrites Answer 2, Answers to Exercises
8772@subsection Rewrites Tutorial Exercise 3
8773
8774@noindent
8775He got an infinite loop. First, Calc did as expected and rewrote
8776@w{@samp{2 + 3 x}} to @samp{f(2, 3, x)}. Then it looked for ways to
8777apply the rule again, and found that @samp{f(2, 3, x)} looks like
8778@samp{a + b x} with @w{@samp{a = 0}} and @samp{b = 1}, so it rewrote to
8779@samp{f(0, 1, f(2, 3, x))}. It then wrapped another @samp{f(0, 1, ...)}
8780around that, and so on, ad infinitum. Joe should have used @kbd{M-1 a r}
8781to make sure the rule applied only once.
8782
8783(Actually, even the first step didn't work as he expected. What Calc
8784really gives for @kbd{M-1 a r} in this situation is @samp{f(3 x, 1, 2)},
8785treating 2 as the ``variable,'' and @samp{3 x} as a constant being added
8786to it. While this may seem odd, it's just as valid a solution as the
8787``obvious'' one. One way to fix this would be to add the condition
8788@samp{:: variable(x)} to the rule, to make sure the thing that matches
8789@samp{x} is indeed a variable, or to change @samp{x} to @samp{quote(x)}
8790on the lefthand side, so that the rule matches the actual variable
8791@samp{x} rather than letting @samp{x} stand for something else.)
8792
8793@node Rewrites Answer 4, Rewrites Answer 5, Rewrites Answer 3, Answers to Exercises
8794@subsection Rewrites Tutorial Exercise 4
8795
8796@noindent
8797@ignore
8798@starindex
8799@end ignore
8800@tindex seq
8801Here is a suitable set of rules to solve the first part of the problem:
8802
8803@smallexample
8804@group
8805[ seq(n, c) := seq(n/2, c+1) :: n%2 = 0,
8806 seq(n, c) := seq(3n+1, c+1) :: n%2 = 1 :: n > 1 ]
8807@end group
8808@end smallexample
8809
8810Given the initial formula @samp{seq(6, 0)}, application of these
8811rules produces the following sequence of formulas:
8812
8813@example
8814seq( 3, 1)
8815seq(10, 2)
8816seq( 5, 3)
8817seq(16, 4)
8818seq( 8, 5)
8819seq( 4, 6)
8820seq( 2, 7)
8821seq( 1, 8)
8822@end example
8823
8824@noindent
8825whereupon neither of the rules match, and rewriting stops.
8826
8827We can pretty this up a bit with a couple more rules:
8828
8829@smallexample
8830@group
8831[ seq(n) := seq(n, 0),
8832 seq(1, c) := c,
8833 ... ]
8834@end group
8835@end smallexample
8836
8837@noindent
8838Now, given @samp{seq(6)} as the starting configuration, we get 8
8839as the result.
8840
8841The change to return a vector is quite simple:
8842
8843@smallexample
8844@group
8845[ seq(n) := seq(n, []) :: integer(n) :: n > 0,
8846 seq(1, v) := v | 1,
8847 seq(n, v) := seq(n/2, v | n) :: n%2 = 0,
8848 seq(n, v) := seq(3n+1, v | n) :: n%2 = 1 ]
8849@end group
8850@end smallexample
8851
8852@noindent
8853Given @samp{seq(6)}, the result is @samp{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
8854
8855Notice that the @expr{n > 1} guard is no longer necessary on the last
8856rule since the @expr{n = 1} case is now detected by another rule.
8857But a guard has been added to the initial rule to make sure the
8858initial value is suitable before the computation begins.
8859
8860While still a good idea, this guard is not as vitally important as it
8861was for the @code{fib} function, since calling, say, @samp{seq(x, [])}
8862will not get into an infinite loop. Calc will not be able to prove
8863the symbol @samp{x} is either even or odd, so none of the rules will
8864apply and the rewrites will stop right away.
8865
8866@node Rewrites Answer 5, Rewrites Answer 6, Rewrites Answer 4, Answers to Exercises
8867@subsection Rewrites Tutorial Exercise 5
8868
8869@noindent
8870@ignore
8871@starindex
8872@end ignore
8873@tindex nterms
8874If @expr{x} is the sum @expr{a + b}, then `@tfn{nterms(}@var{x}@tfn{)}' must
8875be `@tfn{nterms(}@var{a}@tfn{)}' plus `@tfn{nterms(}@var{b}@tfn{)}'. If @expr{x}
8876is not a sum, then `@tfn{nterms(}@var{x}@tfn{)}' = 1.
8877
8878@smallexample
8879@group
8880[ nterms(a + b) := nterms(a) + nterms(b),
8881 nterms(x) := 1 ]
8882@end group
8883@end smallexample
8884
8885@noindent
8886Here we have taken advantage of the fact that earlier rules always
8887match before later rules; @samp{nterms(x)} will only be tried if we
8888already know that @samp{x} is not a sum.
8889
8890@node Rewrites Answer 6, Programming Answer 1, Rewrites Answer 5, Answers to Exercises
8891@subsection Rewrites Tutorial Exercise 6
8892
8893@noindent
8894Here is a rule set that will do the job:
8895
8896@smallexample
8897@group
8898[ a*(b + c) := a*b + a*c,
8899 opt(a) O(x^n) + opt(b) O(x^m) := O(x^n) :: n <= m
8900 :: constant(a) :: constant(b),
8901 opt(a) O(x^n) + opt(b) x^m := O(x^n) :: n <= m
8902 :: constant(a) :: constant(b),
8903 a O(x^n) := O(x^n) :: constant(a),
8904 x^opt(m) O(x^n) := O(x^(n+m)),
8905 O(x^n) O(x^m) := O(x^(n+m)) ]
8906@end group
8907@end smallexample
8908
8909If we really want the @kbd{+} and @kbd{*} keys to operate naturally
8910on power series, we should put these rules in @code{EvalRules}. For
8911testing purposes, it is better to put them in a different variable,
8912say, @code{O}, first.
8913
8914The first rule just expands products of sums so that the rest of the
8915rules can assume they have an expanded-out polynomial to work with.
8916Note that this rule does not mention @samp{O} at all, so it will
8917apply to any product-of-sum it encounters---this rule may surprise
8918you if you put it into @code{EvalRules}!
8919
8920In the second rule, the sum of two O's is changed to the smaller O.
8921The optional constant coefficients are there mostly so that
8922@samp{O(x^2) - O(x^3)} and @samp{O(x^3) - O(x^2)} are handled
8923as well as @samp{O(x^2) + O(x^3)}.
8924
8925The third rule absorbs higher powers of @samp{x} into O's.
8926
8927The fourth rule says that a constant times a negligible quantity
8928is still negligible. (This rule will also match @samp{O(x^3) / 4},
8929with @samp{a = 1/4}.)
8930
8931The fifth rule rewrites, for example, @samp{x^2 O(x^3)} to @samp{O(x^5)}.
8932(It is easy to see that if one of these forms is negligible, the other
8933is, too.) Notice the @samp{x^opt(m)} to pick up terms like
8934@w{@samp{x O(x^3)}}. Optional powers will match @samp{x} as @samp{x^1}
8935but not 1 as @samp{x^0}. This turns out to be exactly what we want here.
8936
8937The sixth rule is the corresponding rule for products of two O's.
8938
8939Another way to solve this problem would be to create a new ``data type''
8940that represents truncated power series. We might represent these as
8941function calls @samp{series(@var{coefs}, @var{x})} where @var{coefs} is
8942a vector of coefficients for @expr{x^0}, @expr{x^1}, @expr{x^2}, and so
8943on. Rules would exist for sums and products of such @code{series}
8944objects, and as an optional convenience could also know how to combine a
8945@code{series} object with a normal polynomial. (With this, and with a
8946rule that rewrites @samp{O(x^n)} to the equivalent @code{series} form,
8947you could still enter power series in exactly the same notation as
8948before.) Operations on such objects would probably be more efficient,
8949although the objects would be a bit harder to read.
8950
8951@c [fix-ref Compositions]
8952Some other symbolic math programs provide a power series data type
8953similar to this. Mathematica, for example, has an object that looks
8954like @samp{PowerSeries[@var{x}, @var{x0}, @var{coefs}, @var{nmin},
8955@var{nmax}, @var{den}]}, where @var{x0} is the point about which the
8956power series is taken (we've been assuming this was always zero),
8957and @var{nmin}, @var{nmax}, and @var{den} allow pseudo-power-series
8958with fractional or negative powers. Also, the @code{PowerSeries}
8959objects have a special display format that makes them look like
8960@samp{2 x^2 + O(x^4)} when they are printed out. (@xref{Compositions},
8961for a way to do this in Calc, although for something as involved as
8962this it would probably be better to write the formatting routine
8963in Lisp.)
8964
8965@node Programming Answer 1, Programming Answer 2, Rewrites Answer 6, Answers to Exercises
8966@subsection Programming Tutorial Exercise 1
8967
8968@noindent
8969Just enter the formula @samp{ninteg(sin(t)/t, t, 0, x)}, type
8970@kbd{Z F}, and answer the questions. Since this formula contains two
8971variables, the default argument list will be @samp{(t x)}. We want to
8972change this to @samp{(x)} since @expr{t} is really a dummy variable
8973to be used within @code{ninteg}.
8974
8975The exact keystrokes are @kbd{Z F s Si @key{RET} @key{RET} C-b C-b @key{DEL} @key{DEL} @key{RET} y}.
8976(The @kbd{C-b C-b @key{DEL} @key{DEL}} are what fix the argument list.)
8977
8978@node Programming Answer 2, Programming Answer 3, Programming Answer 1, Answers to Exercises
8979@subsection Programming Tutorial Exercise 2
8980
8981@noindent
8982One way is to move the number to the top of the stack, operate on
8983it, then move it back: @kbd{C-x ( M-@key{TAB} n M-@key{TAB} M-@key{TAB} C-x )}.
8984
8985Another way is to negate the top three stack entries, then negate
8986again the top two stack entries: @kbd{C-x ( M-3 n M-2 n C-x )}.
8987
8988Finally, it turns out that a negative prefix argument causes a
8989command like @kbd{n} to operate on the specified stack entry only,
8990which is just what we want: @kbd{C-x ( M-- 3 n C-x )}.
8991
8992Just for kicks, let's also do it algebraically:
8993@w{@kbd{C-x ( ' -$$$, $$, $ @key{RET} C-x )}}.
8994
8995@node Programming Answer 3, Programming Answer 4, Programming Answer 2, Answers to Exercises
8996@subsection Programming Tutorial Exercise 3
8997
8998@noindent
8999Each of these functions can be computed using the stack, or using
9000algebraic entry, whichever way you prefer:
9001
9002@noindent
9003Computing
9004@texline @math{\displaystyle{\sin x \over x}}:
9005@infoline @expr{sin(x) / x}:
9006
9007Using the stack: @kbd{C-x ( @key{RET} S @key{TAB} / C-x )}.
9008
9009Using algebraic entry: @kbd{C-x ( ' sin($)/$ @key{RET} C-x )}.
9010
9011@noindent
9012Computing the logarithm:
9013
9014Using the stack: @kbd{C-x ( @key{TAB} B C-x )}
9015
9016Using algebraic entry: @kbd{C-x ( ' log($,$$) @key{RET} C-x )}.
9017
9018@noindent
9019Computing the vector of integers:
9020
9021Using the stack: @kbd{C-x ( 1 @key{RET} 1 C-u v x C-x )}. (Recall that
9022@kbd{C-u v x} takes the vector size, starting value, and increment
9023from the stack.)
9024
9025Alternatively: @kbd{C-x ( ~ v x C-x )}. (The @kbd{~} key pops a
9026number from the stack and uses it as the prefix argument for the
9027next command.)
9028
9029Using algebraic entry: @kbd{C-x ( ' index($) @key{RET} C-x )}.
9030
9031@node Programming Answer 4, Programming Answer 5, Programming Answer 3, Answers to Exercises
9032@subsection Programming Tutorial Exercise 4
9033
9034@noindent
9035Here's one way: @kbd{C-x ( @key{RET} V R + @key{TAB} v l / C-x )}.
9036
9037@node Programming Answer 5, Programming Answer 6, Programming Answer 4, Answers to Exercises
9038@subsection Programming Tutorial Exercise 5
9039
9040@smallexample
9041@group
90422: 1 1: 1.61803398502 2: 1.61803398502
90431: 20 . 1: 1.61803398875
9044 . .
9045
9046 1 @key{RET} 20 Z < & 1 + Z > I H P
9047@end group
9048@end smallexample
9049
9050@noindent
9051This answer is quite accurate.
9052
9053@node Programming Answer 6, Programming Answer 7, Programming Answer 5, Answers to Exercises
9054@subsection Programming Tutorial Exercise 6
9055
9056@noindent
9057Here is the matrix:
9058
9059@example
9060[ [ 0, 1 ] * [a, b] = [b, a + b]
9061 [ 1, 1 ] ]
9062@end example
9063
9064@noindent
9065Thus @samp{[0, 1; 1, 1]^n * [1, 1]} computes Fibonacci numbers @expr{n+1}
9066and @expr{n+2}. Here's one program that does the job:
9067
9068@example
9069C-x ( ' [0, 1; 1, 1] ^ ($-1) * [1, 1] @key{RET} v u @key{DEL} C-x )
9070@end example
9071
9072@noindent
9073This program is quite efficient because Calc knows how to raise a
9074matrix (or other value) to the power @expr{n} in only
9075@texline @math{\log_2 n}
9076@infoline @expr{log(n,2)}
9077steps. For example, this program can compute the 1000th Fibonacci
9078number (a 209-digit integer!) in about 10 steps; even though the
9079@kbd{Z < ... Z >} solution had much simpler steps, it would have
9080required so many steps that it would not have been practical.
9081
9082@node Programming Answer 7, Programming Answer 8, Programming Answer 6, Answers to Exercises
9083@subsection Programming Tutorial Exercise 7
9084
9085@noindent
9086The trick here is to compute the harmonic numbers differently, so that
9087the loop counter itself accumulates the sum of reciprocals. We use
9088a separate variable to hold the integer counter.
9089
9090@smallexample
9091@group
90921: 1 2: 1 1: .
9093 . 1: 4
9094 .
9095
9096 1 t 1 1 @key{RET} 4 Z ( t 2 r 1 1 + s 1 & Z )
9097@end group
9098@end smallexample
9099
9100@noindent
9101The body of the loop goes as follows: First save the harmonic sum
9102so far in variable 2. Then delete it from the stack; the for loop
9103itself will take care of remembering it for us. Next, recall the
9104count from variable 1, add one to it, and feed its reciprocal to
9105the for loop to use as the step value. The for loop will increase
9106the ``loop counter'' by that amount and keep going until the
9107loop counter exceeds 4.
9108
9109@smallexample
9110@group
91112: 31 3: 31
91121: 3.99498713092 2: 3.99498713092
9113 . 1: 4.02724519544
9114 .
9115
9116 r 1 r 2 @key{RET} 31 & +
9117@end group
9118@end smallexample
9119
9120Thus we find that the 30th harmonic number is 3.99, and the 31st
9121harmonic number is 4.02.
9122
9123@node Programming Answer 8, Programming Answer 9, Programming Answer 7, Answers to Exercises
9124@subsection Programming Tutorial Exercise 8
9125
9126@noindent
9127The first step is to compute the derivative @expr{f'(x)} and thus
9128the formula
9129@texline @math{\displaystyle{x - {f(x) \over f'(x)}}}.
9130@infoline @expr{x - f(x)/f'(x)}.
9131
9132(Because this definition is long, it will be repeated in concise form
9133below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
9134entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9135keystrokes without executing them. In the following diagrams we'll
9136pretend Calc actually executed the keystrokes as you typed them,
9137just for purposes of illustration.)
9138
9139@smallexample
9140@group
91412: sin(cos(x)) - 0.5 3: 4.5
91421: 4.5 2: sin(cos(x)) - 0.5
9143 . 1: -(sin(x) cos(cos(x)))
9144 .
9145
9146' sin(cos(x))-0.5 @key{RET} 4.5 m r C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET}
9147
9148@end group
9149@end smallexample
9150@noindent
9151@smallexample
9152@group
91532: 4.5
91541: x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x))
9155 .
9156
9157 / ' x @key{RET} @key{TAB} - t 1
9158@end group
9159@end smallexample
9160
9161Now, we enter the loop. We'll use a repeat loop with a 20-repetition
9162limit just in case the method fails to converge for some reason.
9163(Normally, the @w{@kbd{Z /}} command will stop the loop before all 20
9164repetitions are done.)
9165
9166@smallexample
9167@group
91681: 4.5 3: 4.5 2: 4.5
9169 . 2: x + (sin(cos(x)) ... 1: 5.24196456928
9170 1: 4.5 .
9171 .
9172
9173 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
9174@end group
9175@end smallexample
9176
9177This is the new guess for @expr{x}. Now we compare it with the
9178old one to see if we've converged.
9179
9180@smallexample
9181@group
91823: 5.24196 2: 5.24196 1: 5.24196 1: 5.26345856348
91832: 5.24196 1: 0 . .
91841: 4.5 .
9185 .
9186
9187 @key{RET} M-@key{TAB} a = Z / Z > Z ' C-x )
9188@end group
9189@end smallexample
9190
9191The loop converges in just a few steps to this value. To check
9192the result, we can simply substitute it back into the equation.
9193
9194@smallexample
9195@group
91962: 5.26345856348
91971: 0.499999999997
9198 .
9199
9200 @key{RET} ' sin(cos($)) @key{RET}
9201@end group
9202@end smallexample
9203
9204Let's test the new definition again:
9205
9206@smallexample
9207@group
92082: x^2 - 9 1: 3.
92091: 1 .
9210 .
9211
9212 ' x^2-9 @key{RET} 1 X
9213@end group
9214@end smallexample
9215
9216Once again, here's the full Newton's Method definition:
9217
9218@example
9219@group
9220C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET} / ' x @key{RET} @key{TAB} - t 1
9221 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
9222 @key{RET} M-@key{TAB} a = Z /
9223 Z >
9224 Z '
9225C-x )
9226@end group
9227@end example
9228
9229@c [fix-ref Nesting and Fixed Points]
9230It turns out that Calc has a built-in command for applying a formula
9231repeatedly until it converges to a number. @xref{Nesting and Fixed Points},
9232to see how to use it.
9233
9234@c [fix-ref Root Finding]
9235Also, of course, @kbd{a R} is a built-in command that uses Newton's
9236method (among others) to look for numerical solutions to any equation.
9237@xref{Root Finding}.
9238
9239@node Programming Answer 9, Programming Answer 10, Programming Answer 8, Answers to Exercises
9240@subsection Programming Tutorial Exercise 9
9241
9242@noindent
9243The first step is to adjust @expr{z} to be greater than 5. A simple
9244``for'' loop will do the job here. If @expr{z} is less than 5, we
9245reduce the problem using
9246@texline @math{\psi(z) = \psi(z+1) - 1/z}.
9247@infoline @expr{psi(z) = psi(z+1) - 1/z}. We go
9248on to compute
9249@texline @math{\psi(z+1)},
9250@infoline @expr{psi(z+1)},
9251and remember to add back a factor of @expr{-1/z} when we're done. This
9252step is repeated until @expr{z > 5}.
9253
9254(Because this definition is long, it will be repeated in concise form
9255below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
9256entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9257keystrokes without executing them. In the following diagrams we'll
9258pretend Calc actually executed the keystrokes as you typed them,
9259just for purposes of illustration.)
9260
9261@smallexample
9262@group
92631: 1. 1: 1.
9264 . .
9265
9266 1.0 @key{RET} C-x ( Z ` s 1 0 t 2
9267@end group
9268@end smallexample
9269
9270Here, variable 1 holds @expr{z} and variable 2 holds the adjustment
9271factor. If @expr{z < 5}, we use a loop to increase it.
9272
9273(By the way, we started with @samp{1.0} instead of the integer 1 because
9274otherwise the calculation below will try to do exact fractional arithmetic,
9275and will never converge because fractions compare equal only if they
9276are exactly equal, not just equal to within the current precision.)
9277
9278@smallexample
9279@group
92803: 1. 2: 1. 1: 6.
92812: 1. 1: 1 .
92821: 5 .
9283 .
9284
9285 @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9286@end group
9287@end smallexample
9288
9289Now we compute the initial part of the sum:
9290@texline @math{\ln z - {1 \over 2z}}
9291@infoline @expr{ln(z) - 1/2z}
9292minus the adjustment factor.
9293
9294@smallexample
9295@group
92962: 1.79175946923 2: 1.7084261359 1: -0.57490719743
92971: 0.0833333333333 1: 2.28333333333 .
9298 . .
9299
9300 L r 1 2 * & - r 2 -
9301@end group
9302@end smallexample
9303
9304Now we evaluate the series. We'll use another ``for'' loop counting
9305up the value of @expr{2 n}. (Calc does have a summation command,
9306@kbd{a +}, but we'll use loops just to get more practice with them.)
9307
9308@smallexample
9309@group
93103: -0.5749 3: -0.5749 4: -0.5749 2: -0.5749
93112: 2 2: 1:6 3: 1:6 1: 2.3148e-3
93121: 40 1: 2 2: 2 .
9313 . . 1: 36.
9314 .
9315
9316 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
9317
9318@end group
9319@end smallexample
9320@noindent
9321@smallexample
9322@group
93233: -0.5749 3: -0.5772 2: -0.5772 1: -0.577215664892
93242: -0.5749 2: -0.5772 1: 0 .
93251: 2.3148e-3 1: -0.5749 .
9326 . .
9327
9328 @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z / 2 Z ) Z ' C-x )
9329@end group
9330@end smallexample
9331
9332This is the value of
9333@texline @math{-\gamma},
9334@infoline @expr{- gamma},
9335with a slight bit of roundoff error. To get a full 12 digits, let's use
9336a higher precision:
9337
9338@smallexample
9339@group
93402: -0.577215664892 2: -0.577215664892
93411: 1. 1: -0.577215664901532
9342
9343 1. @key{RET} p 16 @key{RET} X
9344@end group
9345@end smallexample
9346
9347Here's the complete sequence of keystrokes:
9348
9349@example
9350@group
9351C-x ( Z ` s 1 0 t 2
9352 @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9353 L r 1 2 * & - r 2 -
9354 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
9355 @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z /
9356 2 Z )
9357 Z '
9358C-x )
9359@end group
9360@end example
9361
9362@node Programming Answer 10, Programming Answer 11, Programming Answer 9, Answers to Exercises
9363@subsection Programming Tutorial Exercise 10
9364
9365@noindent
9366Taking the derivative of a term of the form @expr{x^n} will produce
9367a term like
9368@texline @math{n x^{n-1}}.
9369@infoline @expr{n x^(n-1)}.
9370Taking the derivative of a constant
9371produces zero. From this it is easy to see that the @expr{n}th
9372derivative of a polynomial, evaluated at @expr{x = 0}, will equal the
9373coefficient on the @expr{x^n} term times @expr{n!}.
9374
9375(Because this definition is long, it will be repeated in concise form
9376below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
9377entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9378keystrokes without executing them. In the following diagrams we'll
9379pretend Calc actually executed the keystrokes as you typed them,
9380just for purposes of illustration.)
9381
9382@smallexample
9383@group
93842: 5 x^4 + (x + 1)^2 3: 5 x^4 + (x + 1)^2
93851: 6 2: 0
9386 . 1: 6
9387 .
9388
9389 ' 5 x^4 + (x+1)^2 @key{RET} 6 C-x ( Z ` [ ] t 1 0 @key{TAB}
9390@end group
9391@end smallexample
9392
9393@noindent
9394Variable 1 will accumulate the vector of coefficients.
9395
9396@smallexample
9397@group
93982: 0 3: 0 2: 5 x^4 + ...
93991: 5 x^4 + ... 2: 5 x^4 + ... 1: 1
9400 . 1: 1 .
9401 .
9402
9403 Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
9404@end group
9405@end smallexample
9406
9407@noindent
9408Note that @kbd{s | 1} appends the top-of-stack value to the vector
9409in a variable; it is completely analogous to @kbd{s + 1}. We could
9410have written instead, @kbd{r 1 @key{TAB} | t 1}.
9411
9412@smallexample
9413@group
94141: 20 x^3 + 2 x + 2 1: 0 1: [1, 2, 1, 0, 5, 0, 0]
9415 . . .
9416
9417 a d x @key{RET} 1 Z ) @key{DEL} r 1 Z ' C-x )
9418@end group
9419@end smallexample
9420
9421To convert back, a simple method is just to map the coefficients
9422against a table of powers of @expr{x}.
9423
9424@smallexample
9425@group
94262: [1, 2, 1, 0, 5, 0, 0] 2: [1, 2, 1, 0, 5, 0, 0]
94271: 6 1: [0, 1, 2, 3, 4, 5, 6]
9428 . .
9429
9430 6 @key{RET} 1 + 0 @key{RET} 1 C-u v x
9431
9432@end group
9433@end smallexample
9434@noindent
9435@smallexample
9436@group
94372: [1, 2, 1, 0, 5, 0, 0] 2: 1 + 2 x + x^2 + 5 x^4
94381: [1, x, x^2, x^3, ... ] .
9439 .
9440
9441 ' x @key{RET} @key{TAB} V M ^ *
9442@end group
9443@end smallexample
9444
9445Once again, here are the whole polynomial to/from vector programs:
9446
9447@example
9448@group
9449C-x ( Z ` [ ] t 1 0 @key{TAB}
9450 Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
9451 a d x @key{RET}
9452 1 Z ) r 1
9453 Z '
9454C-x )
9455
9456C-x ( 1 + 0 @key{RET} 1 C-u v x ' x @key{RET} @key{TAB} V M ^ * C-x )
9457@end group
9458@end example
9459
9460@node Programming Answer 11, Programming Answer 12, Programming Answer 10, Answers to Exercises
9461@subsection Programming Tutorial Exercise 11
9462
9463@noindent
9464First we define a dummy program to go on the @kbd{z s} key. The true
9465@w{@kbd{z s}} key is supposed to take two numbers from the stack and
9466return one number, so @key{DEL} as a dummy definition will make
9467sure the stack comes out right.
9468
9469@smallexample
9470@group
94712: 4 1: 4 2: 4
94721: 2 . 1: 2
9473 . .
9474
9475 4 @key{RET} 2 C-x ( @key{DEL} C-x ) Z K s @key{RET} 2
9476@end group
9477@end smallexample
9478
9479The last step replaces the 2 that was eaten during the creation
9480of the dummy @kbd{z s} command. Now we move on to the real
9481definition. The recurrence needs to be rewritten slightly,
9482to the form @expr{s(n,m) = s(n-1,m-1) - (n-1) s(n-1,m)}.
9483
9484(Because this definition is long, it will be repeated in concise form
9485below. You can use @kbd{C-x * m} to load it from there.)
9486
9487@smallexample
9488@group
94892: 4 4: 4 3: 4 2: 4
94901: 2 3: 2 2: 2 1: 2
9491 . 2: 4 1: 0 .
9492 1: 2 .
9493 .
9494
9495 C-x ( M-2 @key{RET} a = Z [ @key{DEL} @key{DEL} 1 Z :
9496
9497@end group
9498@end smallexample
9499@noindent
9500@smallexample
9501@group
95024: 4 2: 4 2: 3 4: 3 4: 3 3: 3
95033: 2 1: 2 1: 2 3: 2 3: 2 2: 2
95042: 2 . . 2: 3 2: 3 1: 3
95051: 0 1: 2 1: 1 .
9506 . . .
9507
9508 @key{RET} 0 a = Z [ @key{DEL} @key{DEL} 0 Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
9509@end group
9510@end smallexample
9511
9512@noindent
9513(Note that the value 3 that our dummy @kbd{z s} produces is not correct;
9514it is merely a placeholder that will do just as well for now.)
9515
9516@smallexample
9517@group
95183: 3 4: 3 3: 3 2: 3 1: -6
95192: 3 3: 3 2: 3 1: 9 .
95201: 2 2: 3 1: 3 .
9521 . 1: 2 .
9522 .
9523
9524 M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
9525
9526@end group
9527@end smallexample
9528@noindent
9529@smallexample
9530@group
95311: -6 2: 4 1: 11 2: 11
9532 . 1: 2 . 1: 11
9533 . .
9534
9535 Z ] Z ] C-x ) Z K s @key{RET} @key{DEL} 4 @key{RET} 2 z s M-@key{RET} k s
9536@end group
9537@end smallexample
9538
9539Even though the result that we got during the definition was highly
9540bogus, once the definition is complete the @kbd{z s} command gets
9541the right answers.
9542
9543Here's the full program once again:
9544
9545@example
9546@group
9547C-x ( M-2 @key{RET} a =
9548 Z [ @key{DEL} @key{DEL} 1
9549 Z : @key{RET} 0 a =
9550 Z [ @key{DEL} @key{DEL} 0
9551 Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
9552 M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
9553 Z ]
9554 Z ]
9555C-x )
9556@end group
9557@end example
9558
9559You can read this definition using @kbd{C-x * m} (@code{read-kbd-macro})
9560followed by @kbd{Z K s}, without having to make a dummy definition
9561first, because @code{read-kbd-macro} doesn't need to execute the
9562definition as it reads it in. For this reason, @code{C-x * m} is often
9563the easiest way to create recursive programs in Calc.
9564
9565@node Programming Answer 12, , Programming Answer 11, Answers to Exercises
9566@subsection Programming Tutorial Exercise 12
9567
9568@noindent
9569This turns out to be a much easier way to solve the problem. Let's
9570denote Stirling numbers as calls of the function @samp{s}.
9571
9572First, we store the rewrite rules corresponding to the definition of
9573Stirling numbers in a convenient variable:
9574
9575@smallexample
9576s e StirlingRules @key{RET}
9577[ s(n,n) := 1 :: n >= 0,
9578 s(n,0) := 0 :: n > 0,
9579 s(n,m) := s(n-1,m-1) - (n-1) s(n-1,m) :: n >= m :: m >= 1 ]
9580C-c C-c
9581@end smallexample
9582
9583Now, it's just a matter of applying the rules:
9584
9585@smallexample
9586@group
95872: 4 1: s(4, 2) 1: 11
95881: 2 . .
9589 .
9590
9591 4 @key{RET} 2 C-x ( ' s($$,$) @key{RET} a r StirlingRules @key{RET} C-x )
9592@end group
9593@end smallexample
9594
9595As in the case of the @code{fib} rules, it would be useful to put these
9596rules in @code{EvalRules} and to add a @samp{:: remember} condition to
9597the last rule.
9598
9599@c This ends the table-of-contents kludge from above:
9600@tex
9601\global\let\chapternofonts=\oldchapternofonts
9602@end tex
9603
9604@c [reference]
9605
9606@node Introduction, Data Types, Tutorial, Top
9607@chapter Introduction
9608
9609@noindent
9610This chapter is the beginning of the Calc reference manual.
9611It covers basic concepts such as the stack, algebraic and
9612numeric entry, undo, numeric prefix arguments, etc.
9613
9614@c [when-split]
9615@c (Chapter 2, the Tutorial, has been printed in a separate volume.)
9616
9617@menu
9618* Basic Commands::
9619* Help Commands::
9620* Stack Basics::
9621* Numeric Entry::
9622* Algebraic Entry::
9623* Quick Calculator::
9624* Prefix Arguments::
9625* Undo::
9626* Error Messages::
9627* Multiple Calculators::
9628* Troubleshooting Commands::
9629@end menu
9630
9631@node Basic Commands, Help Commands, Introduction, Introduction
9632@section Basic Commands
9633
9634@noindent
9635@pindex calc
9636@pindex calc-mode
9637@cindex Starting the Calculator
9638@cindex Running the Calculator
9639To start the Calculator in its standard interface, type @kbd{M-x calc}.
9640By default this creates a pair of small windows, @samp{*Calculator*}
9641and @samp{*Calc Trail*}. The former displays the contents of the
9642Calculator stack and is manipulated exclusively through Calc commands.
9643It is possible (though not usually necessary) to create several Calc
9644mode buffers each of which has an independent stack, undo list, and
9645mode settings. There is exactly one Calc Trail buffer; it records a
9646list of the results of all calculations that have been done. The
9647Calc Trail buffer uses a variant of Calc mode, so Calculator commands
9648still work when the trail buffer's window is selected. It is possible
9649to turn the trail window off, but the @samp{*Calc Trail*} buffer itself
9650still exists and is updated silently. @xref{Trail Commands}.
9651
9652@kindex C-x * c
9653@kindex C-x * *
9654@ignore
9655@mindex @null
9656@end ignore
9657In most installations, the @kbd{C-x * c} key sequence is a more
9658convenient way to start the Calculator. Also, @kbd{C-x * *}
9659is a synonym for @kbd{C-x * c} unless you last used Calc
9660in its Keypad mode.
9661
9662@kindex x
9663@kindex M-x
9664@pindex calc-execute-extended-command
9665Most Calc commands use one or two keystrokes. Lower- and upper-case
9666letters are distinct. Commands may also be entered in full @kbd{M-x} form;
9667for some commands this is the only form. As a convenience, the @kbd{x}
9668key (@code{calc-execute-extended-command})
9669is like @kbd{M-x} except that it enters the initial string @samp{calc-}
9670for you. For example, the following key sequences are equivalent:
9671@kbd{S}, @kbd{M-x calc-sin @key{RET}}, @kbd{x sin @key{RET}}.
9672
3bc88bc9
JB
9673Although Calc is designed to be used from the keyboard, some of
9674Calc's more common commands are available from a menu. In the menu, the
9675arguments to the functions are given by referring to their stack level
9676numbers.
9677
4009494e
GM
9678@cindex Extensions module
9679@cindex @file{calc-ext} module
9680The Calculator exists in many parts. When you type @kbd{C-x * c}, the
9681Emacs ``auto-load'' mechanism will bring in only the first part, which
9682contains the basic arithmetic functions. The other parts will be
9683auto-loaded the first time you use the more advanced commands like trig
9684functions or matrix operations. This is done to improve the response time
9685of the Calculator in the common case when all you need to do is a
9686little arithmetic. If for some reason the Calculator fails to load an
9687extension module automatically, you can force it to load all the
9688extensions by using the @kbd{C-x * L} (@code{calc-load-everything})
9689command. @xref{Mode Settings}.
9690
9691If you type @kbd{M-x calc} or @kbd{C-x * c} with any numeric prefix argument,
9692the Calculator is loaded if necessary, but it is not actually started.
9693If the argument is positive, the @file{calc-ext} extensions are also
9694loaded if necessary. User-written Lisp code that wishes to make use
9695of Calc's arithmetic routines can use @samp{(calc 0)} or @samp{(calc 1)}
9696to auto-load the Calculator.
9697
9698@kindex C-x * b
9699@pindex full-calc
9700If you type @kbd{C-x * b}, then next time you use @kbd{C-x * c} you
9701will get a Calculator that uses the full height of the Emacs screen.
9702When full-screen mode is on, @kbd{C-x * c} runs the @code{full-calc}
9703command instead of @code{calc}. From the Unix shell you can type
9704@samp{emacs -f full-calc} to start a new Emacs specifically for use
9705as a calculator. When Calc is started from the Emacs command line
9706like this, Calc's normal ``quit'' commands actually quit Emacs itself.
9707
9708@kindex C-x * o
9709@pindex calc-other-window
9710The @kbd{C-x * o} command is like @kbd{C-x * c} except that the Calc
9711window is not actually selected. If you are already in the Calc
9712window, @kbd{C-x * o} switches you out of it. (The regular Emacs
9713@kbd{C-x o} command would also work for this, but it has a
9714tendency to drop you into the Calc Trail window instead, which
9715@kbd{C-x * o} takes care not to do.)
9716
9717@ignore
9718@mindex C-x * q
9719@end ignore
9720For one quick calculation, you can type @kbd{C-x * q} (@code{quick-calc})
9721which prompts you for a formula (like @samp{2+3/4}). The result is
9722displayed at the bottom of the Emacs screen without ever creating
9723any special Calculator windows. @xref{Quick Calculator}.
9724
9725@ignore
9726@mindex C-x * k
9727@end ignore
9728Finally, if you are using the X window system you may want to try
9729@kbd{C-x * k} (@code{calc-keypad}) which runs Calc with a
9730``calculator keypad'' picture as well as a stack display. Click on
9731the keys with the mouse to operate the calculator. @xref{Keypad Mode}.
9732
9733@kindex q
9734@pindex calc-quit
9735@cindex Quitting the Calculator
9736@cindex Exiting the Calculator
9737The @kbd{q} key (@code{calc-quit}) exits Calc mode and closes the
9738Calculator's window(s). It does not delete the Calculator buffers.
9739If you type @kbd{M-x calc} again, the Calculator will reappear with the
9740contents of the stack intact. Typing @kbd{C-x * c} or @kbd{C-x * *}
9741again from inside the Calculator buffer is equivalent to executing
9742@code{calc-quit}; you can think of @kbd{C-x * *} as toggling the
9743Calculator on and off.
9744
9745@kindex C-x * x
9746The @kbd{C-x * x} command also turns the Calculator off, no matter which
9747user interface (standard, Keypad, or Embedded) is currently active.
9748It also cancels @code{calc-edit} mode if used from there.
9749
9750@kindex d @key{SPC}
9751@pindex calc-refresh
9752@cindex Refreshing a garbled display
9753@cindex Garbled displays, refreshing
9754The @kbd{d @key{SPC}} key sequence (@code{calc-refresh}) redraws the contents
9755of the Calculator buffer from memory. Use this if the contents of the
9756buffer have been damaged somehow.
9757
9758@ignore
9759@mindex o
9760@end ignore
9761The @kbd{o} key (@code{calc-realign}) moves the cursor back to its
9762``home'' position at the bottom of the Calculator buffer.
9763
9764@kindex <
9765@kindex >
9766@pindex calc-scroll-left
9767@pindex calc-scroll-right
9768@cindex Horizontal scrolling
9769@cindex Scrolling
9770@cindex Wide text, scrolling
9771The @kbd{<} and @kbd{>} keys are bound to @code{calc-scroll-left} and
9772@code{calc-scroll-right}. These are just like the normal horizontal
9773scrolling commands except that they scroll one half-screen at a time by
9774default. (Calc formats its output to fit within the bounds of the
9775window whenever it can.)
9776
9777@kindex @{
9778@kindex @}
9779@pindex calc-scroll-down
9780@pindex calc-scroll-up
9781@cindex Vertical scrolling
9782The @kbd{@{} and @kbd{@}} keys are bound to @code{calc-scroll-down}
9783and @code{calc-scroll-up}. They scroll up or down by one-half the
9784height of the Calc window.
9785
9786@kindex C-x * 0
9787@pindex calc-reset
9788The @kbd{C-x * 0} command (@code{calc-reset}; that's @kbd{C-x *} followed
9789by a zero) resets the Calculator to its initial state. This clears
9790the stack, resets all the modes to their initial values (the values
9791that were saved with @kbd{m m} (@code{calc-save-modes})), clears the
9792caches (@pxref{Caches}), and so on. (It does @emph{not} erase the
9793values of any variables.) With an argument of 0, Calc will be reset to
9794its default state; namely, the modes will be given their default values.
9795With a positive prefix argument, @kbd{C-x * 0} preserves the contents of
9796the stack but resets everything else to its initial state; with a
9797negative prefix argument, @kbd{C-x * 0} preserves the contents of the
9798stack but resets everything else to its default state.
9799
9800@pindex calc-version
9801The @kbd{M-x calc-version} command displays the current version number
9802of Calc and the name of the person who installed it on your system.
9803(This information is also present in the @samp{*Calc Trail*} buffer,
9804and in the output of the @kbd{h h} command.)
9805
9806@node Help Commands, Stack Basics, Basic Commands, Introduction
9807@section Help Commands
9808
9809@noindent
9810@cindex Help commands
9811@kindex ?
9812@pindex calc-help
9813The @kbd{?} key (@code{calc-help}) displays a series of brief help messages.
9814Some keys (such as @kbd{b} and @kbd{d}) are prefix keys, like Emacs'
9815@key{ESC} and @kbd{C-x} prefixes. You can type
9816@kbd{?} after a prefix to see a list of commands beginning with that
9817prefix. (If the message includes @samp{[MORE]}, press @kbd{?} again
9818to see additional commands for that prefix.)
9819
9820@kindex h h
9821@pindex calc-full-help
9822The @kbd{h h} (@code{calc-full-help}) command displays all the @kbd{?}
9823responses at once. When printed, this makes a nice, compact (three pages)
9824summary of Calc keystrokes.
9825
9826In general, the @kbd{h} key prefix introduces various commands that
9827provide help within Calc. Many of the @kbd{h} key functions are
9828Calc-specific analogues to the @kbd{C-h} functions for Emacs help.
9829
9830@kindex h i
9831@kindex C-x * i
9832@kindex i
9833@pindex calc-info
9834The @kbd{h i} (@code{calc-info}) command runs the Emacs Info system
9835to read this manual on-line. This is basically the same as typing
9836@kbd{C-h i} (the regular way to run the Info system), then, if Info
9837is not already in the Calc manual, selecting the beginning of the
9838manual. The @kbd{C-x * i} command is another way to read the Calc
9839manual; it is different from @kbd{h i} in that it works any time,
9840not just inside Calc. The plain @kbd{i} key is also equivalent to
9841@kbd{h i}, though this key is obsolete and may be replaced with a
9842different command in a future version of Calc.
9843
9844@kindex h t
9845@kindex C-x * t
9846@pindex calc-tutorial
9847The @kbd{h t} (@code{calc-tutorial}) command runs the Info system on
9848the Tutorial section of the Calc manual. It is like @kbd{h i},
9849except that it selects the starting node of the tutorial rather
9850than the beginning of the whole manual. (It actually selects the
9851node ``Interactive Tutorial'' which tells a few things about
9852using the Info system before going on to the actual tutorial.)
9853The @kbd{C-x * t} key is equivalent to @kbd{h t} (but it works at
9854all times).
9855
9856@kindex h s
9857@kindex C-x * s
9858@pindex calc-info-summary
9859The @kbd{h s} (@code{calc-info-summary}) command runs the Info system
9860on the Summary node of the Calc manual. @xref{Summary}. The @kbd{C-x * s}
9861key is equivalent to @kbd{h s}.
9862
9863@kindex h k
9864@pindex calc-describe-key
9865The @kbd{h k} (@code{calc-describe-key}) command looks up a key
9866sequence in the Calc manual. For example, @kbd{h k H a S} looks
9867up the documentation on the @kbd{H a S} (@code{calc-solve-for})
9868command. This works by looking up the textual description of
9869the key(s) in the Key Index of the manual, then jumping to the
9870node indicated by the index.
9871
9872Most Calc commands do not have traditional Emacs documentation
9873strings, since the @kbd{h k} command is both more convenient and
9874more instructive. This means the regular Emacs @kbd{C-h k}
9875(@code{describe-key}) command will not be useful for Calc keystrokes.
9876
9877@kindex h c
9878@pindex calc-describe-key-briefly
9879The @kbd{h c} (@code{calc-describe-key-briefly}) command reads a
9880key sequence and displays a brief one-line description of it at
9881the bottom of the screen. It looks for the key sequence in the
9882Summary node of the Calc manual; if it doesn't find the sequence
9883there, it acts just like its regular Emacs counterpart @kbd{C-h c}
9884(@code{describe-key-briefly}). For example, @kbd{h c H a S}
9885gives the description:
9886
9887@smallexample
9888H a S runs calc-solve-for: a `H a S' v => fsolve(a,v) (?=notes)
9889@end smallexample
9890
9891@noindent
9892which means the command @kbd{H a S} or @kbd{H M-x calc-solve-for}
9893takes a value @expr{a} from the stack, prompts for a value @expr{v},
9894then applies the algebraic function @code{fsolve} to these values.
9895The @samp{?=notes} message means you can now type @kbd{?} to see
9896additional notes from the summary that apply to this command.
9897
9898@kindex h f
9899@pindex calc-describe-function
9900The @kbd{h f} (@code{calc-describe-function}) command looks up an
9901algebraic function or a command name in the Calc manual. Enter an
9902algebraic function name to look up that function in the Function
9903Index or enter a command name beginning with @samp{calc-} to look it
9904up in the Command Index. This command will also look up operator
9905symbols that can appear in algebraic formulas, like @samp{%} and
9906@samp{=>}.
9907
9908@kindex h v
9909@pindex calc-describe-variable
9910The @kbd{h v} (@code{calc-describe-variable}) command looks up a
9911variable in the Calc manual. Enter a variable name like @code{pi} or
9912@code{PlotRejects}.
9913
9914@kindex h b
9915@pindex describe-bindings
9916The @kbd{h b} (@code{calc-describe-bindings}) command is just like
9917@kbd{C-h b}, except that only local (Calc-related) key bindings are
9918listed.
9919
9920@kindex h n
9921The @kbd{h n} or @kbd{h C-n} (@code{calc-view-news}) command displays
9922the ``news'' or change history of Calc. This is kept in the file
9923@file{README}, which Calc looks for in the same directory as the Calc
9924source files.
9925
9926@kindex h C-c
9927@kindex h C-d
9928@kindex h C-w
9929The @kbd{h C-c}, @kbd{h C-d}, and @kbd{h C-w} keys display copying,
9930distribution, and warranty information about Calc. These work by
9931pulling up the appropriate parts of the ``Copying'' or ``Reporting
9932Bugs'' sections of the manual.
9933
9934@node Stack Basics, Numeric Entry, Help Commands, Introduction
9935@section Stack Basics
9936
9937@noindent
9938@cindex Stack basics
9939@c [fix-tut RPN Calculations and the Stack]
9940Calc uses RPN notation. If you are not familiar with RPN, @pxref{RPN
9941Tutorial}.
9942
9943To add the numbers 1 and 2 in Calc you would type the keys:
9944@kbd{1 @key{RET} 2 +}.
9945(@key{RET} corresponds to the @key{ENTER} key on most calculators.)
9946The first three keystrokes ``push'' the numbers 1 and 2 onto the stack. The
9947@kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
9948and pushes the result (3) back onto the stack. This number is ready for
9949further calculations: @kbd{5 -} pushes 5 onto the stack, then pops the
99503 and 5, subtracts them, and pushes the result (@mathit{-2}).
9951
9952Note that the ``top'' of the stack actually appears at the @emph{bottom}
9953of the buffer. A line containing a single @samp{.} character signifies
9954the end of the buffer; Calculator commands operate on the number(s)
9955directly above this line. The @kbd{d t} (@code{calc-truncate-stack})
9956command allows you to move the @samp{.} marker up and down in the stack;
9957@pxref{Truncating the Stack}.
9958
9959@kindex d l
9960@pindex calc-line-numbering
9961Stack elements are numbered consecutively, with number 1 being the top of
9962the stack. These line numbers are ordinarily displayed on the lefthand side
9963of the window. The @kbd{d l} (@code{calc-line-numbering}) command controls
9964whether these numbers appear. (Line numbers may be turned off since they
9965slow the Calculator down a bit and also clutter the display.)
9966
9967@kindex o
9968@pindex calc-realign
9969The unshifted letter @kbd{o} (@code{calc-realign}) command repositions
9970the cursor to its top-of-stack ``home'' position. It also undoes any
9971horizontal scrolling in the window. If you give it a numeric prefix
9972argument, it instead moves the cursor to the specified stack element.
9973
9974The @key{RET} (or equivalent @key{SPC}) key is only required to separate
9975two consecutive numbers.
9976(After all, if you typed @kbd{1 2} by themselves the Calculator
9977would enter the number 12.) If you press @key{RET} or @key{SPC} @emph{not}
9978right after typing a number, the key duplicates the number on the top of
9979the stack. @kbd{@key{RET} *} is thus a handy way to square a number.
9980
9981The @key{DEL} key pops and throws away the top number on the stack.
9982The @key{TAB} key swaps the top two objects on the stack.
9983@xref{Stack and Trail}, for descriptions of these and other stack-related
9984commands.
9985
9986@node Numeric Entry, Algebraic Entry, Stack Basics, Introduction
9987@section Numeric Entry
9988
9989@noindent
9990@kindex 0-9
9991@kindex .
9992@kindex e
9993@cindex Numeric entry
9994@cindex Entering numbers
9995Pressing a digit or other numeric key begins numeric entry using the
9996minibuffer. The number is pushed on the stack when you press the @key{RET}
9997or @key{SPC} keys. If you press any other non-numeric key, the number is
9998pushed onto the stack and the appropriate operation is performed. If
9999you press a numeric key which is not valid, the key is ignored.
10000
10001@cindex Minus signs
10002@cindex Negative numbers, entering
10003@kindex _
10004There are three different concepts corresponding to the word ``minus,''
10005typified by @expr{a-b} (subtraction), @expr{-x}
10006(change-sign), and @expr{-5} (negative number). Calc uses three
10007different keys for these operations, respectively:
10008@kbd{-}, @kbd{n}, and @kbd{_} (the underscore). The @kbd{-} key subtracts
10009the two numbers on the top of the stack. The @kbd{n} key changes the sign
10010of the number on the top of the stack or the number currently being entered.
10011The @kbd{_} key begins entry of a negative number or changes the sign of
10012the number currently being entered. The following sequences all enter the
10013number @mathit{-5} onto the stack: @kbd{0 @key{RET} 5 -}, @kbd{5 n @key{RET}},
10014@kbd{5 @key{RET} n}, @kbd{_ 5 @key{RET}}, @kbd{5 _ @key{RET}}.
10015
10016Some other keys are active during numeric entry, such as @kbd{#} for
10017non-decimal numbers, @kbd{:} for fractions, and @kbd{@@} for HMS forms.
10018These notations are described later in this manual with the corresponding
10019data types. @xref{Data Types}.
10020
10021During numeric entry, the only editing key available is @key{DEL}.
10022
10023@node Algebraic Entry, Quick Calculator, Numeric Entry, Introduction
10024@section Algebraic Entry
10025
10026@noindent
10027@kindex '
10028@pindex calc-algebraic-entry
10029@cindex Algebraic notation
10030@cindex Formulas, entering
8dc6104d
JB
10031The @kbd{'} (@code{calc-algebraic-entry}) command can be used to enter
10032calculations in algebraic form. This is accomplished by typing the
10033apostrophe key, ', followed by the expression in standard format:
4009494e
GM
10034
10035@example
10036' 2+3*4 @key{RET}.
10037@end example
10038
10039@noindent
10040This will compute
10041@texline @math{2+(3\times4) = 14}
10042@infoline @expr{2+(3*4) = 14}
10043and push it on the stack. If you wish you can
10044ignore the RPN aspect of Calc altogether and simply enter algebraic
10045expressions in this way. You may want to use @key{DEL} every so often to
10046clear previous results off the stack.
10047
10048You can press the apostrophe key during normal numeric entry to switch
8dc6104d
JB
10049the half-entered number into Algebraic entry mode. One reason to do
10050this would be to fix a typo, as the full Emacs cursor motion and editing
10051keys are available during algebraic entry but not during numeric entry.
4009494e
GM
10052
10053In the same vein, during either numeric or algebraic entry you can
10054press @kbd{`} (backquote) to switch to @code{calc-edit} mode, where
10055you complete your half-finished entry in a separate buffer.
10056@xref{Editing Stack Entries}.
10057
10058@kindex m a
10059@pindex calc-algebraic-mode
10060@cindex Algebraic Mode
10061If you prefer algebraic entry, you can use the command @kbd{m a}
10062(@code{calc-algebraic-mode}) to set Algebraic mode. In this mode,
10063digits and other keys that would normally start numeric entry instead
10064start full algebraic entry; as long as your formula begins with a digit
10065you can omit the apostrophe. Open parentheses and square brackets also
10066begin algebraic entry. You can still do RPN calculations in this mode,
10067but you will have to press @key{RET} to terminate every number:
10068@kbd{2 @key{RET} 3 @key{RET} * 4 @key{RET} +} would accomplish the same
10069thing as @kbd{2*3+4 @key{RET}}.
10070
10071@cindex Incomplete Algebraic Mode
10072If you give a numeric prefix argument like @kbd{C-u} to the @kbd{m a}
10073command, it enables Incomplete Algebraic mode; this is like regular
10074Algebraic mode except that it applies to the @kbd{(} and @kbd{[} keys
10075only. Numeric keys still begin a numeric entry in this mode.
10076
10077@kindex m t
10078@pindex calc-total-algebraic-mode
10079@cindex Total Algebraic Mode
10080The @kbd{m t} (@code{calc-total-algebraic-mode}) gives you an even
10081stronger algebraic-entry mode, in which @emph{all} regular letter and
10082punctuation keys begin algebraic entry. Use this if you prefer typing
10083@w{@kbd{sqrt( )}} instead of @kbd{Q}, @w{@kbd{factor( )}} instead of
10084@kbd{a f}, and so on. To type regular Calc commands when you are in
10085Total Algebraic mode, hold down the @key{META} key. Thus @kbd{M-q}
10086is the command to quit Calc, @kbd{M-p} sets the precision, and
10087@kbd{M-m t} (or @kbd{M-m M-t}, if you prefer) turns Total Algebraic
10088mode back off again. Meta keys also terminate algebraic entry, so
10089that @kbd{2+3 M-S} is equivalent to @kbd{2+3 @key{RET} M-S}. The symbol
10090@samp{Alg*} will appear in the mode line whenever you are in this mode.
10091
10092Pressing @kbd{'} (the apostrophe) a second time re-enters the previous
10093algebraic formula. You can then use the normal Emacs editing keys to
10094modify this formula to your liking before pressing @key{RET}.
10095
10096@kindex $
10097@cindex Formulas, referring to stack
10098Within a formula entered from the keyboard, the symbol @kbd{$}
10099represents the number on the top of the stack. If an entered formula
10100contains any @kbd{$} characters, the Calculator replaces the top of
10101stack with that formula rather than simply pushing the formula onto the
10102stack. Thus, @kbd{' 1+2 @key{RET}} pushes 3 on the stack, and @kbd{$*2
10103@key{RET}} replaces it with 6. Note that the @kbd{$} key always
10104initiates algebraic entry; the @kbd{'} is unnecessary if @kbd{$} is the
10105first character in the new formula.
10106
10107Higher stack elements can be accessed from an entered formula with the
10108symbols @kbd{$$}, @kbd{$$$}, and so on. The number of stack elements
10109removed (to be replaced by the entered values) equals the number of dollar
10110signs in the longest such symbol in the formula. For example, @samp{$$+$$$}
10111adds the second and third stack elements, replacing the top three elements
10112with the answer. (All information about the top stack element is thus lost
10113since no single @samp{$} appears in this formula.)
10114
10115A slightly different way to refer to stack elements is with a dollar
10116sign followed by a number: @samp{$1}, @samp{$2}, and so on are much
10117like @samp{$}, @samp{$$}, etc., except that stack entries referred
10118to numerically are not replaced by the algebraic entry. That is, while
10119@samp{$+1} replaces 5 on the stack with 6, @samp{$1+1} leaves the 5
10120on the stack and pushes an additional 6.
10121
10122If a sequence of formulas are entered separated by commas, each formula
10123is pushed onto the stack in turn. For example, @samp{1,2,3} pushes
10124those three numbers onto the stack (leaving the 3 at the top), and
10125@samp{$+1,$-1} replaces a 5 on the stack with 4 followed by 6. Also,
10126@samp{$,$$} exchanges the top two elements of the stack, just like the
10127@key{TAB} key.
10128
10129You can finish an algebraic entry with @kbd{M-=} or @kbd{M-@key{RET}} instead
10130of @key{RET}. This uses @kbd{=} to evaluate the variables in each
10131formula that goes onto the stack. (Thus @kbd{' pi @key{RET}} pushes
10132the variable @samp{pi}, but @kbd{' pi M-@key{RET}} pushes 3.1415.)
10133
10134If you finish your algebraic entry by pressing @key{LFD} (or @kbd{C-j})
10135instead of @key{RET}, Calc disables the default simplifications
10136(as if by @kbd{m O}; @pxref{Simplification Modes}) while the entry
10137is being pushed on the stack. Thus @kbd{' 1+2 @key{RET}} pushes 3
10138on the stack, but @kbd{' 1+2 @key{LFD}} pushes the formula @expr{1+2};
10139you might then press @kbd{=} when it is time to evaluate this formula.
10140
10141@node Quick Calculator, Prefix Arguments, Algebraic Entry, Introduction
10142@section ``Quick Calculator'' Mode
10143
10144@noindent
10145@kindex C-x * q
10146@pindex quick-calc
10147@cindex Quick Calculator
10148There is another way to invoke the Calculator if all you need to do
10149is make one or two quick calculations. Type @kbd{C-x * q} (or
10150@kbd{M-x quick-calc}), then type any formula as an algebraic entry.
10151The Calculator will compute the result and display it in the echo
10152area, without ever actually putting up a Calc window.
10153
10154You can use the @kbd{$} character in a Quick Calculator formula to
10155refer to the previous Quick Calculator result. Older results are
10156not retained; the Quick Calculator has no effect on the full
10157Calculator's stack or trail. If you compute a result and then
10158forget what it was, just run @code{C-x * q} again and enter
10159@samp{$} as the formula.
10160
10161If this is the first time you have used the Calculator in this Emacs
10162session, the @kbd{C-x * q} command will create the @code{*Calculator*}
10163buffer and perform all the usual initializations; it simply will
10164refrain from putting that buffer up in a new window. The Quick
10165Calculator refers to the @code{*Calculator*} buffer for all mode
10166settings. Thus, for example, to set the precision that the Quick
10167Calculator uses, simply run the full Calculator momentarily and use
10168the regular @kbd{p} command.
10169
10170If you use @code{C-x * q} from inside the Calculator buffer, the
10171effect is the same as pressing the apostrophe key (algebraic entry).
10172
10173The result of a Quick calculation is placed in the Emacs ``kill ring''
10174as well as being displayed. A subsequent @kbd{C-y} command will
10175yank the result into the editing buffer. You can also use this
10176to yank the result into the next @kbd{C-x * q} input line as a more
10177explicit alternative to @kbd{$} notation, or to yank the result
10178into the Calculator stack after typing @kbd{C-x * c}.
10179
10180If you finish your formula by typing @key{LFD} (or @kbd{C-j}) instead
10181of @key{RET}, the result is inserted immediately into the current
10182buffer rather than going into the kill ring.
10183
10184Quick Calculator results are actually evaluated as if by the @kbd{=}
10185key (which replaces variable names by their stored values, if any).
10186If the formula you enter is an assignment to a variable using the
10187@samp{:=} operator, say, @samp{foo := 2 + 3} or @samp{foo := foo + 1},
10188then the result of the evaluation is stored in that Calc variable.
10189@xref{Store and Recall}.
10190
10191If the result is an integer and the current display radix is decimal,
10192the number will also be displayed in hex, octal and binary formats. If
10193the integer is in the range from 1 to 126, it will also be displayed as
10194an ASCII character.
10195
10196For example, the quoted character @samp{"x"} produces the vector
10197result @samp{[120]} (because 120 is the ASCII code of the lower-case
10198`x'; @pxref{Strings}). Since this is a vector, not an integer, it
10199is displayed only according to the current mode settings. But
10200running Quick Calc again and entering @samp{120} will produce the
10201result @samp{120 (16#78, 8#170, x)} which shows the number in its
10202decimal, hexadecimal, octal, and ASCII forms.
10203
10204Please note that the Quick Calculator is not any faster at loading
10205or computing the answer than the full Calculator; the name ``quick''
10206merely refers to the fact that it's much less hassle to use for
10207small calculations.
10208
10209@node Prefix Arguments, Undo, Quick Calculator, Introduction
10210@section Numeric Prefix Arguments
10211
10212@noindent
10213Many Calculator commands use numeric prefix arguments. Some, such as
10214@kbd{d s} (@code{calc-sci-notation}), set a parameter to the value of
10215the prefix argument or use a default if you don't use a prefix.
10216Others (like @kbd{d f} (@code{calc-fix-notation})) require an argument
10217and prompt for a number if you don't give one as a prefix.
10218
10219As a rule, stack-manipulation commands accept a numeric prefix argument
10220which is interpreted as an index into the stack. A positive argument
10221operates on the top @var{n} stack entries; a negative argument operates
10222on the @var{n}th stack entry in isolation; and a zero argument operates
10223on the entire stack.
10224
10225Most commands that perform computations (such as the arithmetic and
10226scientific functions) accept a numeric prefix argument that allows the
10227operation to be applied across many stack elements. For unary operations
10228(that is, functions of one argument like absolute value or complex
10229conjugate), a positive prefix argument applies that function to the top
10230@var{n} stack entries simultaneously, and a negative argument applies it
10231to the @var{n}th stack entry only. For binary operations (functions of
10232two arguments like addition, GCD, and vector concatenation), a positive
10233prefix argument ``reduces'' the function across the top @var{n}
10234stack elements (for example, @kbd{C-u 5 +} sums the top 5 stack entries;
10235@pxref{Reducing and Mapping}), and a negative argument maps the next-to-top
10236@var{n} stack elements with the top stack element as a second argument
10237(for example, @kbd{7 c-u -5 +} adds 7 to the top 5 stack elements).
10238This feature is not available for operations which use the numeric prefix
10239argument for some other purpose.
10240
10241Numeric prefixes are specified the same way as always in Emacs: Press
10242a sequence of @key{META}-digits, or press @key{ESC} followed by digits,
10243or press @kbd{C-u} followed by digits. Some commands treat plain
10244@kbd{C-u} (without any actual digits) specially.
10245
10246@kindex ~
10247@pindex calc-num-prefix
10248You can type @kbd{~} (@code{calc-num-prefix}) to pop an integer from the
10249top of the stack and enter it as the numeric prefix for the next command.
10250For example, @kbd{C-u 16 p} sets the precision to 16 digits; an alternate
10251(silly) way to do this would be @kbd{2 @key{RET} 4 ^ ~ p}, i.e., compute 2
10252to the fourth power and set the precision to that value.
10253
10254Conversely, if you have typed a numeric prefix argument the @kbd{~} key
10255pushes it onto the stack in the form of an integer.
10256
10257@node Undo, Error Messages, Prefix Arguments, Introduction
10258@section Undoing Mistakes
10259
10260@noindent
10261@kindex U
10262@kindex C-_
10263@pindex calc-undo
10264@cindex Mistakes, undoing
10265@cindex Undoing mistakes
10266@cindex Errors, undoing
10267The shift-@kbd{U} key (@code{calc-undo}) undoes the most recent operation.
10268If that operation added or dropped objects from the stack, those objects
10269are removed or restored. If it was a ``store'' operation, you are
10270queried whether or not to restore the variable to its original value.
10271The @kbd{U} key may be pressed any number of times to undo successively
10272farther back in time; with a numeric prefix argument it undoes a
10273specified number of operations. The undo history is cleared only by the
10274@kbd{q} (@code{calc-quit}) command. (Recall that @kbd{C-x * c} is
10275synonymous with @code{calc-quit} while inside the Calculator; this
10276also clears the undo history.)
10277
10278Currently the mode-setting commands (like @code{calc-precision}) are not
10279undoable. You can undo past a point where you changed a mode, but you
10280will need to reset the mode yourself.
10281
10282@kindex D
10283@pindex calc-redo
10284@cindex Redoing after an Undo
10285The shift-@kbd{D} key (@code{calc-redo}) redoes an operation that was
10286mistakenly undone. Pressing @kbd{U} with a negative prefix argument is
10287equivalent to executing @code{calc-redo}. You can redo any number of
10288times, up to the number of recent consecutive undo commands. Redo
10289information is cleared whenever you give any command that adds new undo
10290information, i.e., if you undo, then enter a number on the stack or make
10291any other change, then it will be too late to redo.
10292
10293@kindex M-@key{RET}
10294@pindex calc-last-args
10295@cindex Last-arguments feature
10296@cindex Arguments, restoring
10297The @kbd{M-@key{RET}} key (@code{calc-last-args}) is like undo in that
10298it restores the arguments of the most recent command onto the stack;
10299however, it does not remove the result of that command. Given a numeric
10300prefix argument, this command applies to the @expr{n}th most recent
10301command which removed items from the stack; it pushes those items back
10302onto the stack.
10303
10304The @kbd{K} (@code{calc-keep-args}) command provides a related function
10305to @kbd{M-@key{RET}}. @xref{Stack and Trail}.
10306
10307It is also possible to recall previous results or inputs using the trail.
10308@xref{Trail Commands}.
10309
10310The standard Emacs @kbd{C-_} undo key is recognized as a synonym for @kbd{U}.
10311
10312@node Error Messages, Multiple Calculators, Undo, Introduction
10313@section Error Messages
10314
10315@noindent
10316@kindex w
10317@pindex calc-why
10318@cindex Errors, messages
10319@cindex Why did an error occur?
10320Many situations that would produce an error message in other calculators
10321simply create unsimplified formulas in the Emacs Calculator. For example,
10322@kbd{1 @key{RET} 0 /} pushes the formula @expr{1 / 0}; @w{@kbd{0 L}} pushes
10323the formula @samp{ln(0)}. Floating-point overflow and underflow are also
10324reasons for this to happen.
10325
10326When a function call must be left in symbolic form, Calc usually
10327produces a message explaining why. Messages that are probably
10328surprising or indicative of user errors are displayed automatically.
10329Other messages are simply kept in Calc's memory and are displayed only
10330if you type @kbd{w} (@code{calc-why}). You can also press @kbd{w} if
10331the same computation results in several messages. (The first message
10332will end with @samp{[w=more]} in this case.)
10333
10334@kindex d w
10335@pindex calc-auto-why
10336The @kbd{d w} (@code{calc-auto-why}) command controls when error messages
10337are displayed automatically. (Calc effectively presses @kbd{w} for you
10338after your computation finishes.) By default, this occurs only for
10339``important'' messages. The other possible modes are to report
10340@emph{all} messages automatically, or to report none automatically (so
10341that you must always press @kbd{w} yourself to see the messages).
10342
10343@node Multiple Calculators, Troubleshooting Commands, Error Messages, Introduction
10344@section Multiple Calculators
10345
10346@noindent
10347@pindex another-calc
10348It is possible to have any number of Calc mode buffers at once.
10349Usually this is done by executing @kbd{M-x another-calc}, which
10350is similar to @kbd{C-x * c} except that if a @samp{*Calculator*}
10351buffer already exists, a new, independent one with a name of the
10352form @samp{*Calculator*<@var{n}>} is created. You can also use the
10353command @code{calc-mode} to put any buffer into Calculator mode, but
10354this would ordinarily never be done.
10355
10356The @kbd{q} (@code{calc-quit}) command does not destroy a Calculator buffer;
10357it only closes its window. Use @kbd{M-x kill-buffer} to destroy a
10358Calculator buffer.
10359
10360Each Calculator buffer keeps its own stack, undo list, and mode settings
10361such as precision, angular mode, and display formats. In Emacs terms,
10362variables such as @code{calc-stack} are buffer-local variables. The
10363global default values of these variables are used only when a new
10364Calculator buffer is created. The @code{calc-quit} command saves
10365the stack and mode settings of the buffer being quit as the new defaults.
10366
10367There is only one trail buffer, @samp{*Calc Trail*}, used by all
10368Calculator buffers.
10369
10370@node Troubleshooting Commands, , Multiple Calculators, Introduction
10371@section Troubleshooting Commands
10372
10373@noindent
10374This section describes commands you can use in case a computation
10375incorrectly fails or gives the wrong answer.
10376
10377@xref{Reporting Bugs}, if you find a problem that appears to be due
10378to a bug or deficiency in Calc.
10379
10380@menu
10381* Autoloading Problems::
10382* Recursion Depth::
10383* Caches::
10384* Debugging Calc::
10385@end menu
10386
10387@node Autoloading Problems, Recursion Depth, Troubleshooting Commands, Troubleshooting Commands
10388@subsection Autoloading Problems
10389
10390@noindent
10391The Calc program is split into many component files; components are
10392loaded automatically as you use various commands that require them.
10393Occasionally Calc may lose track of when a certain component is
10394necessary; typically this means you will type a command and it won't
10395work because some function you've never heard of was undefined.
10396
10397@kindex C-x * L
10398@pindex calc-load-everything
10399If this happens, the easiest workaround is to type @kbd{C-x * L}
10400(@code{calc-load-everything}) to force all the parts of Calc to be
10401loaded right away. This will cause Emacs to take up a lot more
10402memory than it would otherwise, but it's guaranteed to fix the problem.
10403
10404@node Recursion Depth, Caches, Autoloading Problems, Troubleshooting Commands
10405@subsection Recursion Depth
10406
10407@noindent
10408@kindex M
10409@kindex I M
10410@pindex calc-more-recursion-depth
10411@pindex calc-less-recursion-depth
10412@cindex Recursion depth
10413@cindex ``Computation got stuck'' message
10414@cindex @code{max-lisp-eval-depth}
10415@cindex @code{max-specpdl-size}
10416Calc uses recursion in many of its calculations. Emacs Lisp keeps a
10417variable @code{max-lisp-eval-depth} which limits the amount of recursion
10418possible in an attempt to recover from program bugs. If a calculation
10419ever halts incorrectly with the message ``Computation got stuck or
10420ran too long,'' use the @kbd{M} command (@code{calc-more-recursion-depth})
10421to increase this limit. (Of course, this will not help if the
10422calculation really did get stuck due to some problem inside Calc.)
10423
10424The limit is always increased (multiplied) by a factor of two. There
10425is also an @kbd{I M} (@code{calc-less-recursion-depth}) command which
10426decreases this limit by a factor of two, down to a minimum value of 200.
10427The default value is 1000.
10428
10429These commands also double or halve @code{max-specpdl-size}, another
10430internal Lisp recursion limit. The minimum value for this limit is 600.
10431
10432@node Caches, Debugging Calc, Recursion Depth, Troubleshooting Commands
10433@subsection Caches
10434
10435@noindent
10436@cindex Caches
10437@cindex Flushing caches
10438Calc saves certain values after they have been computed once. For
10439example, the @kbd{P} (@code{calc-pi}) command initially ``knows'' the
10440constant @cpi{} to about 20 decimal places; if the current precision
10441is greater than this, it will recompute @cpi{} using a series
10442approximation. This value will not need to be recomputed ever again
10443unless you raise the precision still further. Many operations such as
10444logarithms and sines make use of similarly cached values such as
10445@cpiover{4} and
10446@texline @math{\ln 2}.
10447@infoline @expr{ln(2)}.
10448The visible effect of caching is that
10449high-precision computations may seem to do extra work the first time.
10450Other things cached include powers of two (for the binary arithmetic
10451functions), matrix inverses and determinants, symbolic integrals, and
10452data points computed by the graphing commands.
10453
10454@pindex calc-flush-caches
10455If you suspect a Calculator cache has become corrupt, you can use the
10456@code{calc-flush-caches} command to reset all caches to the empty state.
10457(This should only be necessary in the event of bugs in the Calculator.)
10458The @kbd{C-x * 0} (with the zero key) command also resets caches along
10459with all other aspects of the Calculator's state.
10460
10461@node Debugging Calc, , Caches, Troubleshooting Commands
10462@subsection Debugging Calc
10463
10464@noindent
10465A few commands exist to help in the debugging of Calc commands.
10466@xref{Programming}, to see the various ways that you can write
10467your own Calc commands.
10468
10469@kindex Z T
10470@pindex calc-timing
10471The @kbd{Z T} (@code{calc-timing}) command turns on and off a mode
10472in which the timing of slow commands is reported in the Trail.
10473Any Calc command that takes two seconds or longer writes a line
10474to the Trail showing how many seconds it took. This value is
10475accurate only to within one second.
10476
10477All steps of executing a command are included; in particular, time
10478taken to format the result for display in the stack and trail is
10479counted. Some prompts also count time taken waiting for them to
10480be answered, while others do not; this depends on the exact
10481implementation of the command. For best results, if you are timing
10482a sequence that includes prompts or multiple commands, define a
10483keyboard macro to run the whole sequence at once. Calc's @kbd{X}
10484command (@pxref{Keyboard Macros}) will then report the time taken
10485to execute the whole macro.
10486
10487Another advantage of the @kbd{X} command is that while it is
10488executing, the stack and trail are not updated from step to step.
10489So if you expect the output of your test sequence to leave a result
10490that may take a long time to format and you don't wish to count
10491this formatting time, end your sequence with a @key{DEL} keystroke
10492to clear the result from the stack. When you run the sequence with
10493@kbd{X}, Calc will never bother to format the large result.
10494
10495Another thing @kbd{Z T} does is to increase the Emacs variable
10496@code{gc-cons-threshold} to a much higher value (two million; the
10497usual default in Calc is 250,000) for the duration of each command.
10498This generally prevents garbage collection during the timing of
10499the command, though it may cause your Emacs process to grow
10500abnormally large. (Garbage collection time is a major unpredictable
10501factor in the timing of Emacs operations.)
10502
10503Another command that is useful when debugging your own Lisp
10504extensions to Calc is @kbd{M-x calc-pass-errors}, which disables
10505the error handler that changes the ``@code{max-lisp-eval-depth}
10506exceeded'' message to the much more friendly ``Computation got
10507stuck or ran too long.'' This handler interferes with the Emacs
10508Lisp debugger's @code{debug-on-error} mode. Errors are reported
10509in the handler itself rather than at the true location of the
10510error. After you have executed @code{calc-pass-errors}, Lisp
10511errors will be reported correctly but the user-friendly message
10512will be lost.
10513
10514@node Data Types, Stack and Trail, Introduction, Top
10515@chapter Data Types
10516
10517@noindent
10518This chapter discusses the various types of objects that can be placed
10519on the Calculator stack, how they are displayed, and how they are
10520entered. (@xref{Data Type Formats}, for information on how these data
10521types are represented as underlying Lisp objects.)
10522
10523Integers, fractions, and floats are various ways of describing real
10524numbers. HMS forms also for many purposes act as real numbers. These
10525types can be combined to form complex numbers, modulo forms, error forms,
10526or interval forms. (But these last four types cannot be combined
10527arbitrarily:@: error forms may not contain modulo forms, for example.)
10528Finally, all these types of numbers may be combined into vectors,
10529matrices, or algebraic formulas.
10530
10531@menu
10532* Integers:: The most basic data type.
10533* Fractions:: This and above are called @dfn{rationals}.
10534* Floats:: This and above are called @dfn{reals}.
10535* Complex Numbers:: This and above are called @dfn{numbers}.
10536* Infinities::
10537* Vectors and Matrices::
10538* Strings::
10539* HMS Forms::
10540* Date Forms::
10541* Modulo Forms::
10542* Error Forms::
10543* Interval Forms::
10544* Incomplete Objects::
10545* Variables::
10546* Formulas::
10547@end menu
10548
10549@node Integers, Fractions, Data Types, Data Types
10550@section Integers
10551
10552@noindent
10553@cindex Integers
10554The Calculator stores integers to arbitrary precision. Addition,
10555subtraction, and multiplication of integers always yields an exact
10556integer result. (If the result of a division or exponentiation of
10557integers is not an integer, it is expressed in fractional or
10558floating-point form according to the current Fraction mode.
10559@xref{Fraction Mode}.)
10560
10561A decimal integer is represented as an optional sign followed by a
10562sequence of digits. Grouping (@pxref{Grouping Digits}) can be used to
10563insert a comma at every third digit for display purposes, but you
10564must not type commas during the entry of numbers.
10565
10566@kindex #
10567A non-decimal integer is represented as an optional sign, a radix
10568between 2 and 36, a @samp{#} symbol, and one or more digits. For radix 11
10569and above, the letters A through Z (upper- or lower-case) count as
10570digits and do not terminate numeric entry mode. @xref{Radix Modes}, for how
10571to set the default radix for display of integers. Numbers of any radix
10572may be entered at any time. If you press @kbd{#} at the beginning of a
10573number, the current display radix is used.
10574
10575@node Fractions, Floats, Integers, Data Types
10576@section Fractions
10577
10578@noindent
10579@cindex Fractions
10580A @dfn{fraction} is a ratio of two integers. Fractions are traditionally
10581written ``2/3'' but Calc uses the notation @samp{2:3}. (The @kbd{/} key
10582performs RPN division; the following two sequences push the number
10583@samp{2:3} on the stack: @kbd{2 :@: 3 @key{RET}}, or @kbd{2 @key{RET} 3 /}
10584assuming Fraction mode has been enabled.)
10585When the Calculator produces a fractional result it always reduces it to
10586simplest form, which may in fact be an integer.
10587
10588Fractions may also be entered in a three-part form, where @samp{2:3:4}
10589represents two-and-three-quarters. @xref{Fraction Formats}, for fraction
10590display formats.
10591
10592Non-decimal fractions are entered and displayed as
10593@samp{@var{radix}#@var{num}:@var{denom}} (or in the analogous three-part
10594form). The numerator and denominator always use the same radix.
10595
10596@node Floats, Complex Numbers, Fractions, Data Types
10597@section Floats
10598
10599@noindent
10600@cindex Floating-point numbers
10601A floating-point number or @dfn{float} is a number stored in scientific
10602notation. The number of significant digits in the fractional part is
10603governed by the current floating precision (@pxref{Precision}). The
10604range of acceptable values is from
10605@texline @math{10^{-3999999}}
10606@infoline @expr{10^-3999999}
10607(inclusive) to
10608@texline @math{10^{4000000}}
10609@infoline @expr{10^4000000}
10610(exclusive), plus the corresponding negative values and zero.
10611
10612Calculations that would exceed the allowable range of values (such
10613as @samp{exp(exp(20))}) are left in symbolic form by Calc. The
10614messages ``floating-point overflow'' or ``floating-point underflow''
10615indicate that during the calculation a number would have been produced
10616that was too large or too close to zero, respectively, to be represented
10617by Calc. This does not necessarily mean the final result would have
10618overflowed, just that an overflow occurred while computing the result.
10619(In fact, it could report an underflow even though the final result
10620would have overflowed!)
10621
10622If a rational number and a float are mixed in a calculation, the result
10623will in general be expressed as a float. Commands that require an integer
10624value (such as @kbd{k g} [@code{gcd}]) will also accept integer-valued
10625floats, i.e., floating-point numbers with nothing after the decimal point.
10626
10627Floats are identified by the presence of a decimal point and/or an
10628exponent. In general a float consists of an optional sign, digits
10629including an optional decimal point, and an optional exponent consisting
10630of an @samp{e}, an optional sign, and up to seven exponent digits.
10631For example, @samp{23.5e-2} is 23.5 times ten to the minus-second power,
10632or 0.235.
10633
10634Floating-point numbers are normally displayed in decimal notation with
10635all significant figures shown. Exceedingly large or small numbers are
10636displayed in scientific notation. Various other display options are
10637available. @xref{Float Formats}.
10638
10639@cindex Accuracy of calculations
10640Floating-point numbers are stored in decimal, not binary. The result
10641of each operation is rounded to the nearest value representable in the
10642number of significant digits specified by the current precision,
10643rounding away from zero in the case of a tie. Thus (in the default
10644display mode) what you see is exactly what you get. Some operations such
10645as square roots and transcendental functions are performed with several
10646digits of extra precision and then rounded down, in an effort to make the
10647final result accurate to the full requested precision. However,
10648accuracy is not rigorously guaranteed. If you suspect the validity of a
10649result, try doing the same calculation in a higher precision. The
10650Calculator's arithmetic is not intended to be IEEE-conformant in any
10651way.
10652
10653While floats are always @emph{stored} in decimal, they can be entered
10654and displayed in any radix just like integers and fractions. Since a
10655float that is entered in a radix other that 10 will be converted to
10656decimal, the number that Calc stores may not be exactly the number that
10657was entered, it will be the closest decimal approximation given the
10658current precison. The notation @samp{@var{radix}#@var{ddd}.@var{ddd}}
10659is a floating-point number whose digits are in the specified radix.
10660Note that the @samp{.} is more aptly referred to as a ``radix point''
10661than as a decimal point in this case. The number @samp{8#123.4567} is
10662defined as @samp{8#1234567 * 8^-4}. If the radix is 14 or less, you can
10663use @samp{e} notation to write a non-decimal number in scientific
10664notation. The exponent is written in decimal, and is considered to be a
10665power of the radix: @samp{8#1234567e-4}. If the radix is 15 or above,
10666the letter @samp{e} is a digit, so scientific notation must be written
10667out, e.g., @samp{16#123.4567*16^2}. The first two exercises of the
10668Modes Tutorial explore some of the properties of non-decimal floats.
10669
10670@node Complex Numbers, Infinities, Floats, Data Types
10671@section Complex Numbers
10672
10673@noindent
10674@cindex Complex numbers
10675There are two supported formats for complex numbers: rectangular and
10676polar. The default format is rectangular, displayed in the form
10677@samp{(@var{real},@var{imag})} where @var{real} is the real part and
10678@var{imag} is the imaginary part, each of which may be any real number.
10679Rectangular complex numbers can also be displayed in @samp{@var{a}+@var{b}i}
10680notation; @pxref{Complex Formats}.
10681
10682Polar complex numbers are displayed in the form
10683@texline `@tfn{(}@var{r}@tfn{;}@math{\theta}@tfn{)}'
10684@infoline `@tfn{(}@var{r}@tfn{;}@var{theta}@tfn{)}'
10685where @var{r} is the nonnegative magnitude and
10686@texline @math{\theta}
10687@infoline @var{theta}
10688is the argument or phase angle. The range of
10689@texline @math{\theta}
10690@infoline @var{theta}
10691depends on the current angular mode (@pxref{Angular Modes}); it is
10692generally between @mathit{-180} and @mathit{+180} degrees or the equivalent range
10693in radians.
10694
10695Complex numbers are entered in stages using incomplete objects.
10696@xref{Incomplete Objects}.
10697
10698Operations on rectangular complex numbers yield rectangular complex
10699results, and similarly for polar complex numbers. Where the two types
10700are mixed, or where new complex numbers arise (as for the square root of
10701a negative real), the current @dfn{Polar mode} is used to determine the
10702type. @xref{Polar Mode}.
10703
10704A complex result in which the imaginary part is zero (or the phase angle
10705is 0 or 180 degrees or @cpi{} radians) is automatically converted to a real
10706number.
10707
10708@node Infinities, Vectors and Matrices, Complex Numbers, Data Types
10709@section Infinities
10710
10711@noindent
10712@cindex Infinity
10713@cindex @code{inf} variable
10714@cindex @code{uinf} variable
10715@cindex @code{nan} variable
10716@vindex inf
10717@vindex uinf
10718@vindex nan
10719The word @code{inf} represents the mathematical concept of @dfn{infinity}.
10720Calc actually has three slightly different infinity-like values:
10721@code{inf}, @code{uinf}, and @code{nan}. These are just regular
10722variable names (@pxref{Variables}); you should avoid using these
10723names for your own variables because Calc gives them special
10724treatment. Infinities, like all variable names, are normally
10725entered using algebraic entry.
10726
10727Mathematically speaking, it is not rigorously correct to treat
10728``infinity'' as if it were a number, but mathematicians often do
10729so informally. When they say that @samp{1 / inf = 0}, what they
10730really mean is that @expr{1 / x}, as @expr{x} becomes larger and
10731larger, becomes arbitrarily close to zero. So you can imagine
10732that if @expr{x} got ``all the way to infinity,'' then @expr{1 / x}
10733would go all the way to zero. Similarly, when they say that
10734@samp{exp(inf) = inf}, they mean that
10735@texline @math{e^x}
10736@infoline @expr{exp(x)}
10737grows without bound as @expr{x} grows. The symbol @samp{-inf} likewise
10738stands for an infinitely negative real value; for example, we say that
10739@samp{exp(-inf) = 0}. You can have an infinity pointing in any
10740direction on the complex plane: @samp{sqrt(-inf) = i inf}.
10741
10742The same concept of limits can be used to define @expr{1 / 0}. We
10743really want the value that @expr{1 / x} approaches as @expr{x}
10744approaches zero. But if all we have is @expr{1 / 0}, we can't
10745tell which direction @expr{x} was coming from. If @expr{x} was
10746positive and decreasing toward zero, then we should say that
10747@samp{1 / 0 = inf}. But if @expr{x} was negative and increasing
10748toward zero, the answer is @samp{1 / 0 = -inf}. In fact, @expr{x}
10749could be an imaginary number, giving the answer @samp{i inf} or
10750@samp{-i inf}. Calc uses the special symbol @samp{uinf} to mean
10751@dfn{undirected infinity}, i.e., a value which is infinitely
10752large but with an unknown sign (or direction on the complex plane).
10753
10754Calc actually has three modes that say how infinities are handled.
10755Normally, infinities never arise from calculations that didn't
10756already have them. Thus, @expr{1 / 0} is treated simply as an
10757error and left unevaluated. The @kbd{m i} (@code{calc-infinite-mode})
10758command (@pxref{Infinite Mode}) enables a mode in which
10759@expr{1 / 0} evaluates to @code{uinf} instead. There is also
10760an alternative type of infinite mode which says to treat zeros
10761as if they were positive, so that @samp{1 / 0 = inf}. While this
10762is less mathematically correct, it may be the answer you want in
10763some cases.
10764
10765Since all infinities are ``as large'' as all others, Calc simplifies,
10766e.g., @samp{5 inf} to @samp{inf}. Another example is
10767@samp{5 - inf = -inf}, where the @samp{-inf} is so large that
10768adding a finite number like five to it does not affect it.
10769Note that @samp{a - inf} also results in @samp{-inf}; Calc assumes
10770that variables like @code{a} always stand for finite quantities.
10771Just to show that infinities really are all the same size,
10772note that @samp{sqrt(inf) = inf^2 = exp(inf) = inf} in Calc's
10773notation.
10774
10775It's not so easy to define certain formulas like @samp{0 * inf} and
10776@samp{inf / inf}. Depending on where these zeros and infinities
10777came from, the answer could be literally anything. The latter
10778formula could be the limit of @expr{x / x} (giving a result of one),
10779or @expr{2 x / x} (giving two), or @expr{x^2 / x} (giving @code{inf}),
10780or @expr{x / x^2} (giving zero). Calc uses the symbol @code{nan}
10781to represent such an @dfn{indeterminate} value. (The name ``nan''
10782comes from analogy with the ``NAN'' concept of IEEE standard
10783arithmetic; it stands for ``Not A Number.'' This is somewhat of a
10784misnomer, since @code{nan} @emph{does} stand for some number or
10785infinity, it's just that @emph{which} number it stands for
10786cannot be determined.) In Calc's notation, @samp{0 * inf = nan}
10787and @samp{inf / inf = nan}. A few other common indeterminate
10788expressions are @samp{inf - inf} and @samp{inf ^ 0}. Also,
10789@samp{0 / 0 = nan} if you have turned on Infinite mode
10790(as described above).
10791
10792Infinities are especially useful as parts of @dfn{intervals}.
10793@xref{Interval Forms}.
10794
10795@node Vectors and Matrices, Strings, Infinities, Data Types
10796@section Vectors and Matrices
10797
10798@noindent
10799@cindex Vectors
10800@cindex Plain vectors
10801@cindex Matrices
10802The @dfn{vector} data type is flexible and general. A vector is simply a
10803list of zero or more data objects. When these objects are numbers, the
10804whole is a vector in the mathematical sense. When these objects are
10805themselves vectors of equal (nonzero) length, the whole is a @dfn{matrix}.
10806A vector which is not a matrix is referred to here as a @dfn{plain vector}.
10807
10808A vector is displayed as a list of values separated by commas and enclosed
10809in square brackets: @samp{[1, 2, 3]}. Thus the following is a 2 row by
108103 column matrix: @samp{[[1, 2, 3], [4, 5, 6]]}. Vectors, like complex
10811numbers, are entered as incomplete objects. @xref{Incomplete Objects}.
10812During algebraic entry, vectors are entered all at once in the usual
10813brackets-and-commas form. Matrices may be entered algebraically as nested
10814vectors, or using the shortcut notation @w{@samp{[1, 2, 3; 4, 5, 6]}},
10815with rows separated by semicolons. The commas may usually be omitted
10816when entering vectors: @samp{[1 2 3]}. Curly braces may be used in
10817place of brackets: @samp{@{1, 2, 3@}}, but the commas are required in
10818this case.
10819
10820Traditional vector and matrix arithmetic is also supported;
10821@pxref{Basic Arithmetic} and @pxref{Matrix Functions}.
10822Many other operations are applied to vectors element-wise. For example,
10823the complex conjugate of a vector is a vector of the complex conjugates
10824of its elements.
10825
10826@ignore
10827@starindex
10828@end ignore
10829@tindex vec
10830Algebraic functions for building vectors include @samp{vec(a, b, c)}
10831to build @samp{[a, b, c]}, @samp{cvec(a, n, m)} to build an
10832@texline @math{n\times m}
10833@infoline @var{n}x@var{m}
10834matrix of @samp{a}s, and @samp{index(n)} to build a vector of integers
10835from 1 to @samp{n}.
10836
10837@node Strings, HMS Forms, Vectors and Matrices, Data Types
10838@section Strings
10839
10840@noindent
10841@kindex "
10842@cindex Strings
10843@cindex Character strings
10844Character strings are not a special data type in the Calculator.
10845Rather, a string is represented simply as a vector all of whose
10846elements are integers in the range 0 to 255 (ASCII codes). You can
10847enter a string at any time by pressing the @kbd{"} key. Quotation
10848marks and backslashes are written @samp{\"} and @samp{\\}, respectively,
10849inside strings. Other notations introduced by backslashes are:
10850
10851@example
10852@group
10853\a 7 \^@@ 0
10854\b 8 \^a-z 1-26
10855\e 27 \^[ 27
10856\f 12 \^\\ 28
10857\n 10 \^] 29
10858\r 13 \^^ 30
10859\t 9 \^_ 31
10860 \^? 127
10861@end group
10862@end example
10863
10864@noindent
10865Finally, a backslash followed by three octal digits produces any
10866character from its ASCII code.
10867
10868@kindex d "
10869@pindex calc-display-strings
10870Strings are normally displayed in vector-of-integers form. The
10871@w{@kbd{d "}} (@code{calc-display-strings}) command toggles a mode in
10872which any vectors of small integers are displayed as quoted strings
10873instead.
10874
10875The backslash notations shown above are also used for displaying
10876strings. Characters 128 and above are not translated by Calc; unless
10877you have an Emacs modified for 8-bit fonts, these will show up in
10878backslash-octal-digits notation. For characters below 32, and
10879for character 127, Calc uses the backslash-letter combination if
10880there is one, or otherwise uses a @samp{\^} sequence.
10881
10882The only Calc feature that uses strings is @dfn{compositions};
10883@pxref{Compositions}. Strings also provide a convenient
10884way to do conversions between ASCII characters and integers.
10885
10886@ignore
10887@starindex
10888@end ignore
10889@tindex string
10890There is a @code{string} function which provides a different display
10891format for strings. Basically, @samp{string(@var{s})}, where @var{s}
10892is a vector of integers in the proper range, is displayed as the
10893corresponding string of characters with no surrounding quotation
10894marks or other modifications. Thus @samp{string("ABC")} (or
10895@samp{string([65 66 67])}) will look like @samp{ABC} on the stack.
10896This happens regardless of whether @w{@kbd{d "}} has been used. The
10897only way to turn it off is to use @kbd{d U} (unformatted language
10898mode) which will display @samp{string("ABC")} instead.
10899
10900Control characters are displayed somewhat differently by @code{string}.
10901Characters below 32, and character 127, are shown using @samp{^} notation
10902(same as shown above, but without the backslash). The quote and
10903backslash characters are left alone, as are characters 128 and above.
10904
10905@ignore
10906@starindex
10907@end ignore
10908@tindex bstring
10909The @code{bstring} function is just like @code{string} except that
10910the resulting string is breakable across multiple lines if it doesn't
10911fit all on one line. Potential break points occur at every space
10912character in the string.
10913
10914@node HMS Forms, Date Forms, Strings, Data Types
10915@section HMS Forms
10916
10917@noindent
10918@cindex Hours-minutes-seconds forms
10919@cindex Degrees-minutes-seconds forms
10920@dfn{HMS} stands for Hours-Minutes-Seconds; when used as an angular
10921argument, the interpretation is Degrees-Minutes-Seconds. All functions
10922that operate on angles accept HMS forms. These are interpreted as
10923degrees regardless of the current angular mode. It is also possible to
10924use HMS as the angular mode so that calculated angles are expressed in
10925degrees, minutes, and seconds.
10926
10927@kindex @@
10928@ignore
10929@mindex @null
10930@end ignore
10931@kindex ' (HMS forms)
10932@ignore
10933@mindex @null
10934@end ignore
10935@kindex " (HMS forms)
10936@ignore
10937@mindex @null
10938@end ignore
10939@kindex h (HMS forms)
10940@ignore
10941@mindex @null
10942@end ignore
10943@kindex o (HMS forms)
10944@ignore
10945@mindex @null
10946@end ignore
10947@kindex m (HMS forms)
10948@ignore
10949@mindex @null
10950@end ignore
10951@kindex s (HMS forms)
10952The default format for HMS values is
10953@samp{@var{hours}@@ @var{mins}' @var{secs}"}. During entry, the letters
10954@samp{h} (for ``hours'') or
10955@samp{o} (approximating the ``degrees'' symbol) are accepted as well as
10956@samp{@@}, @samp{m} is accepted in place of @samp{'}, and @samp{s} is
10957accepted in place of @samp{"}.
10958The @var{hours} value is an integer (or integer-valued float).
10959The @var{mins} value is an integer or integer-valued float between 0 and 59.
10960The @var{secs} value is a real number between 0 (inclusive) and 60
10961(exclusive). A positive HMS form is interpreted as @var{hours} +
10962@var{mins}/60 + @var{secs}/3600. A negative HMS form is interpreted
10963as @mathit{- @var{hours}} @mathit{-} @var{mins}/60 @mathit{-} @var{secs}/3600.
10964Display format for HMS forms is quite flexible. @xref{HMS Formats}.
10965
10966HMS forms can be added and subtracted. When they are added to numbers,
10967the numbers are interpreted according to the current angular mode. HMS
10968forms can also be multiplied and divided by real numbers. Dividing
10969two HMS forms produces a real-valued ratio of the two angles.
10970
10971@pindex calc-time
10972@cindex Time of day
10973Just for kicks, @kbd{M-x calc-time} pushes the current time of day on
10974the stack as an HMS form.
10975
10976@node Date Forms, Modulo Forms, HMS Forms, Data Types
10977@section Date Forms
10978
10979@noindent
10980@cindex Date forms
10981A @dfn{date form} represents a date and possibly an associated time.
10982Simple date arithmetic is supported: Adding a number to a date
10983produces a new date shifted by that many days; adding an HMS form to
10984a date shifts it by that many hours. Subtracting two date forms
10985computes the number of days between them (represented as a simple
10986number). Many other operations, such as multiplying two date forms,
10987are nonsensical and are not allowed by Calc.
10988
10989Date forms are entered and displayed enclosed in @samp{< >} brackets.
10990The default format is, e.g., @samp{<Wed Jan 9, 1991>} for dates,
10991or @samp{<3:32:20pm Wed Jan 9, 1991>} for dates with times.
10992Input is flexible; date forms can be entered in any of the usual
10993notations for dates and times. @xref{Date Formats}.
10994
10995Date forms are stored internally as numbers, specifically the number
10996of days since midnight on the morning of January 1 of the year 1 AD.
10997If the internal number is an integer, the form represents a date only;
10998if the internal number is a fraction or float, the form represents
10999a date and time. For example, @samp{<6:00am Wed Jan 9, 1991>}
11000is represented by the number 726842.25. The standard precision of
1100112 decimal digits is enough to ensure that a (reasonable) date and
11002time can be stored without roundoff error.
11003
11004If the current precision is greater than 12, date forms will keep
11005additional digits in the seconds position. For example, if the
11006precision is 15, the seconds will keep three digits after the
11007decimal point. Decreasing the precision below 12 may cause the
11008time part of a date form to become inaccurate. This can also happen
11009if astronomically high years are used, though this will not be an
11010issue in everyday (or even everymillennium) use. Note that date
11011forms without times are stored as exact integers, so roundoff is
11012never an issue for them.
11013
11014You can use the @kbd{v p} (@code{calc-pack}) and @kbd{v u}
11015(@code{calc-unpack}) commands to get at the numerical representation
11016of a date form. @xref{Packing and Unpacking}.
11017
11018Date forms can go arbitrarily far into the future or past. Negative
11019year numbers represent years BC. Calc uses a combination of the
11020Gregorian and Julian calendars, following the history of Great
11021Britain and the British colonies. This is the same calendar that
11022is used by the @code{cal} program in most Unix implementations.
11023
11024@cindex Julian calendar
11025@cindex Gregorian calendar
11026Some historical background: The Julian calendar was created by
11027Julius Caesar in the year 46 BC as an attempt to fix the gradual
11028drift caused by the lack of leap years in the calendar used
11029until that time. The Julian calendar introduced an extra day in
11030all years divisible by four. After some initial confusion, the
11031calendar was adopted around the year we call 8 AD. Some centuries
11032later it became apparent that the Julian year of 365.25 days was
11033itself not quite right. In 1582 Pope Gregory XIII introduced the
11034Gregorian calendar, which added the new rule that years divisible
11035by 100, but not by 400, were not to be considered leap years
11036despite being divisible by four. Many countries delayed adoption
11037of the Gregorian calendar because of religious differences;
11038in Britain it was put off until the year 1752, by which time
11039the Julian calendar had fallen eleven days behind the true
11040seasons. So the switch to the Gregorian calendar in early
11041September 1752 introduced a discontinuity: The day after
11042Sep 2, 1752 is Sep 14, 1752. Calc follows this convention.
11043To take another example, Russia waited until 1918 before
11044adopting the new calendar, and thus needed to remove thirteen
11045days (between Feb 1, 1918 and Feb 14, 1918). This means that
11046Calc's reckoning will be inconsistent with Russian history between
110471752 and 1918, and similarly for various other countries.
11048
11049Today's timekeepers introduce an occasional ``leap second'' as
11050well, but Calc does not take these minor effects into account.
11051(If it did, it would have to report a non-integer number of days
11052between, say, @samp{<12:00am Mon Jan 1, 1900>} and
11053@samp{<12:00am Sat Jan 1, 2000>}.)
11054
11055Calc uses the Julian calendar for all dates before the year 1752,
11056including dates BC when the Julian calendar technically had not
11057yet been invented. Thus the claim that day number @mathit{-10000} is
11058called ``August 16, 28 BC'' should be taken with a grain of salt.
11059
11060Please note that there is no ``year 0''; the day before
11061@samp{<Sat Jan 1, +1>} is @samp{<Fri Dec 31, -1>}. These are
11062days 0 and @mathit{-1} respectively in Calc's internal numbering scheme.
11063
11064@cindex Julian day counting
7c1a0036
GM
11065Another day counting system in common use is, confusingly, also called
11066``Julian.'' The Julian day number is the numbers of days since
1106712:00 noon (GMT) on Jan 1, 4713 BC, which in Calc's scheme (in GMT)
db78a8cb 11068is @mathit{-1721423.5} (recall that Calc starts at midnight instead
7c1a0036
GM
11069of noon). Thus to convert a Calc date code obtained by unpacking a
11070date form into a Julian day number, simply add 1721423.5 after
11071compensating for the time zone difference. The built-in @kbd{t J}
11072command performs this conversion for you.
11073
11074The Julian day number is based on the Julian cycle, which was invented
11075in 1583 by Joseph Justus Scaliger. Scaliger named it the Julian cycle
11076since it is involves the Julian calendar, but some have suggested that
11077Scaliger named it in honor of his father, Julius Caesar Scaliger. The
11078Julian cycle is based it on three other cycles: the indiction cycle,
11079the Metonic cycle, and the solar cycle. The indiction cycle is a 15
11080year cycle originally used by the Romans for tax purposes but later
11081used to date medieval documents. The Metonic cycle is a 19 year
11082cycle; 19 years is close to being a common multiple of a solar year
11083and a lunar month, and so every 19 years the phases of the moon will
11084occur on the same days of the year. The solar cycle is a 28 year
11085cycle; the Julian calendar repeats itself every 28 years. The
11086smallest time period which contains multiples of all three cycles is
11087the least common multiple of 15 years, 19 years and 28 years, which
11088(since they're pairwise relatively prime) is
11089@texline @math{15\times 19\times 28 = 7980} years.
11090@infoline 15*19*28 = 7980 years.
11091This is the length of a Julian cycle. Working backwards, the previous
11092year in which all three cycles began was 4713 BC, and so Scalinger
11093chose that year as the beginning of a Julian cycle. Since at the time
11094there were no historical records from before 4713 BC, using this year
11095as a starting point had the advantage of avoiding negative year
11096numbers. In 1849, the astronomer John Herschel (son of William
11097Herschel) suggested using the number of days since the beginning of
11098the Julian cycle as an astronomical dating system; this idea was taken
11099up by other astronomers. (At the time, noon was the start of the
11100astronomical day. Herschel originally suggested counting the days
11101since Jan 1, 4713 BC at noon Alexandria time; this was later amended to
11102noon GMT.) Julian day numbering is largely used in astronomy.
4009494e
GM
11103
11104@cindex Unix time format
11105The Unix operating system measures time as an integer number of
11106seconds since midnight, Jan 1, 1970. To convert a Calc date
11107value into a Unix time stamp, first subtract 719164 (the code
11108for @samp{<Jan 1, 1970>}), then multiply by 86400 (the number of
11109seconds in a day) and press @kbd{R} to round to the nearest
11110integer. If you have a date form, you can simply subtract the
11111day @samp{<Jan 1, 1970>} instead of unpacking and subtracting
11112719164. Likewise, divide by 86400 and add @samp{<Jan 1, 1970>}
11113to convert from Unix time to a Calc date form. (Note that
11114Unix normally maintains the time in the GMT time zone; you may
11115need to subtract five hours to get New York time, or eight hours
11116for California time. The same is usually true of Julian day
11117counts.) The built-in @kbd{t U} command performs these
11118conversions.
11119
11120@node Modulo Forms, Error Forms, Date Forms, Data Types
11121@section Modulo Forms
11122
11123@noindent
11124@cindex Modulo forms
11125A @dfn{modulo form} is a real number which is taken modulo (i.e., within
11126an integer multiple of) some value @var{M}. Arithmetic modulo @var{M}
11127often arises in number theory. Modulo forms are written
11128`@var{a} @tfn{mod} @var{M}',
11129where @var{a} and @var{M} are real numbers or HMS forms, and
11130@texline @math{0 \le a < M}.
11131@infoline @expr{0 <= a < @var{M}}.
11132In many applications @expr{a} and @expr{M} will be
11133integers but this is not required.
11134
11135@ignore
11136@mindex M
11137@end ignore
11138@kindex M (modulo forms)
11139@ignore
11140@mindex mod
11141@end ignore
11142@tindex mod (operator)
11143To create a modulo form during numeric entry, press the shift-@kbd{M}
11144key to enter the word @samp{mod}. As a special convenience, pressing
11145shift-@kbd{M} a second time automatically enters the value of @expr{M}
11146that was most recently used before. During algebraic entry, either
11147type @samp{mod} by hand or press @kbd{M-m} (that's @kbd{@key{META}-m}).
11148Once again, pressing this a second time enters the current modulo.
11149
11150Modulo forms are not to be confused with the modulo operator @samp{%}.
11151The expression @samp{27 % 10} means to compute 27 modulo 10 to produce
11152the result 7. Further computations treat this 7 as just a regular integer.
11153The expression @samp{27 mod 10} produces the result @samp{7 mod 10};
11154further computations with this value are again reduced modulo 10 so that
11155the result always lies in the desired range.
11156
11157When two modulo forms with identical @expr{M}'s are added or multiplied,
11158the Calculator simply adds or multiplies the values, then reduces modulo
11159@expr{M}. If one argument is a modulo form and the other a plain number,
11160the plain number is treated like a compatible modulo form. It is also
11161possible to raise modulo forms to powers; the result is the value raised
11162to the power, then reduced modulo @expr{M}. (When all values involved
11163are integers, this calculation is done much more efficiently than
11164actually computing the power and then reducing.)
11165
11166@cindex Modulo division
11167Two modulo forms `@var{a} @tfn{mod} @var{M}' and `@var{b} @tfn{mod} @var{M}'
11168can be divided if @expr{a}, @expr{b}, and @expr{M} are all
11169integers. The result is the modulo form which, when multiplied by
11170`@var{b} @tfn{mod} @var{M}', produces `@var{a} @tfn{mod} @var{M}'. If
11171there is no solution to this equation (which can happen only when
11172@expr{M} is non-prime), or if any of the arguments are non-integers, the
11173division is left in symbolic form. Other operations, such as square
11174roots, are not yet supported for modulo forms. (Note that, although
11175@w{`@tfn{(}@var{a} @tfn{mod} @var{M}@tfn{)^.5}'} will compute a ``modulo square root''
11176in the sense of reducing
11177@texline @math{\sqrt a}
11178@infoline @expr{sqrt(a)}
11179modulo @expr{M}, this is not a useful definition from the
11180number-theoretical point of view.)
11181
11182It is possible to mix HMS forms and modulo forms. For example, an
11183HMS form modulo 24 could be used to manipulate clock times; an HMS
11184form modulo 360 would be suitable for angles. Making the modulo @expr{M}
11185also be an HMS form eliminates troubles that would arise if the angular
11186mode were inadvertently set to Radians, in which case
11187@w{@samp{2@@ 0' 0" mod 24}} would be interpreted as two degrees modulo
1118824 radians!
11189
11190Modulo forms cannot have variables or formulas for components. If you
11191enter the formula @samp{(x + 2) mod 5}, Calc propagates the modulus
11192to each of the coefficients: @samp{(1 mod 5) x + (2 mod 5)}.
11193
11194You can use @kbd{v p} and @kbd{%} to modify modulo forms.
11195@xref{Packing and Unpacking}. @xref{Basic Arithmetic}.
11196
11197@ignore
11198@starindex
11199@end ignore
11200@tindex makemod
11201The algebraic function @samp{makemod(a, m)} builds the modulo form
11202@w{@samp{a mod m}}.
11203
11204@node Error Forms, Interval Forms, Modulo Forms, Data Types
11205@section Error Forms
11206
11207@noindent
11208@cindex Error forms
11209@cindex Standard deviations
11210An @dfn{error form} is a number with an associated standard
11211deviation, as in @samp{2.3 +/- 0.12}. The notation
11212@texline `@var{x} @tfn{+/-} @math{\sigma}'
11213@infoline `@var{x} @tfn{+/-} sigma'
11214stands for an uncertain value which follows
11215a normal or Gaussian distribution of mean @expr{x} and standard
11216deviation or ``error''
11217@texline @math{\sigma}.
11218@infoline @expr{sigma}.
11219Both the mean and the error can be either numbers or
11220formulas. Generally these are real numbers but the mean may also be
11221complex. If the error is negative or complex, it is changed to its
11222absolute value. An error form with zero error is converted to a
11223regular number by the Calculator.
11224
11225All arithmetic and transcendental functions accept error forms as input.
11226Operations on the mean-value part work just like operations on regular
11227numbers. The error part for any function @expr{f(x)} (such as
11228@texline @math{\sin x}
11229@infoline @expr{sin(x)})
11230is defined by the error of @expr{x} times the derivative of @expr{f}
11231evaluated at the mean value of @expr{x}. For a two-argument function
11232@expr{f(x,y)} (such as addition) the error is the square root of the sum
11233of the squares of the errors due to @expr{x} and @expr{y}.
11234@tex
11235$$ \eqalign{
11236 f(x \hbox{\code{ +/- }} \sigma)
11237 &= f(x) \hbox{\code{ +/- }} \sigma \left| {df(x) \over dx} \right| \cr
11238 f(x \hbox{\code{ +/- }} \sigma_x, y \hbox{\code{ +/- }} \sigma_y)
11239 &= f(x,y) \hbox{\code{ +/- }}
11240 \sqrt{\left(\sigma_x \left| {\partial f(x,y) \over \partial x}
11241 \right| \right)^2
11242 +\left(\sigma_y \left| {\partial f(x,y) \over \partial y}
11243 \right| \right)^2 } \cr
11244} $$
11245@end tex
11246Note that this
11247definition assumes the errors in @expr{x} and @expr{y} are uncorrelated.
11248A side effect of this definition is that @samp{(2 +/- 1) * (2 +/- 1)}
11249is not the same as @samp{(2 +/- 1)^2}; the former represents the product
11250of two independent values which happen to have the same probability
11251distributions, and the latter is the product of one random value with itself.
11252The former will produce an answer with less error, since on the average
11253the two independent errors can be expected to cancel out.
11254
11255Consult a good text on error analysis for a discussion of the proper use
11256of standard deviations. Actual errors often are neither Gaussian-distributed
11257nor uncorrelated, and the above formulas are valid only when errors
11258are small. As an example, the error arising from
11259@texline `@tfn{sin(}@var{x} @tfn{+/-} @math{\sigma}@tfn{)}'
11260@infoline `@tfn{sin(}@var{x} @tfn{+/-} @var{sigma}@tfn{)}'
11261is
11262@texline `@math{\sigma} @tfn{abs(cos(}@var{x}@tfn{))}'.
11263@infoline `@var{sigma} @tfn{abs(cos(}@var{x}@tfn{))}'.
11264When @expr{x} is close to zero,
11265@texline @math{\cos x}
11266@infoline @expr{cos(x)}
11267is close to one so the error in the sine is close to
11268@texline @math{\sigma};
11269@infoline @expr{sigma};
11270this makes sense, since
11271@texline @math{\sin x}
11272@infoline @expr{sin(x)}
11273is approximately @expr{x} near zero, so a given error in @expr{x} will
11274produce about the same error in the sine. Likewise, near 90 degrees
11275@texline @math{\cos x}
11276@infoline @expr{cos(x)}
11277is nearly zero and so the computed error is
11278small: The sine curve is nearly flat in that region, so an error in @expr{x}
11279has relatively little effect on the value of
11280@texline @math{\sin x}.
11281@infoline @expr{sin(x)}.
11282However, consider @samp{sin(90 +/- 1000)}. The cosine of 90 is zero, so
11283Calc will report zero error! We get an obviously wrong result because
11284we have violated the small-error approximation underlying the error
11285analysis. If the error in @expr{x} had been small, the error in
11286@texline @math{\sin x}
11287@infoline @expr{sin(x)}
11288would indeed have been negligible.
11289
11290@ignore
11291@mindex p
11292@end ignore
11293@kindex p (error forms)
11294@tindex +/-
11295To enter an error form during regular numeric entry, use the @kbd{p}
11296(``plus-or-minus'') key to type the @samp{+/-} symbol. (If you try actually
11297typing @samp{+/-} the @kbd{+} key will be interpreted as the Calculator's
11298@kbd{+} command!) Within an algebraic formula, you can press @kbd{M-+} to
11299type the @samp{+/-} symbol, or type it out by hand.
11300
11301Error forms and complex numbers can be mixed; the formulas shown above
11302are used for complex numbers, too; note that if the error part evaluates
11303to a complex number its absolute value (or the square root of the sum of
11304the squares of the absolute values of the two error contributions) is
11305used. Mathematically, this corresponds to a radially symmetric Gaussian
11306distribution of numbers on the complex plane. However, note that Calc
11307considers an error form with real components to represent a real number,
11308not a complex distribution around a real mean.
11309
11310Error forms may also be composed of HMS forms. For best results, both
11311the mean and the error should be HMS forms if either one is.
11312
11313@ignore
11314@starindex
11315@end ignore
11316@tindex sdev
11317The algebraic function @samp{sdev(a, b)} builds the error form @samp{a +/- b}.
11318
11319@node Interval Forms, Incomplete Objects, Error Forms, Data Types
11320@section Interval Forms
11321
11322@noindent
11323@cindex Interval forms
11324An @dfn{interval} is a subset of consecutive real numbers. For example,
11325the interval @samp{[2 ..@: 4]} represents all the numbers from 2 to 4,
11326inclusive. If you multiply it by the interval @samp{[0.5 ..@: 2]} you
11327obtain @samp{[1 ..@: 8]}. This calculation represents the fact that if
11328you multiply some number in the range @samp{[2 ..@: 4]} by some other
11329number in the range @samp{[0.5 ..@: 2]}, your result will lie in the range
11330from 1 to 8. Interval arithmetic is used to get a worst-case estimate
11331of the possible range of values a computation will produce, given the
11332set of possible values of the input.
11333
11334@ifnottex
11335Calc supports several varieties of intervals, including @dfn{closed}
11336intervals of the type shown above, @dfn{open} intervals such as
11337@samp{(2 ..@: 4)}, which represents the range of numbers from 2 to 4
11338@emph{exclusive}, and @dfn{semi-open} intervals in which one end
11339uses a round parenthesis and the other a square bracket. In mathematical
11340terms,
11341@samp{[2 ..@: 4]} means @expr{2 <= x <= 4}, whereas
11342@samp{[2 ..@: 4)} represents @expr{2 <= x < 4},
11343@samp{(2 ..@: 4]} represents @expr{2 < x <= 4}, and
11344@samp{(2 ..@: 4)} represents @expr{2 < x < 4}.
11345@end ifnottex
11346@tex
11347Calc supports several varieties of intervals, including \dfn{closed}
11348intervals of the type shown above, \dfn{open} intervals such as
11349\samp{(2 ..\: 4)}, which represents the range of numbers from 2 to 4
11350\emph{exclusive}, and \dfn{semi-open} intervals in which one end
11351uses a round parenthesis and the other a square bracket. In mathematical
11352terms,
11353$$ \eqalign{
11354 [2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 \le x \le 4 \cr
11355 [2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 \le x < 4 \cr
11356 (2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 < x \le 4 \cr
11357 (2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 < x < 4 \cr
11358} $$
11359@end tex
11360
11361The lower and upper limits of an interval must be either real numbers
11362(or HMS or date forms), or symbolic expressions which are assumed to be
11363real-valued, or @samp{-inf} and @samp{inf}. In general the lower limit
11364must be less than the upper limit. A closed interval containing only
11365one value, @samp{[3 ..@: 3]}, is converted to a plain number (3)
11366automatically. An interval containing no values at all (such as
11367@samp{[3 ..@: 2]} or @samp{[2 ..@: 2)}) can be represented but is not
11368guaranteed to behave well when used in arithmetic. Note that the
11369interval @samp{[3 .. inf)} represents all real numbers greater than
11370or equal to 3, and @samp{(-inf .. inf)} represents all real numbers.
11371In fact, @samp{[-inf .. inf]} represents all real numbers including
11372the real infinities.
11373
11374Intervals are entered in the notation shown here, either as algebraic
11375formulas, or using incomplete forms. (@xref{Incomplete Objects}.)
11376In algebraic formulas, multiple periods in a row are collected from
11377left to right, so that @samp{1...1e2} is interpreted as @samp{1.0 ..@: 1e2}
11378rather than @samp{1 ..@: 0.1e2}. Add spaces or zeros if you want to
11379get the other interpretation. If you omit the lower or upper limit,
11380a default of @samp{-inf} or @samp{inf} (respectively) is furnished.
11381
11382Infinite mode also affects operations on intervals
11383(@pxref{Infinities}). Calc will always introduce an open infinity,
11384as in @samp{1 / (0 .. 2] = [0.5 .. inf)}. But closed infinities,
11385@w{@samp{1 / [0 .. 2] = [0.5 .. inf]}}, arise only in Infinite mode;
11386otherwise they are left unevaluated. Note that the ``direction'' of
11387a zero is not an issue in this case since the zero is always assumed
11388to be continuous with the rest of the interval. For intervals that
11389contain zero inside them Calc is forced to give the result,
11390@samp{1 / (-2 .. 2) = [-inf .. inf]}.
11391
11392While it may seem that intervals and error forms are similar, they are
11393based on entirely different concepts of inexact quantities. An error
11394form
11395@texline `@var{x} @tfn{+/-} @math{\sigma}'
11396@infoline `@var{x} @tfn{+/-} @var{sigma}'
11397means a variable is random, and its value could
11398be anything but is ``probably'' within one
11399@texline @math{\sigma}
11400@infoline @var{sigma}
11401of the mean value @expr{x}. An interval
11402`@tfn{[}@var{a} @tfn{..@:} @var{b}@tfn{]}' means a
11403variable's value is unknown, but guaranteed to lie in the specified
11404range. Error forms are statistical or ``average case'' approximations;
11405interval arithmetic tends to produce ``worst case'' bounds on an
11406answer.
11407
11408Intervals may not contain complex numbers, but they may contain
11409HMS forms or date forms.
11410
11411@xref{Set Operations}, for commands that interpret interval forms
11412as subsets of the set of real numbers.
11413
11414@ignore
11415@starindex
11416@end ignore
11417@tindex intv
11418The algebraic function @samp{intv(n, a, b)} builds an interval form
11419from @samp{a} to @samp{b}; @samp{n} is an integer code which must
11420be 0 for @samp{(..)}, 1 for @samp{(..]}, 2 for @samp{[..)}, or
114213 for @samp{[..]}.
11422
11423Please note that in fully rigorous interval arithmetic, care would be
11424taken to make sure that the computation of the lower bound rounds toward
11425minus infinity, while upper bound computations round toward plus
11426infinity. Calc's arithmetic always uses a round-to-nearest mode,
11427which means that roundoff errors could creep into an interval
11428calculation to produce intervals slightly smaller than they ought to
11429be. For example, entering @samp{[1..2]} and pressing @kbd{Q 2 ^}
11430should yield the interval @samp{[1..2]} again, but in fact it yields the
11431(slightly too small) interval @samp{[1..1.9999999]} due to roundoff
11432error.
11433
11434@node Incomplete Objects, Variables, Interval Forms, Data Types
11435@section Incomplete Objects
11436
11437@noindent
11438@ignore
11439@mindex [ ]
11440@end ignore
11441@kindex [
11442@ignore
11443@mindex ( )
11444@end ignore
11445@kindex (
11446@kindex ,
11447@ignore
11448@mindex @null
11449@end ignore
11450@kindex ]
11451@ignore
11452@mindex @null
11453@end ignore
11454@kindex )
11455@cindex Incomplete vectors
11456@cindex Incomplete complex numbers
11457@cindex Incomplete interval forms
11458When @kbd{(} or @kbd{[} is typed to begin entering a complex number or
11459vector, respectively, the effect is to push an @dfn{incomplete} complex
11460number or vector onto the stack. The @kbd{,} key adds the value(s) at
11461the top of the stack onto the current incomplete object. The @kbd{)}
11462and @kbd{]} keys ``close'' the incomplete object after adding any values
11463on the top of the stack in front of the incomplete object.
11464
11465As a result, the sequence of keystrokes @kbd{[ 2 , 3 @key{RET} 2 * , 9 ]}
11466pushes the vector @samp{[2, 6, 9]} onto the stack. Likewise, @kbd{( 1 , 2 Q )}
11467pushes the complex number @samp{(1, 1.414)} (approximately).
11468
11469If several values lie on the stack in front of the incomplete object,
11470all are collected and appended to the object. Thus the @kbd{,} key
11471is redundant: @kbd{[ 2 @key{RET} 3 @key{RET} 2 * 9 ]}. Some people
11472prefer the equivalent @key{SPC} key to @key{RET}.
11473
11474As a special case, typing @kbd{,} immediately after @kbd{(}, @kbd{[}, or
11475@kbd{,} adds a zero or duplicates the preceding value in the list being
11476formed. Typing @key{DEL} during incomplete entry removes the last item
11477from the list.
11478
11479@kindex ;
11480The @kbd{;} key is used in the same way as @kbd{,} to create polar complex
11481numbers: @kbd{( 1 ; 2 )}. When entering a vector, @kbd{;} is useful for
11482creating a matrix. In particular, @kbd{[ [ 1 , 2 ; 3 , 4 ; 5 , 6 ] ]} is
11483equivalent to @kbd{[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]}.
11484
11485@kindex ..
11486@pindex calc-dots
11487Incomplete entry is also used to enter intervals. For example,
11488@kbd{[ 2 ..@: 4 )} enters a semi-open interval. Note that when you type
11489the first period, it will be interpreted as a decimal point, but when
11490you type a second period immediately afterward, it is re-interpreted as
11491part of the interval symbol. Typing @kbd{..} corresponds to executing
11492the @code{calc-dots} command.
11493
11494If you find incomplete entry distracting, you may wish to enter vectors
11495and complex numbers as algebraic formulas by pressing the apostrophe key.
11496
11497@node Variables, Formulas, Incomplete Objects, Data Types
11498@section Variables
11499
11500@noindent
11501@cindex Variables, in formulas
11502A @dfn{variable} is somewhere between a storage register on a conventional
11503calculator, and a variable in a programming language. (In fact, a Calc
11504variable is really just an Emacs Lisp variable that contains a Calc number
11505or formula.) A variable's name is normally composed of letters and digits.
11506Calc also allows apostrophes and @code{#} signs in variable names.
11507(The Calc variable @code{foo} corresponds to the Emacs Lisp variable
11508@code{var-foo}, but unless you access the variable from within Emacs
11509Lisp, you don't need to worry about it. Variable names in algebraic
11510formulas implicitly have @samp{var-} prefixed to their names. The
11511@samp{#} character in variable names used in algebraic formulas
11512corresponds to a dash @samp{-} in the Lisp variable name. If the name
11513contains any dashes, the prefix @samp{var-} is @emph{not} automatically
11514added. Thus the two formulas @samp{foo + 1} and @samp{var#foo + 1} both
11515refer to the same variable.)
11516
11517In a command that takes a variable name, you can either type the full
11518name of a variable, or type a single digit to use one of the special
11519convenience variables @code{q0} through @code{q9}. For example,
11520@kbd{3 s s 2} stores the number 3 in variable @code{q2}, and
11521@w{@kbd{3 s s foo @key{RET}}} stores that number in variable
11522@code{foo}.
11523
11524To push a variable itself (as opposed to the variable's value) on the
11525stack, enter its name as an algebraic expression using the apostrophe
11526(@key{'}) key.
11527
11528@kindex =
11529@pindex calc-evaluate
11530@cindex Evaluation of variables in a formula
11531@cindex Variables, evaluation
11532@cindex Formulas, evaluation
11533The @kbd{=} (@code{calc-evaluate}) key ``evaluates'' a formula by
11534replacing all variables in the formula which have been given values by a
11535@code{calc-store} or @code{calc-let} command by their stored values.
11536Other variables are left alone. Thus a variable that has not been
11537stored acts like an abstract variable in algebra; a variable that has
11538been stored acts more like a register in a traditional calculator.
11539With a positive numeric prefix argument, @kbd{=} evaluates the top
11540@var{n} stack entries; with a negative argument, @kbd{=} evaluates
11541the @var{n}th stack entry.
11542
11543@cindex @code{e} variable
11544@cindex @code{pi} variable
11545@cindex @code{i} variable
11546@cindex @code{phi} variable
11547@cindex @code{gamma} variable
11548@vindex e
11549@vindex pi
11550@vindex i
11551@vindex phi
11552@vindex gamma
11553A few variables are called @dfn{special constants}. Their names are
11554@samp{e}, @samp{pi}, @samp{i}, @samp{phi}, and @samp{gamma}.
11555(@xref{Scientific Functions}.) When they are evaluated with @kbd{=},
11556their values are calculated if necessary according to the current precision
11557or complex polar mode. If you wish to use these symbols for other purposes,
11558simply undefine or redefine them using @code{calc-store}.
11559
11560The variables @samp{inf}, @samp{uinf}, and @samp{nan} stand for
11561infinite or indeterminate values. It's best not to use them as
11562regular variables, since Calc uses special algebraic rules when
11563it manipulates them. Calc displays a warning message if you store
11564a value into any of these special variables.
11565
11566@xref{Store and Recall}, for a discussion of commands dealing with variables.
11567
11568@node Formulas, , Variables, Data Types
11569@section Formulas
11570
11571@noindent
11572@cindex Formulas
11573@cindex Expressions
11574@cindex Operators in formulas
11575@cindex Precedence of operators
11576When you press the apostrophe key you may enter any expression or formula
11577in algebraic form. (Calc uses the terms ``expression'' and ``formula''
11578interchangeably.) An expression is built up of numbers, variable names,
11579and function calls, combined with various arithmetic operators.
11580Parentheses may
11581be used to indicate grouping. Spaces are ignored within formulas, except
11582that spaces are not permitted within variable names or numbers.
11583Arithmetic operators, in order from highest to lowest precedence, and
11584with their equivalent function names, are:
11585
11586@samp{_} [@code{subscr}] (subscripts);
11587
11588postfix @samp{%} [@code{percent}] (as in @samp{25% = 0.25});
11589
0edd2970 11590prefix @samp{!} [@code{lnot}] (logical ``not,'' as in @samp{!x});
4009494e
GM
11591
11592@samp{+/-} [@code{sdev}] (the standard deviation symbol) and
11593@samp{mod} [@code{makemod}] (the symbol for modulo forms);
11594
11595postfix @samp{!} [@code{fact}] (factorial, as in @samp{n!})
11596and postfix @samp{!!} [@code{dfact}] (double factorial);
11597
11598@samp{^} [@code{pow}] (raised-to-the-power-of);
11599
0edd2970
JB
11600prefix @samp{+} and @samp{-} [@code{neg}] (as in @samp{-x});
11601
4009494e
GM
11602@samp{*} [@code{mul}];
11603
11604@samp{/} [@code{div}], @samp{%} [@code{mod}] (modulo), and
11605@samp{\} [@code{idiv}] (integer division);
11606
11607infix @samp{+} [@code{add}] and @samp{-} [@code{sub}] (as in @samp{x-y});
11608
11609@samp{|} [@code{vconcat}] (vector concatenation);
11610
11611relations @samp{=} [@code{eq}], @samp{!=} [@code{neq}], @samp{<} [@code{lt}],
11612@samp{>} [@code{gt}], @samp{<=} [@code{leq}], and @samp{>=} [@code{geq}];
11613
11614@samp{&&} [@code{land}] (logical ``and'');
11615
11616@samp{||} [@code{lor}] (logical ``or'');
11617
11618the C-style ``if'' operator @samp{a?b:c} [@code{if}];
11619
11620@samp{!!!} [@code{pnot}] (rewrite pattern ``not'');
11621
11622@samp{&&&} [@code{pand}] (rewrite pattern ``and'');
11623
11624@samp{|||} [@code{por}] (rewrite pattern ``or'');
11625
11626@samp{:=} [@code{assign}] (for assignments and rewrite rules);
11627
11628@samp{::} [@code{condition}] (rewrite pattern condition);
11629
11630@samp{=>} [@code{evalto}].
11631
11632Note that, unlike in usual computer notation, multiplication binds more
11633strongly than division: @samp{a*b/c*d} is equivalent to
11634@texline @math{a b \over c d}.
11635@infoline @expr{(a*b)/(c*d)}.
11636
11637@cindex Multiplication, implicit
11638@cindex Implicit multiplication
11639The multiplication sign @samp{*} may be omitted in many cases. In particular,
11640if the righthand side is a number, variable name, or parenthesized
11641expression, the @samp{*} may be omitted. Implicit multiplication has the
11642same precedence as the explicit @samp{*} operator. The one exception to
11643the rule is that a variable name followed by a parenthesized expression,
11644as in @samp{f(x)},
11645is interpreted as a function call, not an implicit @samp{*}. In many
11646cases you must use a space if you omit the @samp{*}: @samp{2a} is the
11647same as @samp{2*a}, and @samp{a b} is the same as @samp{a*b}, but @samp{ab}
11648is a variable called @code{ab}, @emph{not} the product of @samp{a} and
11649@samp{b}! Also note that @samp{f (x)} is still a function call.
11650
11651@cindex Implicit comma in vectors
11652The rules are slightly different for vectors written with square brackets.
11653In vectors, the space character is interpreted (like the comma) as a
11654separator of elements of the vector. Thus @w{@samp{[ 2a b+c d ]}} is
11655equivalent to @samp{[2*a, b+c, d]}, whereas @samp{2a b+c d} is equivalent
11656to @samp{2*a*b + c*d}.
11657Note that spaces around the brackets, and around explicit commas, are
11658ignored. To force spaces to be interpreted as multiplication you can
11659enclose a formula in parentheses as in @samp{[(a b) 2(c d)]}, which is
11660interpreted as @samp{[a*b, 2*c*d]}. An implicit comma is also inserted
11661between @samp{][}, as in the matrix @samp{[[1 2][3 4]]}.
11662
11663Vectors that contain commas (not embedded within nested parentheses or
11664brackets) do not treat spaces specially: @samp{[a b, 2 c d]} is a vector
11665of two elements. Also, if it would be an error to treat spaces as
11666separators, but not otherwise, then Calc will ignore spaces:
11667@w{@samp{[a - b]}} is a vector of one element, but @w{@samp{[a -b]}} is
11668a vector of two elements. Finally, vectors entered with curly braces
11669instead of square brackets do not give spaces any special treatment.
11670When Calc displays a vector that does not contain any commas, it will
11671insert parentheses if necessary to make the meaning clear:
11672@w{@samp{[(a b)]}}.
11673
11674The expression @samp{5%-2} is ambiguous; is this five-percent minus two,
11675or five modulo minus-two? Calc always interprets the leftmost symbol as
11676an infix operator preferentially (modulo, in this case), so you would
11677need to write @samp{(5%)-2} to get the former interpretation.
11678
11679@cindex Function call notation
11680A function call is, e.g., @samp{sin(1+x)}. (The Calc algebraic function
11681@code{foo} corresponds to the Emacs Lisp function @code{calcFunc-foo},
11682but unless you access the function from within Emacs Lisp, you don't
11683need to worry about it.) Most mathematical Calculator commands like
11684@code{calc-sin} have function equivalents like @code{sin}.
11685If no Lisp function is defined for a function called by a formula, the
11686call is left as it is during algebraic manipulation: @samp{f(x+y)} is
11687left alone. Beware that many innocent-looking short names like @code{in}
11688and @code{re} have predefined meanings which could surprise you; however,
11689single letters or single letters followed by digits are always safe to
11690use for your own function names. @xref{Function Index}.
11691
11692In the documentation for particular commands, the notation @kbd{H S}
11693(@code{calc-sinh}) [@code{sinh}] means that the key sequence @kbd{H S}, the
11694command @kbd{M-x calc-sinh}, and the algebraic function @code{sinh(x)} all
11695represent the same operation.
11696
11697Commands that interpret (``parse'') text as algebraic formulas include
11698algebraic entry (@kbd{'}), editing commands like @kbd{`} which parse
11699the contents of the editing buffer when you finish, the @kbd{C-x * g}
11700and @w{@kbd{C-x * r}} commands, the @kbd{C-y} command, the X window system
11701``paste'' mouse operation, and Embedded mode. All of these operations
11702use the same rules for parsing formulas; in particular, language modes
11703(@pxref{Language Modes}) affect them all in the same way.
11704
11705When you read a large amount of text into the Calculator (say a vector
11706which represents a big set of rewrite rules; @pxref{Rewrite Rules}),
11707you may wish to include comments in the text. Calc's formula parser
11708ignores the symbol @samp{%%} and anything following it on a line:
11709
11710@example
11711[ a + b, %% the sum of "a" and "b"
11712 c + d,
11713 %% last line is coming up:
11714 e + f ]
11715@end example
11716
11717@noindent
11718This is parsed exactly the same as @samp{[ a + b, c + d, e + f ]}.
11719
11720@xref{Syntax Tables}, for a way to create your own operators and other
11721input notations. @xref{Compositions}, for a way to create new display
11722formats.
11723
11724@xref{Algebra}, for commands for manipulating formulas symbolically.
11725
11726@node Stack and Trail, Mode Settings, Data Types, Top
11727@chapter Stack and Trail Commands
11728
11729@noindent
11730This chapter describes the Calc commands for manipulating objects on the
11731stack and in the trail buffer. (These commands operate on objects of any
11732type, such as numbers, vectors, formulas, and incomplete objects.)
11733
11734@menu
11735* Stack Manipulation::
11736* Editing Stack Entries::
11737* Trail Commands::
11738* Keep Arguments::
11739@end menu
11740
11741@node Stack Manipulation, Editing Stack Entries, Stack and Trail, Stack and Trail
11742@section Stack Manipulation Commands
11743
11744@noindent
11745@kindex @key{RET}
11746@kindex @key{SPC}
11747@pindex calc-enter
11748@cindex Duplicating stack entries
11749To duplicate the top object on the stack, press @key{RET} or @key{SPC}
11750(two equivalent keys for the @code{calc-enter} command).
11751Given a positive numeric prefix argument, these commands duplicate
11752several elements at the top of the stack.
11753Given a negative argument,
11754these commands duplicate the specified element of the stack.
11755Given an argument of zero, they duplicate the entire stack.
11756For example, with @samp{10 20 30} on the stack,
11757@key{RET} creates @samp{10 20 30 30},
11758@kbd{C-u 2 @key{RET}} creates @samp{10 20 30 20 30},
11759@kbd{C-u - 2 @key{RET}} creates @samp{10 20 30 20}, and
11760@kbd{C-u 0 @key{RET}} creates @samp{10 20 30 10 20 30}.
11761
11762@kindex @key{LFD}
11763@pindex calc-over
11764The @key{LFD} (@code{calc-over}) command (on a key marked Line-Feed if you
11765have it, else on @kbd{C-j}) is like @code{calc-enter}
11766except that the sign of the numeric prefix argument is interpreted
11767oppositely. Also, with no prefix argument the default argument is 2.
11768Thus with @samp{10 20 30} on the stack, @key{LFD} and @kbd{C-u 2 @key{LFD}}
11769are both equivalent to @kbd{C-u - 2 @key{RET}}, producing
11770@samp{10 20 30 20}.
11771
11772@kindex @key{DEL}
11773@kindex C-d
11774@pindex calc-pop
11775@cindex Removing stack entries
11776@cindex Deleting stack entries
11777To remove the top element from the stack, press @key{DEL} (@code{calc-pop}).
11778The @kbd{C-d} key is a synonym for @key{DEL}.
11779(If the top element is an incomplete object with at least one element, the
11780last element is removed from it.) Given a positive numeric prefix argument,
11781several elements are removed. Given a negative argument, the specified
11782element of the stack is deleted. Given an argument of zero, the entire
11783stack is emptied.
11784For example, with @samp{10 20 30} on the stack,
11785@key{DEL} leaves @samp{10 20},
11786@kbd{C-u 2 @key{DEL}} leaves @samp{10},
11787@kbd{C-u - 2 @key{DEL}} leaves @samp{10 30}, and
11788@kbd{C-u 0 @key{DEL}} leaves an empty stack.
11789
11790@kindex M-@key{DEL}
11791@pindex calc-pop-above
11792The @kbd{M-@key{DEL}} (@code{calc-pop-above}) command is to @key{DEL} what
11793@key{LFD} is to @key{RET}: It interprets the sign of the numeric
11794prefix argument in the opposite way, and the default argument is 2.
11795Thus @kbd{M-@key{DEL}} by itself removes the second-from-top stack element,
11796leaving the first, third, fourth, and so on; @kbd{M-3 M-@key{DEL}} deletes
11797the third stack element.
11798
11799@kindex @key{TAB}
11800@pindex calc-roll-down
11801To exchange the top two elements of the stack, press @key{TAB}
11802(@code{calc-roll-down}). Given a positive numeric prefix argument, the
11803specified number of elements at the top of the stack are rotated downward.
11804Given a negative argument, the entire stack is rotated downward the specified
11805number of times. Given an argument of zero, the entire stack is reversed
11806top-for-bottom.
11807For example, with @samp{10 20 30 40 50} on the stack,
11808@key{TAB} creates @samp{10 20 30 50 40},
11809@kbd{C-u 3 @key{TAB}} creates @samp{10 20 50 30 40},
11810@kbd{C-u - 2 @key{TAB}} creates @samp{40 50 10 20 30}, and
11811@kbd{C-u 0 @key{TAB}} creates @samp{50 40 30 20 10}.
11812
11813@kindex M-@key{TAB}
11814@pindex calc-roll-up
11815The command @kbd{M-@key{TAB}} (@code{calc-roll-up}) is analogous to @key{TAB}
11816except that it rotates upward instead of downward. Also, the default
11817with no prefix argument is to rotate the top 3 elements.
11818For example, with @samp{10 20 30 40 50} on the stack,
11819@kbd{M-@key{TAB}} creates @samp{10 20 40 50 30},
11820@kbd{C-u 4 M-@key{TAB}} creates @samp{10 30 40 50 20},
11821@kbd{C-u - 2 M-@key{TAB}} creates @samp{30 40 50 10 20}, and
11822@kbd{C-u 0 M-@key{TAB}} creates @samp{50 40 30 20 10}.
11823
11824A good way to view the operation of @key{TAB} and @kbd{M-@key{TAB}} is in
11825terms of moving a particular element to a new position in the stack.
11826With a positive argument @var{n}, @key{TAB} moves the top stack
11827element down to level @var{n}, making room for it by pulling all the
11828intervening stack elements toward the top. @kbd{M-@key{TAB}} moves the
11829element at level @var{n} up to the top. (Compare with @key{LFD},
11830which copies instead of moving the element in level @var{n}.)
11831
11832With a negative argument @mathit{-@var{n}}, @key{TAB} rotates the stack
11833to move the object in level @var{n} to the deepest place in the
11834stack, and the object in level @mathit{@var{n}+1} to the top. @kbd{M-@key{TAB}}
11835rotates the deepest stack element to be in level @mathit{n}, also
11836putting the top stack element in level @mathit{@var{n}+1}.
11837
11838@xref{Selecting Subformulas}, for a way to apply these commands to
11839any portion of a vector or formula on the stack.
11840
11841@node Editing Stack Entries, Trail Commands, Stack Manipulation, Stack and Trail
11842@section Editing Stack Entries
11843
11844@noindent
11845@kindex `
11846@pindex calc-edit
11847@pindex calc-edit-finish
11848@cindex Editing the stack with Emacs
8dc6104d
JB
11849The @kbd{`} (@code{calc-edit}) command creates a temporary buffer
11850(@samp{*Calc Edit*}) for editing the top-of-stack value using regular
11851Emacs commands. Note that @kbd{`} is a backquote, not a quote. With a
11852numeric prefix argument, it edits the specified number of stack entries
11853at once. (An argument of zero edits the entire stack; a negative
11854argument edits one specific stack entry.)
4009494e
GM
11855
11856When you are done editing, press @kbd{C-c C-c} to finish and return
11857to Calc. The @key{RET} and @key{LFD} keys also work to finish most
11858sorts of editing, though in some cases Calc leaves @key{RET} with its
11859usual meaning (``insert a newline'') if it's a situation where you
11860might want to insert new lines into the editing buffer.
11861
11862When you finish editing, the Calculator parses the lines of text in
11863the @samp{*Calc Edit*} buffer as numbers or formulas, replaces the
11864original stack elements in the original buffer with these new values,
11865then kills the @samp{*Calc Edit*} buffer. The original Calculator buffer
11866continues to exist during editing, but for best results you should be
11867careful not to change it until you have finished the edit. You can
11868also cancel the edit by killing the buffer with @kbd{C-x k}.
11869
11870The formula is normally reevaluated as it is put onto the stack.
11871For example, editing @samp{a + 2} to @samp{3 + 2} and pressing
11872@kbd{C-c C-c} will push 5 on the stack. If you use @key{LFD} to
11873finish, Calc will put the result on the stack without evaluating it.
11874
11875If you give a prefix argument to @kbd{C-c C-c},
11876Calc will not kill the @samp{*Calc Edit*} buffer. You can switch
11877back to that buffer and continue editing if you wish. However, you
11878should understand that if you initiated the edit with @kbd{`}, the
11879@kbd{C-c C-c} operation will be programmed to replace the top of the
11880stack with the new edited value, and it will do this even if you have
11881rearranged the stack in the meanwhile. This is not so much of a problem
11882with other editing commands, though, such as @kbd{s e}
11883(@code{calc-edit-variable}; @pxref{Operations on Variables}).
11884
11885If the @code{calc-edit} command involves more than one stack entry,
11886each line of the @samp{*Calc Edit*} buffer is interpreted as a
11887separate formula. Otherwise, the entire buffer is interpreted as
11888one formula, with line breaks ignored. (You can use @kbd{C-o} or
11889@kbd{C-q C-j} to insert a newline in the buffer without pressing @key{RET}.)
11890
11891The @kbd{`} key also works during numeric or algebraic entry. The
11892text entered so far is moved to the @code{*Calc Edit*} buffer for
11893more extensive editing than is convenient in the minibuffer.
11894
11895@node Trail Commands, Keep Arguments, Editing Stack Entries, Stack and Trail
11896@section Trail Commands
11897
11898@noindent
11899@cindex Trail buffer
11900The commands for manipulating the Calc Trail buffer are two-key sequences
11901beginning with the @kbd{t} prefix.
11902
11903@kindex t d
11904@pindex calc-trail-display
11905The @kbd{t d} (@code{calc-trail-display}) command turns display of the
11906trail on and off. Normally the trail display is toggled on if it was off,
11907off if it was on. With a numeric prefix of zero, this command always
11908turns the trail off; with a prefix of one, it always turns the trail on.
11909The other trail-manipulation commands described here automatically turn
11910the trail on. Note that when the trail is off values are still recorded
11911there; they are simply not displayed. To set Emacs to turn the trail
11912off by default, type @kbd{t d} and then save the mode settings with
11913@kbd{m m} (@code{calc-save-modes}).
11914
11915@kindex t i
11916@pindex calc-trail-in
11917@kindex t o
11918@pindex calc-trail-out
11919The @kbd{t i} (@code{calc-trail-in}) and @kbd{t o}
11920(@code{calc-trail-out}) commands switch the cursor into and out of the
11921Calc Trail window. In practice they are rarely used, since the commands
11922shown below are a more convenient way to move around in the
11923trail, and they work ``by remote control'' when the cursor is still
11924in the Calculator window.
11925
11926@cindex Trail pointer
11927There is a @dfn{trail pointer} which selects some entry of the trail at
11928any given time. The trail pointer looks like a @samp{>} symbol right
11929before the selected number. The following commands operate on the
11930trail pointer in various ways.
11931
11932@kindex t y
11933@pindex calc-trail-yank
11934@cindex Retrieving previous results
11935The @kbd{t y} (@code{calc-trail-yank}) command reads the selected value in
11936the trail and pushes it onto the Calculator stack. It allows you to
11937re-use any previously computed value without retyping. With a numeric
11938prefix argument @var{n}, it yanks the value @var{n} lines above the current
11939trail pointer.
11940
11941@kindex t <
11942@pindex calc-trail-scroll-left
11943@kindex t >
11944@pindex calc-trail-scroll-right
11945The @kbd{t <} (@code{calc-trail-scroll-left}) and @kbd{t >}
11946(@code{calc-trail-scroll-right}) commands horizontally scroll the trail
11947window left or right by one half of its width.
11948
11949@kindex t n
11950@pindex calc-trail-next
11951@kindex t p
11952@pindex calc-trail-previous
11953@kindex t f
11954@pindex calc-trail-forward
11955@kindex t b
11956@pindex calc-trail-backward
11957The @kbd{t n} (@code{calc-trail-next}) and @kbd{t p}
11958(@code{calc-trail-previous)} commands move the trail pointer down or up
11959one line. The @kbd{t f} (@code{calc-trail-forward}) and @kbd{t b}
11960(@code{calc-trail-backward}) commands move the trail pointer down or up
11961one screenful at a time. All of these commands accept numeric prefix
11962arguments to move several lines or screenfuls at a time.
11963
11964@kindex t [
11965@pindex calc-trail-first
11966@kindex t ]
11967@pindex calc-trail-last
11968@kindex t h
11969@pindex calc-trail-here
11970The @kbd{t [} (@code{calc-trail-first}) and @kbd{t ]}
11971(@code{calc-trail-last}) commands move the trail pointer to the first or
11972last line of the trail. The @kbd{t h} (@code{calc-trail-here}) command
11973moves the trail pointer to the cursor position; unlike the other trail
11974commands, @kbd{t h} works only when Calc Trail is the selected window.
11975
11976@kindex t s
11977@pindex calc-trail-isearch-forward
11978@kindex t r
11979@pindex calc-trail-isearch-backward
11980@ifnottex
11981The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
11982(@code{calc-trail-isearch-backward}) commands perform an incremental
11983search forward or backward through the trail. You can press @key{RET}
11984to terminate the search; the trail pointer moves to the current line.
11985If you cancel the search with @kbd{C-g}, the trail pointer stays where
11986it was when the search began.
11987@end ifnottex
11988@tex
11989The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
11990(@code{calc-trail-isearch-backward}) com\-mands perform an incremental
11991search forward or backward through the trail. You can press @key{RET}
11992to terminate the search; the trail pointer moves to the current line.
11993If you cancel the search with @kbd{C-g}, the trail pointer stays where
11994it was when the search began.
11995@end tex
11996
11997@kindex t m
11998@pindex calc-trail-marker
11999The @kbd{t m} (@code{calc-trail-marker}) command allows you to enter a
12000line of text of your own choosing into the trail. The text is inserted
12001after the line containing the trail pointer; this usually means it is
12002added to the end of the trail. Trail markers are useful mainly as the
12003targets for later incremental searches in the trail.
12004
12005@kindex t k
12006@pindex calc-trail-kill
12007The @kbd{t k} (@code{calc-trail-kill}) command removes the selected line
12008from the trail. The line is saved in the Emacs kill ring suitable for
12009yanking into another buffer, but it is not easy to yank the text back
12010into the trail buffer. With a numeric prefix argument, this command
12011kills the @var{n} lines below or above the selected one.
12012
12013The @kbd{t .} (@code{calc-full-trail-vectors}) command is described
12014elsewhere; @pxref{Vector and Matrix Formats}.
12015
12016@node Keep Arguments, , Trail Commands, Stack and Trail
12017@section Keep Arguments
12018
12019@noindent
12020@kindex K
12021@pindex calc-keep-args
12022The @kbd{K} (@code{calc-keep-args}) command acts like a prefix for
12023the following command. It prevents that command from removing its
12024arguments from the stack. For example, after @kbd{2 @key{RET} 3 +},
12025the stack contains the sole number 5, but after @kbd{2 @key{RET} 3 K +},
12026the stack contains the arguments and the result: @samp{2 3 5}.
12027
12028With the exception of keyboard macros, this works for all commands that
12029take arguments off the stack. (To avoid potentially unpleasant behavior,
12030a @kbd{K} prefix before a keyboard macro will be ignored. A @kbd{K}
12031prefix called @emph{within} the keyboard macro will still take effect.)
12032As another example, @kbd{K a s} simplifies a formula, pushing the
12033simplified version of the formula onto the stack after the original
12034formula (rather than replacing the original formula). Note that you
12035could get the same effect by typing @kbd{@key{RET} a s}, copying the
12036formula and then simplifying the copy. One difference is that for a very
12037large formula the time taken to format the intermediate copy in
12038@kbd{@key{RET} a s} could be noticeable; @kbd{K a s} would avoid this
12039extra work.
12040
12041Even stack manipulation commands are affected. @key{TAB} works by
12042popping two values and pushing them back in the opposite order,
12043so @kbd{2 @key{RET} 3 K @key{TAB}} produces @samp{2 3 3 2}.
12044
12045A few Calc commands provide other ways of doing the same thing.
12046For example, @kbd{' sin($)} replaces the number on the stack with
12047its sine using algebraic entry; to push the sine and keep the
12048original argument you could use either @kbd{' sin($1)} or
12049@kbd{K ' sin($)}. @xref{Algebraic Entry}. Also, the @kbd{s s}
12050command is effectively the same as @kbd{K s t}. @xref{Storing Variables}.
12051
12052If you execute a command and then decide you really wanted to keep
12053the argument, you can press @kbd{M-@key{RET}} (@code{calc-last-args}).
12054This command pushes the last arguments that were popped by any command
12055onto the stack. Note that the order of things on the stack will be
12056different than with @kbd{K}: @kbd{2 @key{RET} 3 + M-@key{RET}} leaves
12057@samp{5 2 3} on the stack instead of @samp{2 3 5}. @xref{Undo}.
12058
12059@node Mode Settings, Arithmetic, Stack and Trail, Top
12060@chapter Mode Settings
12061
12062@noindent
12063This chapter describes commands that set modes in the Calculator.
12064They do not affect the contents of the stack, although they may change
12065the @emph{appearance} or @emph{interpretation} of the stack's contents.
12066
12067@menu
12068* General Mode Commands::
12069* Precision::
12070* Inverse and Hyperbolic::
12071* Calculation Modes::
12072* Simplification Modes::
12073* Declarations::
12074* Display Modes::
12075* Language Modes::
12076* Modes Variable::
12077* Calc Mode Line::
12078@end menu
12079
12080@node General Mode Commands, Precision, Mode Settings, Mode Settings
12081@section General Mode Commands
12082
12083@noindent
12084@kindex m m
12085@pindex calc-save-modes
12086@cindex Continuous memory
12087@cindex Saving mode settings
12088@cindex Permanent mode settings
12089@cindex Calc init file, mode settings
12090You can save all of the current mode settings in your Calc init file
12091(the file given by the variable @code{calc-settings-file}, typically
12092@file{~/.calc.el}) with the @kbd{m m} (@code{calc-save-modes}) command.
12093This will cause Emacs to reestablish these modes each time it starts up.
12094The modes saved in the file include everything controlled by the @kbd{m}
12095and @kbd{d} prefix keys, the current precision and binary word size,
12096whether or not the trail is displayed, the current height of the Calc
12097window, and more. The current interface (used when you type @kbd{C-x * *})
12098is also saved. If there were already saved mode settings in the
12099file, they are replaced. Otherwise, the new mode information is
12100appended to the end of the file.
12101
12102@kindex m R
12103@pindex calc-mode-record-mode
12104The @kbd{m R} (@code{calc-mode-record-mode}) command tells Calc to
12105record all the mode settings (as if by pressing @kbd{m m}) every
12106time a mode setting changes. If the modes are saved this way, then this
12107``automatic mode recording'' mode is also saved.
12108Type @kbd{m R} again to disable this method of recording the mode
12109settings. To turn it off permanently, the @kbd{m m} command will also be
12110necessary. (If Embedded mode is enabled, other options for recording
12111the modes are available; @pxref{Mode Settings in Embedded Mode}.)
12112
12113@kindex m F
12114@pindex calc-settings-file-name
12115The @kbd{m F} (@code{calc-settings-file-name}) command allows you to
12116choose a different file than the current value of @code{calc-settings-file}
12117for @kbd{m m}, @kbd{Z P}, and similar commands to save permanent information.
12118You are prompted for a file name. All Calc modes are then reset to
12119their default values, then settings from the file you named are loaded
12120if this file exists, and this file becomes the one that Calc will
12121use in the future for commands like @kbd{m m}. The default settings
12122file name is @file{~/.calc.el}. You can see the current file name by
12123giving a blank response to the @kbd{m F} prompt. See also the
12124discussion of the @code{calc-settings-file} variable; @pxref{Customizing Calc}.
12125
12126If the file name you give is your user init file (typically
12127@file{~/.emacs}), @kbd{m F} will not automatically load the new file. This
12128is because your user init file may contain other things you don't want
12129to reread. You can give
12130a numeric prefix argument of 1 to @kbd{m F} to force it to read the
12131file no matter what. Conversely, an argument of @mathit{-1} tells
12132@kbd{m F} @emph{not} to read the new file. An argument of 2 or @mathit{-2}
12133tells @kbd{m F} not to reset the modes to their defaults beforehand,
12134which is useful if you intend your new file to have a variant of the
12135modes present in the file you were using before.
12136
12137@kindex m x
12138@pindex calc-always-load-extensions
12139The @kbd{m x} (@code{calc-always-load-extensions}) command enables a mode
12140in which the first use of Calc loads the entire program, including all
12141extensions modules. Otherwise, the extensions modules will not be loaded
12142until the various advanced Calc features are used. Since this mode only
12143has effect when Calc is first loaded, @kbd{m x} is usually followed by
12144@kbd{m m} to make the mode-setting permanent. To load all of Calc just
12145once, rather than always in the future, you can press @kbd{C-x * L}.
12146
12147@kindex m S
12148@pindex calc-shift-prefix
12149The @kbd{m S} (@code{calc-shift-prefix}) command enables a mode in which
12150all of Calc's letter prefix keys may be typed shifted as well as unshifted.
12151If you are typing, say, @kbd{a S} (@code{calc-solve-for}) quite often
12152you might find it easier to turn this mode on so that you can type
12153@kbd{A S} instead. When this mode is enabled, the commands that used to
12154be on those single shifted letters (e.g., @kbd{A} (@code{calc-abs})) can
12155now be invoked by pressing the shifted letter twice: @kbd{A A}. Note
12156that the @kbd{v} prefix key always works both shifted and unshifted, and
12157the @kbd{z} and @kbd{Z} prefix keys are always distinct. Also, the @kbd{h}
12158prefix is not affected by this mode. Press @kbd{m S} again to disable
12159shifted-prefix mode.
12160
12161@node Precision, Inverse and Hyperbolic, General Mode Commands, Mode Settings
12162@section Precision
12163
12164@noindent
12165@kindex p
12166@pindex calc-precision
12167@cindex Precision of calculations
12168The @kbd{p} (@code{calc-precision}) command controls the precision to
12169which floating-point calculations are carried. The precision must be
12170at least 3 digits and may be arbitrarily high, within the limits of
12171memory and time. This affects only floats: Integer and rational
12172calculations are always carried out with as many digits as necessary.
12173
12174The @kbd{p} key prompts for the current precision. If you wish you
12175can instead give the precision as a numeric prefix argument.
12176
12177Many internal calculations are carried to one or two digits higher
12178precision than normal. Results are rounded down afterward to the
12179current precision. Unless a special display mode has been selected,
12180floats are always displayed with their full stored precision, i.e.,
12181what you see is what you get. Reducing the current precision does not
12182round values already on the stack, but those values will be rounded
12183down before being used in any calculation. The @kbd{c 0} through
12184@kbd{c 9} commands (@pxref{Conversions}) can be used to round an
12185existing value to a new precision.
12186
12187@cindex Accuracy of calculations
12188It is important to distinguish the concepts of @dfn{precision} and
12189@dfn{accuracy}. In the normal usage of these words, the number
12190123.4567 has a precision of 7 digits but an accuracy of 4 digits.
12191The precision is the total number of digits not counting leading
12192or trailing zeros (regardless of the position of the decimal point).
12193The accuracy is simply the number of digits after the decimal point
12194(again not counting trailing zeros). In Calc you control the precision,
12195not the accuracy of computations. If you were to set the accuracy
12196instead, then calculations like @samp{exp(100)} would generate many
12197more digits than you would typically need, while @samp{exp(-100)} would
12198probably round to zero! In Calc, both these computations give you
12199exactly 12 (or the requested number of) significant digits.
12200
12201The only Calc features that deal with accuracy instead of precision
12202are fixed-point display mode for floats (@kbd{d f}; @pxref{Float Formats}),
12203and the rounding functions like @code{floor} and @code{round}
12204(@pxref{Integer Truncation}). Also, @kbd{c 0} through @kbd{c 9}
12205deal with both precision and accuracy depending on the magnitudes
12206of the numbers involved.
12207
12208If you need to work with a particular fixed accuracy (say, dollars and
12209cents with two digits after the decimal point), one solution is to work
12210with integers and an ``implied'' decimal point. For example, $8.99
12211divided by 6 would be entered @kbd{899 @key{RET} 6 /}, yielding 149.833
12212(actually $1.49833 with our implied decimal point); pressing @kbd{R}
12213would round this to 150 cents, i.e., $1.50.
12214
12215@xref{Floats}, for still more on floating-point precision and related
12216issues.
12217
12218@node Inverse and Hyperbolic, Calculation Modes, Precision, Mode Settings
12219@section Inverse and Hyperbolic Flags
12220
12221@noindent
12222@kindex I
12223@pindex calc-inverse
12224There is no single-key equivalent to the @code{calc-arcsin} function.
12225Instead, you must first press @kbd{I} (@code{calc-inverse}) to set
12226the @dfn{Inverse Flag}, then press @kbd{S} (@code{calc-sin}).
12227The @kbd{I} key actually toggles the Inverse Flag. When this flag
12228is set, the word @samp{Inv} appears in the mode line.
12229
12230@kindex H
12231@pindex calc-hyperbolic
12232Likewise, the @kbd{H} key (@code{calc-hyperbolic}) sets or clears the
12233Hyperbolic Flag, which transforms @code{calc-sin} into @code{calc-sinh}.
12234If both of these flags are set at once, the effect will be
12235@code{calc-arcsinh}. (The Hyperbolic flag is also used by some
12236non-trigonometric commands; for example @kbd{H L} computes a base-10,
12237instead of base-@mathit{e}, logarithm.)
12238
12239Command names like @code{calc-arcsin} are provided for completeness, and
12240may be executed with @kbd{x} or @kbd{M-x}. Their effect is simply to
12241toggle the Inverse and/or Hyperbolic flags and then execute the
12242corresponding base command (@code{calc-sin} in this case).
12243
12244The Inverse and Hyperbolic flags apply only to the next Calculator
12245command, after which they are automatically cleared. (They are also
12246cleared if the next keystroke is not a Calc command.) Digits you
12247type after @kbd{I} or @kbd{H} (or @kbd{K}) are treated as prefix
12248arguments for the next command, not as numeric entries. The same
12249is true of @kbd{C-u}, but not of the minus sign (@kbd{K -} means to
12250subtract and keep arguments).
12251
12252The third Calc prefix flag, @kbd{K} (keep-arguments), is discussed
12253elsewhere. @xref{Keep Arguments}.
12254
12255@node Calculation Modes, Simplification Modes, Inverse and Hyperbolic, Mode Settings
12256@section Calculation Modes
12257
12258@noindent
12259The commands in this section are two-key sequences beginning with
12260the @kbd{m} prefix. (That's the letter @kbd{m}, not the @key{META} key.)
12261The @samp{m a} (@code{calc-algebraic-mode}) command is described elsewhere
12262(@pxref{Algebraic Entry}).
12263
12264@menu
12265* Angular Modes::
12266* Polar Mode::
12267* Fraction Mode::
12268* Infinite Mode::
12269* Symbolic Mode::
12270* Matrix Mode::
12271* Automatic Recomputation::
12272* Working Message::
12273@end menu
12274
12275@node Angular Modes, Polar Mode, Calculation Modes, Calculation Modes
12276@subsection Angular Modes
12277
12278@noindent
12279@cindex Angular mode
12280The Calculator supports three notations for angles: radians, degrees,
12281and degrees-minutes-seconds. When a number is presented to a function
12282like @code{sin} that requires an angle, the current angular mode is
12283used to interpret the number as either radians or degrees. If an HMS
12284form is presented to @code{sin}, it is always interpreted as
12285degrees-minutes-seconds.
12286
12287Functions that compute angles produce a number in radians, a number in
12288degrees, or an HMS form depending on the current angular mode. If the
12289result is a complex number and the current mode is HMS, the number is
12290instead expressed in degrees. (Complex-number calculations would
12291normally be done in Radians mode, though. Complex numbers are converted
12292to degrees by calculating the complex result in radians and then
12293multiplying by 180 over @cpi{}.)
12294
12295@kindex m r
12296@pindex calc-radians-mode
12297@kindex m d
12298@pindex calc-degrees-mode
12299@kindex m h
12300@pindex calc-hms-mode
12301The @kbd{m r} (@code{calc-radians-mode}), @kbd{m d} (@code{calc-degrees-mode}),
12302and @kbd{m h} (@code{calc-hms-mode}) commands control the angular mode.
12303The current angular mode is displayed on the Emacs mode line.
12304The default angular mode is Degrees.
12305
12306@node Polar Mode, Fraction Mode, Angular Modes, Calculation Modes
12307@subsection Polar Mode
12308
12309@noindent
12310@cindex Polar mode
12311The Calculator normally ``prefers'' rectangular complex numbers in the
12312sense that rectangular form is used when the proper form can not be
12313decided from the input. This might happen by multiplying a rectangular
12314number by a polar one, by taking the square root of a negative real
12315number, or by entering @kbd{( 2 @key{SPC} 3 )}.
12316
12317@kindex m p
12318@pindex calc-polar-mode
12319The @kbd{m p} (@code{calc-polar-mode}) command toggles complex-number
12320preference between rectangular and polar forms. In Polar mode, all
12321of the above example situations would produce polar complex numbers.
12322
12323@node Fraction Mode, Infinite Mode, Polar Mode, Calculation Modes
12324@subsection Fraction Mode
12325
12326@noindent
12327@cindex Fraction mode
12328@cindex Division of integers
12329Division of two integers normally yields a floating-point number if the
12330result cannot be expressed as an integer. In some cases you would
12331rather get an exact fractional answer. One way to accomplish this is
12332to use the @kbd{:} (@code{calc-fdiv}) [@code{fdiv}] command, which
12333divides the two integers on the top of the stack to produce a fraction:
12334@kbd{6 @key{RET} 4 :} produces @expr{3:2} even though
12335@kbd{6 @key{RET} 4 /} produces @expr{1.5}.
12336
12337@kindex m f
12338@pindex calc-frac-mode
12339To set the Calculator to produce fractional results for normal integer
12340divisions, use the @kbd{m f} (@code{calc-frac-mode}) command.
12341For example, @expr{8/4} produces @expr{2} in either mode,
12342but @expr{6/4} produces @expr{3:2} in Fraction mode, @expr{1.5} in
12343Float mode.
12344
12345At any time you can use @kbd{c f} (@code{calc-float}) to convert a
12346fraction to a float, or @kbd{c F} (@code{calc-fraction}) to convert a
12347float to a fraction. @xref{Conversions}.
12348
12349@node Infinite Mode, Symbolic Mode, Fraction Mode, Calculation Modes
12350@subsection Infinite Mode
12351
12352@noindent
12353@cindex Infinite mode
12354The Calculator normally treats results like @expr{1 / 0} as errors;
12355formulas like this are left in unsimplified form. But Calc can be
12356put into a mode where such calculations instead produce ``infinite''
12357results.
12358
12359@kindex m i
12360@pindex calc-infinite-mode
12361The @kbd{m i} (@code{calc-infinite-mode}) command turns this mode
12362on and off. When the mode is off, infinities do not arise except
12363in calculations that already had infinities as inputs. (One exception
12364is that infinite open intervals like @samp{[0 .. inf)} can be
12365generated; however, intervals closed at infinity (@samp{[0 .. inf]})
12366will not be generated when Infinite mode is off.)
12367
12368With Infinite mode turned on, @samp{1 / 0} will generate @code{uinf},
12369an undirected infinity. @xref{Infinities}, for a discussion of the
12370difference between @code{inf} and @code{uinf}. Also, @expr{0 / 0}
12371evaluates to @code{nan}, the ``indeterminate'' symbol. Various other
12372functions can also return infinities in this mode; for example,
12373@samp{ln(0) = -inf}, and @samp{gamma(-7) = uinf}. Once again,
12374note that @samp{exp(inf) = inf} regardless of Infinite mode because
12375this calculation has infinity as an input.
12376
12377@cindex Positive Infinite mode
12378The @kbd{m i} command with a numeric prefix argument of zero,
12379i.e., @kbd{C-u 0 m i}, turns on a Positive Infinite mode in
12380which zero is treated as positive instead of being directionless.
12381Thus, @samp{1 / 0 = inf} and @samp{-1 / 0 = -inf} in this mode.
12382Note that zero never actually has a sign in Calc; there are no
12383separate representations for @mathit{+0} and @mathit{-0}. Positive
12384Infinite mode merely changes the interpretation given to the
12385single symbol, @samp{0}. One consequence of this is that, while
12386you might expect @samp{1 / -0 = -inf}, actually @samp{1 / -0}
12387is equivalent to @samp{1 / 0}, which is equal to positive @code{inf}.
12388
12389@node Symbolic Mode, Matrix Mode, Infinite Mode, Calculation Modes
12390@subsection Symbolic Mode
12391
12392@noindent
12393@cindex Symbolic mode
12394@cindex Inexact results
12395Calculations are normally performed numerically wherever possible.
12396For example, the @code{calc-sqrt} command, or @code{sqrt} function in an
12397algebraic expression, produces a numeric answer if the argument is a
12398number or a symbolic expression if the argument is an expression:
12399@kbd{2 Q} pushes 1.4142 but @kbd{@key{'} x+1 @key{RET} Q} pushes @samp{sqrt(x+1)}.
12400
12401@kindex m s
12402@pindex calc-symbolic-mode
12403In @dfn{Symbolic mode}, controlled by the @kbd{m s} (@code{calc-symbolic-mode})
12404command, functions which would produce inexact, irrational results are
12405left in symbolic form. Thus @kbd{16 Q} pushes 4, but @kbd{2 Q} pushes
12406@samp{sqrt(2)}.
12407
12408@kindex N
12409@pindex calc-eval-num
12410The shift-@kbd{N} (@code{calc-eval-num}) command evaluates numerically
12411the expression at the top of the stack, by temporarily disabling
12412@code{calc-symbolic-mode} and executing @kbd{=} (@code{calc-evaluate}).
12413Given a numeric prefix argument, it also
12414sets the floating-point precision to the specified value for the duration
12415of the command.
12416
12417To evaluate a formula numerically without expanding the variables it
12418contains, you can use the key sequence @kbd{m s a v m s} (this uses
12419@code{calc-alg-evaluate}, which resimplifies but doesn't evaluate
12420variables.)
12421
12422@node Matrix Mode, Automatic Recomputation, Symbolic Mode, Calculation Modes
12423@subsection Matrix and Scalar Modes
12424
12425@noindent
12426@cindex Matrix mode
12427@cindex Scalar mode
12428Calc sometimes makes assumptions during algebraic manipulation that
12429are awkward or incorrect when vectors and matrices are involved.
12430Calc has two modes, @dfn{Matrix mode} and @dfn{Scalar mode}, which
12431modify its behavior around vectors in useful ways.
12432
12433@kindex m v
12434@pindex calc-matrix-mode
12435Press @kbd{m v} (@code{calc-matrix-mode}) once to enter Matrix mode.
12436In this mode, all objects are assumed to be matrices unless provably
12437otherwise. One major effect is that Calc will no longer consider
12438multiplication to be commutative. (Recall that in matrix arithmetic,
12439@samp{A*B} is not the same as @samp{B*A}.) This assumption affects
12440rewrite rules and algebraic simplification. Another effect of this
12441mode is that calculations that would normally produce constants like
124420 and 1 (e.g., @expr{a - a} and @expr{a / a}, respectively) will now
12443produce function calls that represent ``generic'' zero or identity
12444matrices: @samp{idn(0)}, @samp{idn(1)}. The @code{idn} function
12445@samp{idn(@var{a},@var{n})} returns @var{a} times an @var{n}x@var{n}
12446identity matrix; if @var{n} is omitted, it doesn't know what
12447dimension to use and so the @code{idn} call remains in symbolic
12448form. However, if this generic identity matrix is later combined
12449with a matrix whose size is known, it will be converted into
12450a true identity matrix of the appropriate size. On the other hand,
12451if it is combined with a scalar (as in @samp{idn(1) + 2}), Calc
12452will assume it really was a scalar after all and produce, e.g., 3.
12453
12454Press @kbd{m v} a second time to get Scalar mode. Here, objects are
12455assumed @emph{not} to be vectors or matrices unless provably so.
12456For example, normally adding a variable to a vector, as in
12457@samp{[x, y, z] + a}, will leave the sum in symbolic form because
12458as far as Calc knows, @samp{a} could represent either a number or
12459another 3-vector. In Scalar mode, @samp{a} is assumed to be a
12460non-vector, and the addition is evaluated to @samp{[x+a, y+a, z+a]}.
12461
12462Press @kbd{m v} a third time to return to the normal mode of operation.
12463
12464If you press @kbd{m v} with a numeric prefix argument @var{n}, you
12465get a special ``dimensioned'' Matrix mode in which matrices of
12466unknown size are assumed to be @var{n}x@var{n} square matrices.
12467Then, the function call @samp{idn(1)} will expand into an actual
12468matrix rather than representing a ``generic'' matrix. Simply typing
12469@kbd{C-u m v} will get you a square Matrix mode, in which matrices of
12470unknown size are assumed to be square matrices of unspecified size.
12471
12472@cindex Declaring scalar variables
12473Of course these modes are approximations to the true state of
12474affairs, which is probably that some quantities will be matrices
12475and others will be scalars. One solution is to ``declare''
12476certain variables or functions to be scalar-valued.
12477@xref{Declarations}, to see how to make declarations in Calc.
12478
12479There is nothing stopping you from declaring a variable to be
12480scalar and then storing a matrix in it; however, if you do, the
12481results you get from Calc may not be valid. Suppose you let Calc
12482get the result @samp{[x+a, y+a, z+a]} shown above, and then stored
12483@samp{[1, 2, 3]} in @samp{a}. The result would not be the same as
12484for @samp{[x, y, z] + [1, 2, 3]}, but that's because you have broken
12485your earlier promise to Calc that @samp{a} would be scalar.
12486
12487Another way to mix scalars and matrices is to use selections
12488(@pxref{Selecting Subformulas}). Use Matrix mode when operating on
12489your formula normally; then, to apply Scalar mode to a certain part
12490of the formula without affecting the rest just select that part,
12491change into Scalar mode and press @kbd{=} to resimplify the part
12492under this mode, then change back to Matrix mode before deselecting.
12493
12494@node Automatic Recomputation, Working Message, Matrix Mode, Calculation Modes
12495@subsection Automatic Recomputation
12496
12497@noindent
12498The @dfn{evaluates-to} operator, @samp{=>}, has the special
12499property that any @samp{=>} formulas on the stack are recomputed
12500whenever variable values or mode settings that might affect them
12501are changed. @xref{Evaluates-To Operator}.
12502
12503@kindex m C
12504@pindex calc-auto-recompute
12505The @kbd{m C} (@code{calc-auto-recompute}) command turns this
12506automatic recomputation on and off. If you turn it off, Calc will
12507not update @samp{=>} operators on the stack (nor those in the
12508attached Embedded mode buffer, if there is one). They will not
12509be updated unless you explicitly do so by pressing @kbd{=} or until
12510you press @kbd{m C} to turn recomputation back on. (While automatic
12511recomputation is off, you can think of @kbd{m C m C} as a command
12512to update all @samp{=>} operators while leaving recomputation off.)
12513
12514To update @samp{=>} operators in an Embedded buffer while
12515automatic recomputation is off, use @w{@kbd{C-x * u}}.
12516@xref{Embedded Mode}.
12517
12518@node Working Message, , Automatic Recomputation, Calculation Modes
12519@subsection Working Messages
12520
12521@noindent
12522@cindex Performance
12523@cindex Working messages
12524Since the Calculator is written entirely in Emacs Lisp, which is not
12525designed for heavy numerical work, many operations are quite slow.
12526The Calculator normally displays the message @samp{Working...} in the
12527echo area during any command that may be slow. In addition, iterative
12528operations such as square roots and trigonometric functions display the
12529intermediate result at each step. Both of these types of messages can
12530be disabled if you find them distracting.
12531
12532@kindex m w
12533@pindex calc-working
12534Type @kbd{m w} (@code{calc-working}) with a numeric prefix of 0 to
12535disable all ``working'' messages. Use a numeric prefix of 1 to enable
12536only the plain @samp{Working...} message. Use a numeric prefix of 2 to
12537see intermediate results as well. With no numeric prefix this displays
12538the current mode.
12539
12540While it may seem that the ``working'' messages will slow Calc down
12541considerably, experiments have shown that their impact is actually
12542quite small. But if your terminal is slow you may find that it helps
12543to turn the messages off.
12544
12545@node Simplification Modes, Declarations, Calculation Modes, Mode Settings
12546@section Simplification Modes
12547
12548@noindent
12549The current @dfn{simplification mode} controls how numbers and formulas
12550are ``normalized'' when being taken from or pushed onto the stack.
12551Some normalizations are unavoidable, such as rounding floating-point
12552results to the current precision, and reducing fractions to simplest
12553form. Others, such as simplifying a formula like @expr{a+a} (or @expr{2+3}),
12554are done by default but can be turned off when necessary.
12555
12556When you press a key like @kbd{+} when @expr{2} and @expr{3} are on the
12557stack, Calc pops these numbers, normalizes them, creates the formula
12558@expr{2+3}, normalizes it, and pushes the result. Of course the standard
12559rules for normalizing @expr{2+3} will produce the result @expr{5}.
12560
12561Simplification mode commands consist of the lower-case @kbd{m} prefix key
12562followed by a shifted letter.
12563
12564@kindex m O
12565@pindex calc-no-simplify-mode
12566The @kbd{m O} (@code{calc-no-simplify-mode}) command turns off all optional
12567simplifications. These would leave a formula like @expr{2+3} alone. In
12568fact, nothing except simple numbers are ever affected by normalization
12569in this mode.
12570
12571@kindex m N
12572@pindex calc-num-simplify-mode
12573The @kbd{m N} (@code{calc-num-simplify-mode}) command turns off simplification
12574of any formulas except those for which all arguments are constants. For
12575example, @expr{1+2} is simplified to @expr{3}, and @expr{a+(2-2)} is
12576simplified to @expr{a+0} but no further, since one argument of the sum
12577is not a constant. Unfortunately, @expr{(a+2)-2} is @emph{not} simplified
12578because the top-level @samp{-} operator's arguments are not both
12579constant numbers (one of them is the formula @expr{a+2}).
12580A constant is a number or other numeric object (such as a constant
12581error form or modulo form), or a vector all of whose
12582elements are constant.
12583
12584@kindex m D
12585@pindex calc-default-simplify-mode
12586The @kbd{m D} (@code{calc-default-simplify-mode}) command restores the
12587default simplifications for all formulas. This includes many easy and
12588fast algebraic simplifications such as @expr{a+0} to @expr{a}, and
12589@expr{a + 2 a} to @expr{3 a}, as well as evaluating functions like
12590@expr{@tfn{deriv}(x^2, x)} to @expr{2 x}.
12591
12592@kindex m B
12593@pindex calc-bin-simplify-mode
12594The @kbd{m B} (@code{calc-bin-simplify-mode}) mode applies the default
12595simplifications to a result and then, if the result is an integer,
12596uses the @kbd{b c} (@code{calc-clip}) command to clip the integer according
12597to the current binary word size. @xref{Binary Functions}. Real numbers
12598are rounded to the nearest integer and then clipped; other kinds of
12599results (after the default simplifications) are left alone.
12600
12601@kindex m A
12602@pindex calc-alg-simplify-mode
12603The @kbd{m A} (@code{calc-alg-simplify-mode}) mode does algebraic
12604simplification; it applies all the default simplifications, and also
12605the more powerful (and slower) simplifications made by @kbd{a s}
12606(@code{calc-simplify}). @xref{Algebraic Simplifications}.
12607
12608@kindex m E
12609@pindex calc-ext-simplify-mode
12610The @kbd{m E} (@code{calc-ext-simplify-mode}) mode does ``extended''
12611algebraic simplification, as by the @kbd{a e} (@code{calc-simplify-extended})
12612command. @xref{Unsafe Simplifications}.
12613
12614@kindex m U
12615@pindex calc-units-simplify-mode
12616The @kbd{m U} (@code{calc-units-simplify-mode}) mode does units
12617simplification; it applies the command @kbd{u s}
12618(@code{calc-simplify-units}), which in turn
12619is a superset of @kbd{a s}. In this mode, variable names which
12620are identifiable as unit names (like @samp{mm} for ``millimeters'')
12621are simplified with their unit definitions in mind.
12622
12623A common technique is to set the simplification mode down to the lowest
12624amount of simplification you will allow to be applied automatically, then
12625use manual commands like @kbd{a s} and @kbd{c c} (@code{calc-clean}) to
12626perform higher types of simplifications on demand. @xref{Algebraic
12627Definitions}, for another sample use of No-Simplification mode.
12628
12629@node Declarations, Display Modes, Simplification Modes, Mode Settings
12630@section Declarations
12631
12632@noindent
12633A @dfn{declaration} is a statement you make that promises you will
12634use a certain variable or function in a restricted way. This may
12635give Calc the freedom to do things that it couldn't do if it had to
12636take the fully general situation into account.
12637
12638@menu
12639* Declaration Basics::
12640* Kinds of Declarations::
12641* Functions for Declarations::
12642@end menu
12643
12644@node Declaration Basics, Kinds of Declarations, Declarations, Declarations
12645@subsection Declaration Basics
12646
12647@noindent
12648@kindex s d
12649@pindex calc-declare-variable
12650The @kbd{s d} (@code{calc-declare-variable}) command is the easiest
12651way to make a declaration for a variable. This command prompts for
12652the variable name, then prompts for the declaration. The default
12653at the declaration prompt is the previous declaration, if any.
12654You can edit this declaration, or press @kbd{C-k} to erase it and
12655type a new declaration. (Or, erase it and press @key{RET} to clear
12656the declaration, effectively ``undeclaring'' the variable.)
12657
12658A declaration is in general a vector of @dfn{type symbols} and
12659@dfn{range} values. If there is only one type symbol or range value,
12660you can write it directly rather than enclosing it in a vector.
12661For example, @kbd{s d foo @key{RET} real @key{RET}} declares @code{foo} to
12662be a real number, and @kbd{s d bar @key{RET} [int, const, [1..6]] @key{RET}}
12663declares @code{bar} to be a constant integer between 1 and 6.
12664(Actually, you can omit the outermost brackets and Calc will
12665provide them for you: @kbd{s d bar @key{RET} int, const, [1..6] @key{RET}}.)
12666
12667@cindex @code{Decls} variable
12668@vindex Decls
12669Declarations in Calc are kept in a special variable called @code{Decls}.
12670This variable encodes the set of all outstanding declarations in
12671the form of a matrix. Each row has two elements: A variable or
12672vector of variables declared by that row, and the declaration
12673specifier as described above. You can use the @kbd{s D} command to
12674edit this variable if you wish to see all the declarations at once.
12675@xref{Operations on Variables}, for a description of this command
12676and the @kbd{s p} command that allows you to save your declarations
12677permanently if you wish.
12678
12679Items being declared can also be function calls. The arguments in
12680the call are ignored; the effect is to say that this function returns
12681values of the declared type for any valid arguments. The @kbd{s d}
12682command declares only variables, so if you wish to make a function
12683declaration you will have to edit the @code{Decls} matrix yourself.
12684
12685For example, the declaration matrix
12686
12687@smallexample
12688@group
12689[ [ foo, real ]
12690 [ [j, k, n], int ]
12691 [ f(1,2,3), [0 .. inf) ] ]
12692@end group
12693@end smallexample
12694
12695@noindent
12696declares that @code{foo} represents a real number, @code{j}, @code{k}
12697and @code{n} represent integers, and the function @code{f} always
12698returns a real number in the interval shown.
12699
12700@vindex All
12701If there is a declaration for the variable @code{All}, then that
12702declaration applies to all variables that are not otherwise declared.
12703It does not apply to function names. For example, using the row
12704@samp{[All, real]} says that all your variables are real unless they
12705are explicitly declared without @code{real} in some other row.
12706The @kbd{s d} command declares @code{All} if you give a blank
12707response to the variable-name prompt.
12708
12709@node Kinds of Declarations, Functions for Declarations, Declaration Basics, Declarations
12710@subsection Kinds of Declarations
12711
12712@noindent
12713The type-specifier part of a declaration (that is, the second prompt
12714in the @kbd{s d} command) can be a type symbol, an interval, or a
12715vector consisting of zero or more type symbols followed by zero or
12716more intervals or numbers that represent the set of possible values
12717for the variable.
12718
12719@smallexample
12720@group
12721[ [ a, [1, 2, 3, 4, 5] ]
12722 [ b, [1 .. 5] ]
12723 [ c, [int, 1 .. 5] ] ]
12724@end group
12725@end smallexample
12726
12727Here @code{a} is declared to contain one of the five integers shown;
12728@code{b} is any number in the interval from 1 to 5 (any real number
12729since we haven't specified), and @code{c} is any integer in that
12730interval. Thus the declarations for @code{a} and @code{c} are
12731nearly equivalent (see below).
12732
12733The type-specifier can be the empty vector @samp{[]} to say that
12734nothing is known about a given variable's value. This is the same
12735as not declaring the variable at all except that it overrides any
12736@code{All} declaration which would otherwise apply.
12737
12738The initial value of @code{Decls} is the empty vector @samp{[]}.
12739If @code{Decls} has no stored value or if the value stored in it
12740is not valid, it is ignored and there are no declarations as far
12741as Calc is concerned. (The @kbd{s d} command will replace such a
12742malformed value with a fresh empty matrix, @samp{[]}, before recording
12743the new declaration.) Unrecognized type symbols are ignored.
12744
12745The following type symbols describe what sorts of numbers will be
12746stored in a variable:
12747
12748@table @code
12749@item int
12750Integers.
12751@item numint
12752Numerical integers. (Integers or integer-valued floats.)
12753@item frac
12754Fractions. (Rational numbers which are not integers.)
12755@item rat
12756Rational numbers. (Either integers or fractions.)
12757@item float
12758Floating-point numbers.
12759@item real
12760Real numbers. (Integers, fractions, or floats. Actually,
12761intervals and error forms with real components also count as
12762reals here.)
12763@item pos
12764Positive real numbers. (Strictly greater than zero.)
12765@item nonneg
12766Nonnegative real numbers. (Greater than or equal to zero.)
12767@item number
12768Numbers. (Real or complex.)
12769@end table
12770
12771Calc uses this information to determine when certain simplifications
12772of formulas are safe. For example, @samp{(x^y)^z} cannot be
12773simplified to @samp{x^(y z)} in general; for example,
12774@samp{((-3)^2)^1:2} is 3, but @samp{(-3)^(2*1:2) = (-3)^1} is @mathit{-3}.
12775However, this simplification @emph{is} safe if @code{z} is known
12776to be an integer, or if @code{x} is known to be a nonnegative
12777real number. If you have given declarations that allow Calc to
12778deduce either of these facts, Calc will perform this simplification
12779of the formula.
12780
12781Calc can apply a certain amount of logic when using declarations.
12782For example, @samp{(x^y)^(2n+1)} will be simplified if @code{n}
12783has been declared @code{int}; Calc knows that an integer times an
12784integer, plus an integer, must always be an integer. (In fact,
12785Calc would simplify @samp{(-x)^(2n+1)} to @samp{-(x^(2n+1))} since
12786it is able to determine that @samp{2n+1} must be an odd integer.)
12787
12788Similarly, @samp{(abs(x)^y)^z} will be simplified to @samp{abs(x)^(y z)}
12789because Calc knows that the @code{abs} function always returns a
12790nonnegative real. If you had a @code{myabs} function that also had
12791this property, you could get Calc to recognize it by adding the row
12792@samp{[myabs(), nonneg]} to the @code{Decls} matrix.
12793
12794One instance of this simplification is @samp{sqrt(x^2)} (since the
12795@code{sqrt} function is effectively a one-half power). Normally
12796Calc leaves this formula alone. After the command
12797@kbd{s d x @key{RET} real @key{RET}}, however, it can simplify the formula to
12798@samp{abs(x)}. And after @kbd{s d x @key{RET} nonneg @key{RET}}, Calc can
12799simplify this formula all the way to @samp{x}.
12800
12801If there are any intervals or real numbers in the type specifier,
12802they comprise the set of possible values that the variable or
12803function being declared can have. In particular, the type symbol
12804@code{real} is effectively the same as the range @samp{[-inf .. inf]}
12805(note that infinity is included in the range of possible values);
12806@code{pos} is the same as @samp{(0 .. inf]}, and @code{nonneg} is
12807the same as @samp{[0 .. inf]}. Saying @samp{[real, [-5 .. 5]]} is
12808redundant because the fact that the variable is real can be
12809deduced just from the interval, but @samp{[int, [-5 .. 5]]} and
12810@samp{[rat, [-5 .. 5]]} are useful combinations.
12811
12812Note that the vector of intervals or numbers is in the same format
12813used by Calc's set-manipulation commands. @xref{Set Operations}.
12814
12815The type specifier @samp{[1, 2, 3]} is equivalent to
12816@samp{[numint, 1, 2, 3]}, @emph{not} to @samp{[int, 1, 2, 3]}.
12817In other words, the range of possible values means only that
12818the variable's value must be numerically equal to a number in
12819that range, but not that it must be equal in type as well.
12820Calc's set operations act the same way; @samp{in(2, [1., 2., 3.])}
12821and @samp{in(1.5, [1:2, 3:2, 5:2])} both report ``true.''
12822
12823If you use a conflicting combination of type specifiers, the
12824results are unpredictable. An example is @samp{[pos, [0 .. 5]]},
12825where the interval does not lie in the range described by the
12826type symbol.
12827
12828``Real'' declarations mostly affect simplifications involving powers
12829like the one described above. Another case where they are used
12830is in the @kbd{a P} command which returns a list of all roots of a
12831polynomial; if the variable has been declared real, only the real
12832roots (if any) will be included in the list.
12833
12834``Integer'' declarations are used for simplifications which are valid
12835only when certain values are integers (such as @samp{(x^y)^z}
12836shown above).
12837
12838Another command that makes use of declarations is @kbd{a s}, when
12839simplifying equations and inequalities. It will cancel @code{x}
12840from both sides of @samp{a x = b x} only if it is sure @code{x}
12841is non-zero, say, because it has a @code{pos} declaration.
12842To declare specifically that @code{x} is real and non-zero,
12843use @samp{[[-inf .. 0), (0 .. inf]]}. (There is no way in the
12844current notation to say that @code{x} is nonzero but not necessarily
12845real.) The @kbd{a e} command does ``unsafe'' simplifications,
12846including cancelling @samp{x} from the equation when @samp{x} is
12847not known to be nonzero.
12848
12849Another set of type symbols distinguish between scalars and vectors.
12850
12851@table @code
12852@item scalar
12853The value is not a vector.
12854@item vector
12855The value is a vector.
12856@item matrix
12857The value is a matrix (a rectangular vector of vectors).
12858@item sqmatrix
12859The value is a square matrix.
12860@end table
12861
12862These type symbols can be combined with the other type symbols
12863described above; @samp{[int, matrix]} describes an object which
12864is a matrix of integers.
12865
12866Scalar/vector declarations are used to determine whether certain
12867algebraic operations are safe. For example, @samp{[a, b, c] + x}
12868is normally not simplified to @samp{[a + x, b + x, c + x]}, but
12869it will be if @code{x} has been declared @code{scalar}. On the
12870other hand, multiplication is usually assumed to be commutative,
12871but the terms in @samp{x y} will never be exchanged if both @code{x}
12872and @code{y} are known to be vectors or matrices. (Calc currently
12873never distinguishes between @code{vector} and @code{matrix}
12874declarations.)
12875
12876@xref{Matrix Mode}, for a discussion of Matrix mode and
12877Scalar mode, which are similar to declaring @samp{[All, matrix]}
12878or @samp{[All, scalar]} but much more convenient.
12879
12880One more type symbol that is recognized is used with the @kbd{H a d}
12881command for taking total derivatives of a formula. @xref{Calculus}.
12882
12883@table @code
12884@item const
12885The value is a constant with respect to other variables.
12886@end table
12887
12888Calc does not check the declarations for a variable when you store
12889a value in it. However, storing @mathit{-3.5} in a variable that has
12890been declared @code{pos}, @code{int}, or @code{matrix} may have
12891unexpected effects; Calc may evaluate @samp{sqrt(x^2)} to @expr{3.5}
12892if it substitutes the value first, or to @expr{-3.5} if @code{x}
12893was declared @code{pos} and the formula @samp{sqrt(x^2)} is
12894simplified to @samp{x} before the value is substituted. Before
12895using a variable for a new purpose, it is best to use @kbd{s d}
12896or @kbd{s D} to check to make sure you don't still have an old
12897declaration for the variable that will conflict with its new meaning.
12898
12899@node Functions for Declarations, , Kinds of Declarations, Declarations
12900@subsection Functions for Declarations
12901
12902@noindent
12903Calc has a set of functions for accessing the current declarations
12904in a convenient manner. These functions return 1 if the argument
12905can be shown to have the specified property, or 0 if the argument
12906can be shown @emph{not} to have that property; otherwise they are
12907left unevaluated. These functions are suitable for use with rewrite
12908rules (@pxref{Conditional Rewrite Rules}) or programming constructs
12909(@pxref{Conditionals in Macros}). They can be entered only using
12910algebraic notation. @xref{Logical Operations}, for functions
12911that perform other tests not related to declarations.
12912
12913For example, @samp{dint(17)} returns 1 because 17 is an integer, as
12914do @samp{dint(n)} and @samp{dint(2 n - 3)} if @code{n} has been declared
12915@code{int}, but @samp{dint(2.5)} and @samp{dint(n + 0.5)} return 0.
12916Calc consults knowledge of its own built-in functions as well as your
12917own declarations: @samp{dint(floor(x))} returns 1.
12918
12919@ignore
12920@starindex
12921@end ignore
12922@tindex dint
12923@ignore
12924@starindex
12925@end ignore
12926@tindex dnumint
12927@ignore
12928@starindex
12929@end ignore
12930@tindex dnatnum
12931The @code{dint} function checks if its argument is an integer.
12932The @code{dnatnum} function checks if its argument is a natural
12933number, i.e., a nonnegative integer. The @code{dnumint} function
12934checks if its argument is numerically an integer, i.e., either an
12935integer or an integer-valued float. Note that these and the other
12936data type functions also accept vectors or matrices composed of
12937suitable elements, and that real infinities @samp{inf} and @samp{-inf}
12938are considered to be integers for the purposes of these functions.
12939
12940@ignore
12941@starindex
12942@end ignore
12943@tindex drat
12944The @code{drat} function checks if its argument is rational, i.e.,
12945an integer or fraction. Infinities count as rational, but intervals
12946and error forms do not.
12947
12948@ignore
12949@starindex
12950@end ignore
12951@tindex dreal
12952The @code{dreal} function checks if its argument is real. This
12953includes integers, fractions, floats, real error forms, and intervals.
12954
12955@ignore
12956@starindex
12957@end ignore
12958@tindex dimag
12959The @code{dimag} function checks if its argument is imaginary,
12960i.e., is mathematically equal to a real number times @expr{i}.
12961
12962@ignore
12963@starindex
12964@end ignore
12965@tindex dpos
12966@ignore
12967@starindex
12968@end ignore
12969@tindex dneg
12970@ignore
12971@starindex
12972@end ignore
12973@tindex dnonneg
12974The @code{dpos} function checks for positive (but nonzero) reals.
12975The @code{dneg} function checks for negative reals. The @code{dnonneg}
12976function checks for nonnegative reals, i.e., reals greater than or
12977equal to zero. Note that the @kbd{a s} command can simplify an
12978expression like @expr{x > 0} to 1 or 0 using @code{dpos}, and that
12979@kbd{a s} is effectively applied to all conditions in rewrite rules,
12980so the actual functions @code{dpos}, @code{dneg}, and @code{dnonneg}
12981are rarely necessary.
12982
12983@ignore
12984@starindex
12985@end ignore
12986@tindex dnonzero
12987The @code{dnonzero} function checks that its argument is nonzero.
12988This includes all nonzero real or complex numbers, all intervals that
12989do not include zero, all nonzero modulo forms, vectors all of whose
12990elements are nonzero, and variables or formulas whose values can be
12991deduced to be nonzero. It does not include error forms, since they
12992represent values which could be anything including zero. (This is
12993also the set of objects considered ``true'' in conditional contexts.)
12994
12995@ignore
12996@starindex
12997@end ignore
12998@tindex deven
12999@ignore
13000@starindex
13001@end ignore
13002@tindex dodd
13003The @code{deven} function returns 1 if its argument is known to be
13004an even integer (or integer-valued float); it returns 0 if its argument
13005is known not to be even (because it is known to be odd or a non-integer).
13006The @kbd{a s} command uses this to simplify a test of the form
13007@samp{x % 2 = 0}. There is also an analogous @code{dodd} function.
13008
13009@ignore
13010@starindex
13011@end ignore
13012@tindex drange
13013The @code{drange} function returns a set (an interval or a vector
13014of intervals and/or numbers; @pxref{Set Operations}) that describes
13015the set of possible values of its argument. If the argument is
13016a variable or a function with a declaration, the range is copied
13017from the declaration. Otherwise, the possible signs of the
13018expression are determined using a method similar to @code{dpos},
13019etc., and a suitable set like @samp{[0 .. inf]} is returned. If
13020the expression is not provably real, the @code{drange} function
13021remains unevaluated.
13022
13023@ignore
13024@starindex
13025@end ignore
13026@tindex dscalar
13027The @code{dscalar} function returns 1 if its argument is provably
13028scalar, or 0 if its argument is provably non-scalar. It is left
13029unevaluated if this cannot be determined. (If Matrix mode or Scalar
13030mode is in effect, this function returns 1 or 0, respectively,
13031if it has no other information.) When Calc interprets a condition
13032(say, in a rewrite rule) it considers an unevaluated formula to be
13033``false.'' Thus, @samp{dscalar(a)} is ``true'' only if @code{a} is
13034provably scalar, and @samp{!dscalar(a)} is ``true'' only if @code{a}
13035is provably non-scalar; both are ``false'' if there is insufficient
13036information to tell.
13037
13038@node Display Modes, Language Modes, Declarations, Mode Settings
13039@section Display Modes
13040
13041@noindent
13042The commands in this section are two-key sequences beginning with the
13043@kbd{d} prefix. The @kbd{d l} (@code{calc-line-numbering}) and @kbd{d b}
13044(@code{calc-line-breaking}) commands are described elsewhere;
13045@pxref{Stack Basics} and @pxref{Normal Language Modes}, respectively.
13046Display formats for vectors and matrices are also covered elsewhere;
13047@pxref{Vector and Matrix Formats}.
13048
13049One thing all display modes have in common is their treatment of the
13050@kbd{H} prefix. This prefix causes any mode command that would normally
13051refresh the stack to leave the stack display alone. The word ``Dirty''
13052will appear in the mode line when Calc thinks the stack display may not
13053reflect the latest mode settings.
13054
13055@kindex d @key{RET}
13056@pindex calc-refresh-top
13057The @kbd{d @key{RET}} (@code{calc-refresh-top}) command reformats the
13058top stack entry according to all the current modes. Positive prefix
13059arguments reformat the top @var{n} entries; negative prefix arguments
13060reformat the specified entry, and a prefix of zero is equivalent to
13061@kbd{d @key{SPC}} (@code{calc-refresh}), which reformats the entire stack.
13062For example, @kbd{H d s M-2 d @key{RET}} changes to scientific notation
13063but reformats only the top two stack entries in the new mode.
13064
13065The @kbd{I} prefix has another effect on the display modes. The mode
13066is set only temporarily; the top stack entry is reformatted according
13067to that mode, then the original mode setting is restored. In other
13068words, @kbd{I d s} is equivalent to @kbd{H d s d @key{RET} H d (@var{old mode})}.
13069
13070@menu
13071* Radix Modes::
13072* Grouping Digits::
13073* Float Formats::
13074* Complex Formats::
13075* Fraction Formats::
13076* HMS Formats::
13077* Date Formats::
13078* Truncating the Stack::
13079* Justification::
13080* Labels::
13081@end menu
13082
13083@node Radix Modes, Grouping Digits, Display Modes, Display Modes
13084@subsection Radix Modes
13085
13086@noindent
13087@cindex Radix display
13088@cindex Non-decimal numbers
13089@cindex Decimal and non-decimal numbers
13090Calc normally displays numbers in decimal (@dfn{base-10} or @dfn{radix-10})
13091notation. Calc can actually display in any radix from two (binary) to 36.
13092When the radix is above 10, the letters @code{A} to @code{Z} are used as
13093digits. When entering such a number, letter keys are interpreted as
13094potential digits rather than terminating numeric entry mode.
13095
13096@kindex d 2
13097@kindex d 8
13098@kindex d 6
13099@kindex d 0
13100@cindex Hexadecimal integers
13101@cindex Octal integers
13102The key sequences @kbd{d 2}, @kbd{d 8}, @kbd{d 6}, and @kbd{d 0} select
13103binary, octal, hexadecimal, and decimal as the current display radix,
13104respectively. Numbers can always be entered in any radix, though the
13105current radix is used as a default if you press @kbd{#} without any initial
13106digits. A number entered without a @kbd{#} is @emph{always} interpreted
13107as decimal.
13108
13109@kindex d r
13110@pindex calc-radix
13111To set the radix generally, use @kbd{d r} (@code{calc-radix}) and enter
13112an integer from 2 to 36. You can specify the radix as a numeric prefix
13113argument; otherwise you will be prompted for it.
13114
13115@kindex d z
13116@pindex calc-leading-zeros
13117@cindex Leading zeros
13118Integers normally are displayed with however many digits are necessary to
13119represent the integer and no more. The @kbd{d z} (@code{calc-leading-zeros})
13120command causes integers to be padded out with leading zeros according to the
13121current binary word size. (@xref{Binary Functions}, for a discussion of
13122word size.) If the absolute value of the word size is @expr{w}, all integers
13123are displayed with at least enough digits to represent
13124@texline @math{2^w-1}
13125@infoline @expr{(2^w)-1}
13126in the current radix. (Larger integers will still be displayed in their
13127entirety.)
13128
13129@node Grouping Digits, Float Formats, Radix Modes, Display Modes
13130@subsection Grouping Digits
13131
13132@noindent
13133@kindex d g
13134@pindex calc-group-digits
13135@cindex Grouping digits
13136@cindex Digit grouping
13137Long numbers can be hard to read if they have too many digits. For
13138example, the factorial of 30 is 33 digits long! Press @kbd{d g}
13139(@code{calc-group-digits}) to enable @dfn{Grouping} mode, in which digits
13140are displayed in clumps of 3 or 4 (depending on the current radix)
13141separated by commas.
13142
13143The @kbd{d g} command toggles grouping on and off.
13144With a numeric prefix of 0, this command displays the current state of
13145the grouping flag; with an argument of minus one it disables grouping;
13146with a positive argument @expr{N} it enables grouping on every @expr{N}
13147digits. For floating-point numbers, grouping normally occurs only
13148before the decimal point. A negative prefix argument @expr{-N} enables
13149grouping every @expr{N} digits both before and after the decimal point.
13150
13151@kindex d ,
13152@pindex calc-group-char
13153The @kbd{d ,} (@code{calc-group-char}) command allows you to choose any
13154character as the grouping separator. The default is the comma character.
13155If you find it difficult to read vectors of large integers grouped with
13156commas, you may wish to use spaces or some other character instead.
13157This command takes the next character you type, whatever it is, and
13158uses it as the digit separator. As a special case, @kbd{d , \} selects
13159@samp{\,} (@TeX{}'s thin-space symbol) as the digit separator.
13160
13161Please note that grouped numbers will not generally be parsed correctly
13162if re-read in textual form, say by the use of @kbd{C-x * y} and @kbd{C-x * g}.
13163(@xref{Kill and Yank}, for details on these commands.) One exception is
13164the @samp{\,} separator, which doesn't interfere with parsing because it
13165is ignored by @TeX{} language mode.
13166
13167@node Float Formats, Complex Formats, Grouping Digits, Display Modes
13168@subsection Float Formats
13169
13170@noindent
13171Floating-point quantities are normally displayed in standard decimal
13172form, with scientific notation used if the exponent is especially high
13173or low. All significant digits are normally displayed. The commands
13174in this section allow you to choose among several alternative display
13175formats for floats.
13176
13177@kindex d n
13178@pindex calc-normal-notation
13179The @kbd{d n} (@code{calc-normal-notation}) command selects the normal
13180display format. All significant figures in a number are displayed.
13181With a positive numeric prefix, numbers are rounded if necessary to
13182that number of significant digits. With a negative numerix prefix,
13183the specified number of significant digits less than the current
13184precision is used. (Thus @kbd{C-u -2 d n} displays 10 digits if the
13185current precision is 12.)
13186
13187@kindex d f
13188@pindex calc-fix-notation
13189The @kbd{d f} (@code{calc-fix-notation}) command selects fixed-point
13190notation. The numeric argument is the number of digits after the
13191decimal point, zero or more. This format will relax into scientific
13192notation if a nonzero number would otherwise have been rounded all the
13193way to zero. Specifying a negative number of digits is the same as
13194for a positive number, except that small nonzero numbers will be rounded
13195to zero rather than switching to scientific notation.
13196
13197@kindex d s
13198@pindex calc-sci-notation
13199@cindex Scientific notation, display of
13200The @kbd{d s} (@code{calc-sci-notation}) command selects scientific
13201notation. A positive argument sets the number of significant figures
13202displayed, of which one will be before and the rest after the decimal
13203point. A negative argument works the same as for @kbd{d n} format.
13204The default is to display all significant digits.
13205
13206@kindex d e
13207@pindex calc-eng-notation
13208@cindex Engineering notation, display of
13209The @kbd{d e} (@code{calc-eng-notation}) command selects engineering
13210notation. This is similar to scientific notation except that the
13211exponent is rounded down to a multiple of three, with from one to three
13212digits before the decimal point. An optional numeric prefix sets the
13213number of significant digits to display, as for @kbd{d s}.
13214
13215It is important to distinguish between the current @emph{precision} and
13216the current @emph{display format}. After the commands @kbd{C-u 10 p}
13217and @kbd{C-u 6 d n} the Calculator computes all results to ten
13218significant figures but displays only six. (In fact, intermediate
13219calculations are often carried to one or two more significant figures,
13220but values placed on the stack will be rounded down to ten figures.)
13221Numbers are never actually rounded to the display precision for storage,
13222except by commands like @kbd{C-k} and @kbd{C-x * y} which operate on the
13223actual displayed text in the Calculator buffer.
13224
13225@kindex d .
13226@pindex calc-point-char
13227The @kbd{d .} (@code{calc-point-char}) command selects the character used
13228as a decimal point. Normally this is a period; users in some countries
13229may wish to change this to a comma. Note that this is only a display
13230style; on entry, periods must always be used to denote floating-point
13231numbers, and commas to separate elements in a list.
13232
13233@node Complex Formats, Fraction Formats, Float Formats, Display Modes
13234@subsection Complex Formats
13235
13236@noindent
13237@kindex d c
13238@pindex calc-complex-notation
13239There are three supported notations for complex numbers in rectangular
13240form. The default is as a pair of real numbers enclosed in parentheses
13241and separated by a comma: @samp{(a,b)}. The @kbd{d c}
13242(@code{calc-complex-notation}) command selects this style.
13243
13244@kindex d i
13245@pindex calc-i-notation
13246@kindex d j
13247@pindex calc-j-notation
13248The other notations are @kbd{d i} (@code{calc-i-notation}), in which
13249numbers are displayed in @samp{a+bi} form, and @kbd{d j}
13250(@code{calc-j-notation}) which displays the form @samp{a+bj} preferred
13251in some disciplines.
13252
13253@cindex @code{i} variable
13254@vindex i
13255Complex numbers are normally entered in @samp{(a,b)} format.
13256If you enter @samp{2+3i} as an algebraic formula, it will be stored as
13257the formula @samp{2 + 3 * i}. However, if you use @kbd{=} to evaluate
13258this formula and you have not changed the variable @samp{i}, the @samp{i}
13259will be interpreted as @samp{(0,1)} and the formula will be simplified
13260to @samp{(2,3)}. Other commands (like @code{calc-sin}) will @emph{not}
13261interpret the formula @samp{2 + 3 * i} as a complex number.
13262@xref{Variables}, under ``special constants.''
13263
13264@node Fraction Formats, HMS Formats, Complex Formats, Display Modes
13265@subsection Fraction Formats
13266
13267@noindent
13268@kindex d o
13269@pindex calc-over-notation
13270Display of fractional numbers is controlled by the @kbd{d o}
13271(@code{calc-over-notation}) command. By default, a number like
13272eight thirds is displayed in the form @samp{8:3}. The @kbd{d o} command
13273prompts for a one- or two-character format. If you give one character,
13274that character is used as the fraction separator. Common separators are
13275@samp{:} and @samp{/}. (During input of numbers, the @kbd{:} key must be
13276used regardless of the display format; in particular, the @kbd{/} is used
13277for RPN-style division, @emph{not} for entering fractions.)
13278
13279If you give two characters, fractions use ``integer-plus-fractional-part''
13280notation. For example, the format @samp{+/} would display eight thirds
13281as @samp{2+2/3}. If two colons are present in a number being entered,
13282the number is interpreted in this form (so that the entries @kbd{2:2:3}
13283and @kbd{8:3} are equivalent).
13284
13285It is also possible to follow the one- or two-character format with
13286a number. For example: @samp{:10} or @samp{+/3}. In this case,
13287Calc adjusts all fractions that are displayed to have the specified
13288denominator, if possible. Otherwise it adjusts the denominator to
13289be a multiple of the specified value. For example, in @samp{:6} mode
13290the fraction @expr{1:6} will be unaffected, but @expr{2:3} will be
13291displayed as @expr{4:6}, @expr{1:2} will be displayed as @expr{3:6},
13292and @expr{1:8} will be displayed as @expr{3:24}. Integers are also
13293affected by this mode: 3 is displayed as @expr{18:6}. Note that the
13294format @samp{:1} writes fractions the same as @samp{:}, but it writes
13295integers as @expr{n:1}.
13296
13297The fraction format does not affect the way fractions or integers are
13298stored, only the way they appear on the screen. The fraction format
13299never affects floats.
13300
13301@node HMS Formats, Date Formats, Fraction Formats, Display Modes
13302@subsection HMS Formats
13303
13304@noindent
13305@kindex d h
13306@pindex calc-hms-notation
13307The @kbd{d h} (@code{calc-hms-notation}) command controls the display of
13308HMS (hours-minutes-seconds) forms. It prompts for a string which
13309consists basically of an ``hours'' marker, optional punctuation, a
13310``minutes'' marker, more optional punctuation, and a ``seconds'' marker.
13311Punctuation is zero or more spaces, commas, or semicolons. The hours
13312marker is one or more non-punctuation characters. The minutes and
13313seconds markers must be single non-punctuation characters.
13314
13315The default HMS format is @samp{@@ ' "}, producing HMS values of the form
13316@samp{23@@ 30' 15.75"}. The format @samp{deg, ms} would display this same
13317value as @samp{23deg, 30m15.75s}. During numeric entry, the @kbd{h} or @kbd{o}
13318keys are recognized as synonyms for @kbd{@@} regardless of display format.
13319The @kbd{m} and @kbd{s} keys are recognized as synonyms for @kbd{'} and
13320@kbd{"}, respectively, but only if an @kbd{@@} (or @kbd{h} or @kbd{o}) has
13321already been typed; otherwise, they have their usual meanings
13322(@kbd{m-} prefix and @kbd{s-} prefix). Thus, @kbd{5 "}, @kbd{0 @@ 5 "}, and
13323@kbd{0 h 5 s} are some of the ways to enter the quantity ``five seconds.''
13324The @kbd{'} key is recognized as ``minutes'' only if @kbd{@@} (or @kbd{h} or
13325@kbd{o}) has already been pressed; otherwise it means to switch to algebraic
13326entry.
13327
13328@node Date Formats, Truncating the Stack, HMS Formats, Display Modes
13329@subsection Date Formats
13330
13331@noindent
13332@kindex d d
13333@pindex calc-date-notation
13334The @kbd{d d} (@code{calc-date-notation}) command controls the display
13335of date forms (@pxref{Date Forms}). It prompts for a string which
13336contains letters that represent the various parts of a date and time.
13337To show which parts should be omitted when the form represents a pure
13338date with no time, parts of the string can be enclosed in @samp{< >}
13339marks. If you don't include @samp{< >} markers in the format, Calc
13340guesses at which parts, if any, should be omitted when formatting
13341pure dates.
13342
13343The default format is: @samp{<H:mm:SSpp >Www Mmm D, YYYY}.
13344An example string in this format is @samp{3:32pm Wed Jan 9, 1991}.
13345If you enter a blank format string, this default format is
13346reestablished.
13347
13348Calc uses @samp{< >} notation for nameless functions as well as for
13349dates. @xref{Specifying Operators}. To avoid confusion with nameless
13350functions, your date formats should avoid using the @samp{#} character.
13351
13352@menu
13353* Date Formatting Codes::
13354* Free-Form Dates::
13355* Standard Date Formats::
13356@end menu
13357
13358@node Date Formatting Codes, Free-Form Dates, Date Formats, Date Formats
13359@subsubsection Date Formatting Codes
13360
13361@noindent
13362When displaying a date, the current date format is used. All
13363characters except for letters and @samp{<} and @samp{>} are
13364copied literally when dates are formatted. The portion between
13365@samp{< >} markers is omitted for pure dates, or included for
13366date/time forms. Letters are interpreted according to the table
13367below.
13368
13369When dates are read in during algebraic entry, Calc first tries to
13370match the input string to the current format either with or without
13371the time part. The punctuation characters (including spaces) must
13372match exactly; letter fields must correspond to suitable text in
13373the input. If this doesn't work, Calc checks if the input is a
13374simple number; if so, the number is interpreted as a number of days
13375since Jan 1, 1 AD. Otherwise, Calc tries a much more relaxed and
13376flexible algorithm which is described in the next section.
13377
13378Weekday names are ignored during reading.
13379
13380Two-digit year numbers are interpreted as lying in the range
13381from 1941 to 2039. Years outside that range are always
13382entered and displayed in full. Year numbers with a leading
13383@samp{+} sign are always interpreted exactly, allowing the
13384entry and display of the years 1 through 99 AD.
13385
13386Here is a complete list of the formatting codes for dates:
13387
13388@table @asis
13389@item Y
13390Year: ``91'' for 1991, ``7'' for 2007, ``+23'' for 23 AD.
13391@item YY
13392Year: ``91'' for 1991, ``07'' for 2007, ``+23'' for 23 AD.
13393@item BY
13394Year: ``91'' for 1991, `` 7'' for 2007, ``+23'' for 23 AD.
13395@item YYY
13396Year: ``1991'' for 1991, ``23'' for 23 AD.
13397@item YYYY
13398Year: ``1991'' for 1991, ``+23'' for 23 AD.
13399@item aa
13400Year: ``ad'' or blank.
13401@item AA
13402Year: ``AD'' or blank.
13403@item aaa
13404Year: ``ad '' or blank. (Note trailing space.)
13405@item AAA
13406Year: ``AD '' or blank.
13407@item aaaa
13408Year: ``a.d.'' or blank.
13409@item AAAA
13410Year: ``A.D.'' or blank.
13411@item bb
13412Year: ``bc'' or blank.
13413@item BB
13414Year: ``BC'' or blank.
13415@item bbb
13416Year: `` bc'' or blank. (Note leading space.)
13417@item BBB
13418Year: `` BC'' or blank.
13419@item bbbb
13420Year: ``b.c.'' or blank.
13421@item BBBB
13422Year: ``B.C.'' or blank.
13423@item M
13424Month: ``8'' for August.
13425@item MM
13426Month: ``08'' for August.
13427@item BM
13428Month: `` 8'' for August.
13429@item MMM
13430Month: ``AUG'' for August.
13431@item Mmm
13432Month: ``Aug'' for August.
13433@item mmm
13434Month: ``aug'' for August.
13435@item MMMM
13436Month: ``AUGUST'' for August.
13437@item Mmmm
13438Month: ``August'' for August.
13439@item D
13440Day: ``7'' for 7th day of month.
13441@item DD
13442Day: ``07'' for 7th day of month.
13443@item BD
13444Day: `` 7'' for 7th day of month.
13445@item W
13446Weekday: ``0'' for Sunday, ``6'' for Saturday.
13447@item WWW
13448Weekday: ``SUN'' for Sunday.
13449@item Www
13450Weekday: ``Sun'' for Sunday.
13451@item www
13452Weekday: ``sun'' for Sunday.
13453@item WWWW
13454Weekday: ``SUNDAY'' for Sunday.
13455@item Wwww
13456Weekday: ``Sunday'' for Sunday.
13457@item d
13458Day of year: ``34'' for Feb. 3.
13459@item ddd
13460Day of year: ``034'' for Feb. 3.
13461@item bdd
13462Day of year: `` 34'' for Feb. 3.
13463@item h
13464Hour: ``5'' for 5 AM; ``17'' for 5 PM.
13465@item hh
13466Hour: ``05'' for 5 AM; ``17'' for 5 PM.
13467@item bh
13468Hour: `` 5'' for 5 AM; ``17'' for 5 PM.
13469@item H
13470Hour: ``5'' for 5 AM and 5 PM.
13471@item HH
13472Hour: ``05'' for 5 AM and 5 PM.
13473@item BH
13474Hour: `` 5'' for 5 AM and 5 PM.
13475@item p
13476AM/PM: ``a'' or ``p''.
13477@item P
13478AM/PM: ``A'' or ``P''.
13479@item pp
13480AM/PM: ``am'' or ``pm''.
13481@item PP
13482AM/PM: ``AM'' or ``PM''.
13483@item pppp
13484AM/PM: ``a.m.'' or ``p.m.''.
13485@item PPPP
13486AM/PM: ``A.M.'' or ``P.M.''.
13487@item m
13488Minutes: ``7'' for 7.
13489@item mm
13490Minutes: ``07'' for 7.
13491@item bm
13492Minutes: `` 7'' for 7.
13493@item s
13494Seconds: ``7'' for 7; ``7.23'' for 7.23.
13495@item ss
13496Seconds: ``07'' for 7; ``07.23'' for 7.23.
13497@item bs
13498Seconds: `` 7'' for 7; `` 7.23'' for 7.23.
13499@item SS
13500Optional seconds: ``07'' for 7; blank for 0.
13501@item BS
13502Optional seconds: `` 7'' for 7; blank for 0.
13503@item N
13504Numeric date/time: ``726842.25'' for 6:00am Wed Jan 9, 1991.
13505@item n
13506Numeric date: ``726842'' for any time on Wed Jan 9, 1991.
13507@item J
13508Julian date/time: ``2448265.75'' for 6:00am Wed Jan 9, 1991.
13509@item j
13510Julian date: ``2448266'' for any time on Wed Jan 9, 1991.
13511@item U
13512Unix time: ``663400800'' for 6:00am Wed Jan 9, 1991.
13513@item X
13514Brackets suppression. An ``X'' at the front of the format
13515causes the surrounding @w{@samp{< >}} delimiters to be omitted
13516when formatting dates. Note that the brackets are still
13517required for algebraic entry.
13518@end table
13519
13520If ``SS'' or ``BS'' (optional seconds) is preceded by a colon, the
13521colon is also omitted if the seconds part is zero.
13522
13523If ``bb,'' ``bbb'' or ``bbbb'' or their upper-case equivalents
13524appear in the format, then negative year numbers are displayed
13525without a minus sign. Note that ``aa'' and ``bb'' are mutually
13526exclusive. Some typical usages would be @samp{YYYY AABB};
13527@samp{AAAYYYYBBB}; @samp{YYYYBBB}.
13528
13529The formats ``YY,'' ``YYYY,'' ``MM,'' ``DD,'' ``ddd,'' ``hh,'' ``HH,''
13530``mm,'' ``ss,'' and ``SS'' actually match any number of digits during
13531reading unless several of these codes are strung together with no
13532punctuation in between, in which case the input must have exactly as
13533many digits as there are letters in the format.
13534
13535The ``j,'' ``J,'' and ``U'' formats do not make any time zone
13536adjustment. They effectively use @samp{julian(x,0)} and
13537@samp{unixtime(x,0)} to make the conversion; @pxref{Date Arithmetic}.
13538
13539@node Free-Form Dates, Standard Date Formats, Date Formatting Codes, Date Formats
13540@subsubsection Free-Form Dates
13541
13542@noindent
13543When reading a date form during algebraic entry, Calc falls back
13544on the algorithm described here if the input does not exactly
13545match the current date format. This algorithm generally
13546``does the right thing'' and you don't have to worry about it,
13547but it is described here in full detail for the curious.
13548
13549Calc does not distinguish between upper- and lower-case letters
13550while interpreting dates.
13551
13552First, the time portion, if present, is located somewhere in the
13553text and then removed. The remaining text is then interpreted as
13554the date.
13555
13556A time is of the form @samp{hh:mm:ss}, possibly with the seconds
13557part omitted and possibly with an AM/PM indicator added to indicate
1355812-hour time. If the AM/PM is present, the minutes may also be
13559omitted. The AM/PM part may be any of the words @samp{am},
13560@samp{pm}, @samp{noon}, or @samp{midnight}; each of these may be
13561abbreviated to one letter, and the alternate forms @samp{a.m.},
13562@samp{p.m.}, and @samp{mid} are also understood. Obviously
13563@samp{noon} and @samp{midnight} are allowed only on 12:00:00.
13564The words @samp{noon}, @samp{mid}, and @samp{midnight} are also
13565recognized with no number attached.
13566
13567If there is no AM/PM indicator, the time is interpreted in 24-hour
13568format.
13569
13570To read the date portion, all words and numbers are isolated
13571from the string; other characters are ignored. All words must
13572be either month names or day-of-week names (the latter of which
13573are ignored). Names can be written in full or as three-letter
13574abbreviations.
13575
13576Large numbers, or numbers with @samp{+} or @samp{-} signs,
13577are interpreted as years. If one of the other numbers is
13578greater than 12, then that must be the day and the remaining
13579number in the input is therefore the month. Otherwise, Calc
13580assumes the month, day and year are in the same order that they
13581appear in the current date format. If the year is omitted, the
13582current year is taken from the system clock.
13583
13584If there are too many or too few numbers, or any unrecognizable
13585words, then the input is rejected.
13586
13587If there are any large numbers (of five digits or more) other than
13588the year, they are ignored on the assumption that they are something
13589like Julian dates that were included along with the traditional
13590date components when the date was formatted.
13591
13592One of the words @samp{ad}, @samp{a.d.}, @samp{bc}, or @samp{b.c.}
13593may optionally be used; the latter two are equivalent to a
13594minus sign on the year value.
13595
13596If you always enter a four-digit year, and use a name instead
13597of a number for the month, there is no danger of ambiguity.
13598
13599@node Standard Date Formats, , Free-Form Dates, Date Formats
13600@subsubsection Standard Date Formats
13601
13602@noindent
13603There are actually ten standard date formats, numbered 0 through 9.
13604Entering a blank line at the @kbd{d d} command's prompt gives
13605you format number 1, Calc's usual format. You can enter any digit
13606to select the other formats.
13607
13608To create your own standard date formats, give a numeric prefix
13609argument from 0 to 9 to the @w{@kbd{d d}} command. The format you
13610enter will be recorded as the new standard format of that
13611number, as well as becoming the new current date format.
13612You can save your formats permanently with the @w{@kbd{m m}}
13613command (@pxref{Mode Settings}).
13614
13615@table @asis
13616@item 0
13617@samp{N} (Numerical format)
13618@item 1
13619@samp{<H:mm:SSpp >Www Mmm D, YYYY} (American format)
13620@item 2
13621@samp{D Mmm YYYY<, h:mm:SS>} (European format)
13622@item 3
13623@samp{Www Mmm BD< hh:mm:ss> YYYY} (Unix written date format)
13624@item 4
13625@samp{M/D/Y< H:mm:SSpp>} (American slashed format)
13626@item 5
13627@samp{D.M.Y< h:mm:SS>} (European dotted format)
13628@item 6
13629@samp{M-D-Y< H:mm:SSpp>} (American dashed format)
13630@item 7
13631@samp{D-M-Y< h:mm:SS>} (European dashed format)
13632@item 8
13633@samp{j<, h:mm:ss>} (Julian day plus time)
13634@item 9
13635@samp{YYddd< hh:mm:ss>} (Year-day format)
13636@end table
13637
13638@node Truncating the Stack, Justification, Date Formats, Display Modes
13639@subsection Truncating the Stack
13640
13641@noindent
13642@kindex d t
13643@pindex calc-truncate-stack
13644@cindex Truncating the stack
13645@cindex Narrowing the stack
13646The @kbd{d t} (@code{calc-truncate-stack}) command moves the @samp{.}@:
13647line that marks the top-of-stack up or down in the Calculator buffer.
13648The number right above that line is considered to the be at the top of
13649the stack. Any numbers below that line are ``hidden'' from all stack
13650operations (although still visible to the user). This is similar to the
13651Emacs ``narrowing'' feature, except that the values below the @samp{.}
13652are @emph{visible}, just temporarily frozen. This feature allows you to
13653keep several independent calculations running at once in different parts
13654of the stack, or to apply a certain command to an element buried deep in
13655the stack.
13656
13657Pressing @kbd{d t} by itself moves the @samp{.} to the line the cursor
13658is on. Thus, this line and all those below it become hidden. To un-hide
13659these lines, move down to the end of the buffer and press @w{@kbd{d t}}.
13660With a positive numeric prefix argument @expr{n}, @kbd{d t} hides the
13661bottom @expr{n} values in the buffer. With a negative argument, it hides
13662all but the top @expr{n} values. With an argument of zero, it hides zero
13663values, i.e., moves the @samp{.} all the way down to the bottom.
13664
13665@kindex d [
13666@pindex calc-truncate-up
13667@kindex d ]
13668@pindex calc-truncate-down
13669The @kbd{d [} (@code{calc-truncate-up}) and @kbd{d ]}
13670(@code{calc-truncate-down}) commands move the @samp{.} up or down one
13671line at a time (or several lines with a prefix argument).
13672
13673@node Justification, Labels, Truncating the Stack, Display Modes
13674@subsection Justification
13675
13676@noindent
13677@kindex d <
13678@pindex calc-left-justify
13679@kindex d =
13680@pindex calc-center-justify
13681@kindex d >
13682@pindex calc-right-justify
13683Values on the stack are normally left-justified in the window. You can
13684control this arrangement by typing @kbd{d <} (@code{calc-left-justify}),
13685@kbd{d >} (@code{calc-right-justify}), or @kbd{d =}
13686(@code{calc-center-justify}). For example, in Right-Justification mode,
13687stack entries are displayed flush-right against the right edge of the
13688window.
13689
13690If you change the width of the Calculator window you may have to type
13691@kbd{d @key{SPC}} (@code{calc-refresh}) to re-align right-justified or centered
13692text.
13693
13694Right-justification is especially useful together with fixed-point
13695notation (see @code{d f}; @code{calc-fix-notation}). With these modes
13696together, the decimal points on numbers will always line up.
13697
13698With a numeric prefix argument, the justification commands give you
13699a little extra control over the display. The argument specifies the
13700horizontal ``origin'' of a display line. It is also possible to
13701specify a maximum line width using the @kbd{d b} command (@pxref{Normal
13702Language Modes}). For reference, the precise rules for formatting and
13703breaking lines are given below. Notice that the interaction between
13704origin and line width is slightly different in each justification
13705mode.
13706
13707In Left-Justified mode, the line is indented by a number of spaces
13708given by the origin (default zero). If the result is longer than the
13709maximum line width, if given, or too wide to fit in the Calc window
13710otherwise, then it is broken into lines which will fit; each broken
13711line is indented to the origin.
13712
13713In Right-Justified mode, lines are shifted right so that the rightmost
13714character is just before the origin, or just before the current
13715window width if no origin was specified. If the line is too long
13716for this, then it is broken; the current line width is used, if
13717specified, or else the origin is used as a width if that is
13718specified, or else the line is broken to fit in the window.
13719
13720In Centering mode, the origin is the column number of the center of
13721each stack entry. If a line width is specified, lines will not be
13722allowed to go past that width; Calc will either indent less or
13723break the lines if necessary. If no origin is specified, half the
13724line width or Calc window width is used.
13725
13726Note that, in each case, if line numbering is enabled the display
13727is indented an additional four spaces to make room for the line
13728number. The width of the line number is taken into account when
13729positioning according to the current Calc window width, but not
13730when positioning by explicit origins and widths. In the latter
13731case, the display is formatted as specified, and then uniformly
13732shifted over four spaces to fit the line numbers.
13733
13734@node Labels, , Justification, Display Modes
13735@subsection Labels
13736
13737@noindent
13738@kindex d @{
13739@pindex calc-left-label
13740The @kbd{d @{} (@code{calc-left-label}) command prompts for a string,
13741then displays that string to the left of every stack entry. If the
13742entries are left-justified (@pxref{Justification}), then they will
13743appear immediately after the label (unless you specified an origin
13744greater than the length of the label). If the entries are centered
13745or right-justified, the label appears on the far left and does not
13746affect the horizontal position of the stack entry.
13747
13748Give a blank string (with @kbd{d @{ @key{RET}}) to turn the label off.
13749
13750@kindex d @}
13751@pindex calc-right-label
13752The @kbd{d @}} (@code{calc-right-label}) command similarly adds a
13753label on the righthand side. It does not affect positioning of
13754the stack entries unless they are right-justified. Also, if both
13755a line width and an origin are given in Right-Justified mode, the
13756stack entry is justified to the origin and the righthand label is
13757justified to the line width.
13758
13759One application of labels would be to add equation numbers to
13760formulas you are manipulating in Calc and then copying into a
13761document (possibly using Embedded mode). The equations would
13762typically be centered, and the equation numbers would be on the
13763left or right as you prefer.
13764
13765@node Language Modes, Modes Variable, Display Modes, Mode Settings
13766@section Language Modes
13767
13768@noindent
13769The commands in this section change Calc to use a different notation for
13770entry and display of formulas, corresponding to the conventions of some
13771other common language such as Pascal or La@TeX{}. Objects displayed on the
13772stack or yanked from the Calculator to an editing buffer will be formatted
13773in the current language; objects entered in algebraic entry or yanked from
13774another buffer will be interpreted according to the current language.
13775
13776The current language has no effect on things written to or read from the
13777trail buffer, nor does it affect numeric entry. Only algebraic entry is
13778affected. You can make even algebraic entry ignore the current language
13779and use the standard notation by giving a numeric prefix, e.g., @kbd{C-u '}.
13780
13781For example, suppose the formula @samp{2*a[1] + atan(a[2])} occurs in a C
13782program; elsewhere in the program you need the derivatives of this formula
13783with respect to @samp{a[1]} and @samp{a[2]}. First, type @kbd{d C}
13784to switch to C notation. Now use @code{C-u C-x * g} to grab the formula
13785into the Calculator, @kbd{a d a[1] @key{RET}} to differentiate with respect
13786to the first variable, and @kbd{C-x * y} to yank the formula for the derivative
13787back into your C program. Press @kbd{U} to undo the differentiation and
13788repeat with @kbd{a d a[2] @key{RET}} for the other derivative.
13789
13790Without being switched into C mode first, Calc would have misinterpreted
13791the brackets in @samp{a[1]} and @samp{a[2]}, would not have known that
13792@code{atan} was equivalent to Calc's built-in @code{arctan} function,
13793and would have written the formula back with notations (like implicit
13794multiplication) which would not have been valid for a C program.
13795
13796As another example, suppose you are maintaining a C program and a La@TeX{}
13797document, each of which needs a copy of the same formula. You can grab the
13798formula from the program in C mode, switch to La@TeX{} mode, and yank the
13799formula into the document in La@TeX{} math-mode format.
13800
13801Language modes are selected by typing the letter @kbd{d} followed by a
13802shifted letter key.
13803
13804@menu
13805* Normal Language Modes::
13806* C FORTRAN Pascal::
13807* TeX and LaTeX Language Modes::
13808* Eqn Language Mode::
4e320733
JB
13809* Yacas Language Mode::
13810* Maxima Language Mode::
13811* Giac Language Mode::
4009494e
GM
13812* Mathematica Language Mode::
13813* Maple Language Mode::
13814* Compositions::
13815* Syntax Tables::
13816@end menu
13817
13818@node Normal Language Modes, C FORTRAN Pascal, Language Modes, Language Modes
13819@subsection Normal Language Modes
13820
13821@noindent
13822@kindex d N
13823@pindex calc-normal-language
13824The @kbd{d N} (@code{calc-normal-language}) command selects the usual
13825notation for Calc formulas, as described in the rest of this manual.
13826Matrices are displayed in a multi-line tabular format, but all other
13827objects are written in linear form, as they would be typed from the
13828keyboard.
13829
13830@kindex d O
13831@pindex calc-flat-language
13832@cindex Matrix display
13833The @kbd{d O} (@code{calc-flat-language}) command selects a language
13834identical with the normal one, except that matrices are written in
13835one-line form along with everything else. In some applications this
13836form may be more suitable for yanking data into other buffers.
13837
13838@kindex d b
13839@pindex calc-line-breaking
13840@cindex Line breaking
13841@cindex Breaking up long lines
13842Even in one-line mode, long formulas or vectors will still be split
13843across multiple lines if they exceed the width of the Calculator window.
13844The @kbd{d b} (@code{calc-line-breaking}) command turns this line-breaking
13845feature on and off. (It works independently of the current language.)
13846If you give a numeric prefix argument of five or greater to the @kbd{d b}
13847command, that argument will specify the line width used when breaking
13848long lines.
13849
13850@kindex d B
13851@pindex calc-big-language
13852The @kbd{d B} (@code{calc-big-language}) command selects a language
13853which uses textual approximations to various mathematical notations,
13854such as powers, quotients, and square roots:
13855
13856@example
13857 ____________
13858 | a + 1 2
13859 | ----- + c
13860\| b
13861@end example
13862
13863@noindent
13864in place of @samp{sqrt((a+1)/b + c^2)}.
13865
13866Subscripts like @samp{a_i} are displayed as actual subscripts in Big
13867mode. Double subscripts, @samp{a_i_j} (@samp{subscr(subscr(a, i), j)})
13868are displayed as @samp{a} with subscripts separated by commas:
13869@samp{i, j}. They must still be entered in the usual underscore
13870notation.
13871
13872One slight ambiguity of Big notation is that
13873
13874@example
13875 3
13876- -
13877 4
13878@end example
13879
13880@noindent
13881can represent either the negative rational number @expr{-3:4}, or the
13882actual expression @samp{-(3/4)}; but the latter formula would normally
13883never be displayed because it would immediately be evaluated to
13884@expr{-3:4} or @expr{-0.75}, so this ambiguity is not a problem in
13885typical use.
13886
13887Non-decimal numbers are displayed with subscripts. Thus there is no
13888way to tell the difference between @samp{16#C2} and @samp{C2_16},
13889though generally you will know which interpretation is correct.
13890Logarithms @samp{log(x,b)} and @samp{log10(x)} also use subscripts
13891in Big mode.
13892
13893In Big mode, stack entries often take up several lines. To aid
13894readability, stack entries are separated by a blank line in this mode.
13895You may find it useful to expand the Calc window's height using
13896@kbd{C-x ^} (@code{enlarge-window}) or to make the Calc window the only
13897one on the screen with @kbd{C-x 1} (@code{delete-other-windows}).
13898
13899Long lines are currently not rearranged to fit the window width in
13900Big mode, so you may need to use the @kbd{<} and @kbd{>} keys
13901to scroll across a wide formula. For really big formulas, you may
13902even need to use @kbd{@{} and @kbd{@}} to scroll up and down.
13903
13904@kindex d U
13905@pindex calc-unformatted-language
13906The @kbd{d U} (@code{calc-unformatted-language}) command altogether disables
13907the use of operator notation in formulas. In this mode, the formula
13908shown above would be displayed:
13909
13910@example
13911sqrt(add(div(add(a, 1), b), pow(c, 2)))
13912@end example
13913
13914These four modes differ only in display format, not in the format
13915expected for algebraic entry. The standard Calc operators work in
13916all four modes, and unformatted notation works in any language mode
13917(except that Mathematica mode expects square brackets instead of
13918parentheses).
13919
13920@node C FORTRAN Pascal, TeX and LaTeX Language Modes, Normal Language Modes, Language Modes
13921@subsection C, FORTRAN, and Pascal Modes
13922
13923@noindent
13924@kindex d C
13925@pindex calc-c-language
13926@cindex C language
13927The @kbd{d C} (@code{calc-c-language}) command selects the conventions
13928of the C language for display and entry of formulas. This differs from
13929the normal language mode in a variety of (mostly minor) ways. In
13930particular, C language operators and operator precedences are used in
13931place of Calc's usual ones. For example, @samp{a^b} means @samp{xor(a,b)}
13932in C mode; a value raised to a power is written as a function call,
13933@samp{pow(a,b)}.
13934
13935In C mode, vectors and matrices use curly braces instead of brackets.
13936Octal and hexadecimal values are written with leading @samp{0} or @samp{0x}
13937rather than using the @samp{#} symbol. Array subscripting is
13938translated into @code{subscr} calls, so that @samp{a[i]} in C
13939mode is the same as @samp{a_i} in Normal mode. Assignments
13940turn into the @code{assign} function, which Calc normally displays
13941using the @samp{:=} symbol.
13942
13943The variables @code{pi} and @code{e} would be displayed @samp{pi}
13944and @samp{e} in Normal mode, but in C mode they are displayed as
13945@samp{M_PI} and @samp{M_E}, corresponding to the names of constants
13946typically provided in the @file{<math.h>} header. Functions whose
13947names are different in C are translated automatically for entry and
13948display purposes. For example, entering @samp{asin(x)} will push the
13949formula @samp{arcsin(x)} onto the stack; this formula will be displayed
13950as @samp{asin(x)} as long as C mode is in effect.
13951
13952@kindex d P
13953@pindex calc-pascal-language
13954@cindex Pascal language
13955The @kbd{d P} (@code{calc-pascal-language}) command selects Pascal
13956conventions. Like C mode, Pascal mode interprets array brackets and uses
13957a different table of operators. Hexadecimal numbers are entered and
13958displayed with a preceding dollar sign. (Thus the regular meaning of
13959@kbd{$2} during algebraic entry does not work in Pascal mode, though
13960@kbd{$} (and @kbd{$$}, etc.) not followed by digits works the same as
13961always.) No special provisions are made for other non-decimal numbers,
13962vectors, and so on, since there is no universally accepted standard way
13963of handling these in Pascal.
13964
13965@kindex d F
13966@pindex calc-fortran-language
13967@cindex FORTRAN language
13968The @kbd{d F} (@code{calc-fortran-language}) command selects FORTRAN
13969conventions. Various function names are transformed into FORTRAN
13970equivalents. Vectors are written as @samp{/1, 2, 3/}, and may be
13971entered this way or using square brackets. Since FORTRAN uses round
13972parentheses for both function calls and array subscripts, Calc displays
13973both in the same way; @samp{a(i)} is interpreted as a function call
13974upon reading, and subscripts must be entered as @samp{subscr(a, i)}.
702dbfd9
JB
13975If the variable @code{a} has been declared to have type
13976@code{vector} or @code{matrix}, however, then @samp{a(i)} will be
13977parsed as a subscript. (@xref{Declarations}.) Usually it doesn't
13978matter, though; if you enter the subscript expression @samp{a(i)} and
13979Calc interprets it as a function call, you'll never know the difference
13980unless you switch to another language mode or replace @code{a} with an
13981actual vector (or unless @code{a} happens to be the name of a built-in
4009494e
GM
13982function!).
13983
13984Underscores are allowed in variable and function names in all of these
13985language modes. The underscore here is equivalent to the @samp{#} in
13986Normal mode, or to hyphens in the underlying Emacs Lisp variable names.
13987
13988FORTRAN and Pascal modes normally do not adjust the case of letters in
13989formulas. Most built-in Calc names use lower-case letters. If you use a
13990positive numeric prefix argument with @kbd{d P} or @kbd{d F}, these
13991modes will use upper-case letters exclusively for display, and will
13992convert to lower-case on input. With a negative prefix, these modes
13993convert to lower-case for display and input.
13994
13995@node TeX and LaTeX Language Modes, Eqn Language Mode, C FORTRAN Pascal, Language Modes
13996@subsection @TeX{} and La@TeX{} Language Modes
13997
13998@noindent
13999@kindex d T
14000@pindex calc-tex-language
14001@cindex TeX language
14002@kindex d L
14003@pindex calc-latex-language
14004@cindex LaTeX language
14005The @kbd{d T} (@code{calc-tex-language}) command selects the conventions
14006of ``math mode'' in Donald Knuth's @TeX{} typesetting language,
14007and the @kbd{d L} (@code{calc-latex-language}) command selects the
14008conventions of ``math mode'' in La@TeX{}, a typesetting language that
14009uses @TeX{} as its formatting engine. Calc's La@TeX{} language mode can
14010read any formula that the @TeX{} language mode can, although La@TeX{}
14011mode may display it differently.
14012
14013Formulas are entered and displayed in the appropriate notation;
14014@texline @math{\sin(a/b)}
14015@infoline @expr{sin(a/b)}
0cbe9c78 14016will appear as @samp{\sin\left( @{a \over b@} \right)} in @TeX{} mode and
4009494e
GM
14017@samp{\sin\left(\frac@{a@}@{b@}\right)} in La@TeX{} mode.
14018Math formulas are often enclosed by @samp{$ $} signs in @TeX{} and
14019La@TeX{}; these should be omitted when interfacing with Calc. To Calc,
14020the @samp{$} sign has the same meaning it always does in algebraic
14021formulas (a reference to an existing entry on the stack).
14022
14023Complex numbers are displayed as in @samp{3 + 4i}. Fractions and
14024quotients are written using @code{\over} in @TeX{} mode (as in
14025@code{@{a \over b@}}) and @code{\frac} in La@TeX{} mode (as in
14026@code{\frac@{a@}@{b@}}); binomial coefficients are written with
14027@code{\choose} in @TeX{} mode (as in @code{@{a \choose b@}}) and
14028@code{\binom} in La@TeX{} mode (as in @code{\binom@{a@}@{b@}}).
14029Interval forms are written with @code{\ldots}, and error forms are
14030written with @code{\pm}. Absolute values are written as in
14031@samp{|x + 1|}, and the floor and ceiling functions are written with
14032@code{\lfloor}, @code{\rfloor}, etc. The words @code{\left} and
14033@code{\right} are ignored when reading formulas in @TeX{} and La@TeX{}
14034modes. Both @code{inf} and @code{uinf} are written as @code{\infty};
14035when read, @code{\infty} always translates to @code{inf}.
14036
14037Function calls are written the usual way, with the function name followed
14038by the arguments in parentheses. However, functions for which @TeX{}
14039and La@TeX{} have special names (like @code{\sin}) will use curly braces
14040instead of parentheses for very simple arguments. During input, curly
14041braces and parentheses work equally well for grouping, but when the
14042document is formatted the curly braces will be invisible. Thus the
14043printed result is
14044@texline @math{\sin{2 x}}
14045@infoline @expr{sin 2x}
14046but
14047@texline @math{\sin(2 + x)}.
14048@infoline @expr{sin(2 + x)}.
14049
14050Function and variable names not treated specially by @TeX{} and La@TeX{}
14051are simply written out as-is, which will cause them to come out in
14052italic letters in the printed document. If you invoke @kbd{d T} or
14053@kbd{d L} with a positive numeric prefix argument, names of more than
14054one character will instead be enclosed in a protective commands that
14055will prevent them from being typeset in the math italics; they will be
14056written @samp{\hbox@{@var{name}@}} in @TeX{} mode and
14057@samp{\text@{@var{name}@}} in La@TeX{} mode. The
14058@samp{\hbox@{ @}} and @samp{\text@{ @}} notations are ignored during
14059reading. If you use a negative prefix argument, such function names are
14060written @samp{\@var{name}}, and function names that begin with @code{\} during
14061reading have the @code{\} removed. (Note that in this mode, long
14062variable names are still written with @code{\hbox} or @code{\text}.
14063However, you can always make an actual variable name like @code{\bar} in
14064any @TeX{} mode.)
14065
14066During reading, text of the form @samp{\matrix@{ ...@: @}} is replaced
14067by @samp{[ ...@: ]}. The same also applies to @code{\pmatrix} and
14068@code{\bmatrix}. In La@TeX{} mode this also applies to
14069@samp{\begin@{matrix@} ... \end@{matrix@}},
14070@samp{\begin@{bmatrix@} ... \end@{bmatrix@}},
14071@samp{\begin@{pmatrix@} ... \end@{pmatrix@}}, as well as
14072@samp{\begin@{smallmatrix@} ... \end@{smallmatrix@}}.
14073The symbol @samp{&} is interpreted as a comma,
14074and the symbols @samp{\cr} and @samp{\\} are interpreted as semicolons.
14075During output, matrices are displayed in @samp{\matrix@{ a & b \\ c & d@}}
14076format in @TeX{} mode and in
14077@samp{\begin@{pmatrix@} a & b \\ c & d \end@{pmatrix@}} format in
14078La@TeX{} mode; you may need to edit this afterwards to change to your
14079preferred matrix form. If you invoke @kbd{d T} or @kbd{d L} with an
14080argument of 2 or -2, then matrices will be displayed in two-dimensional
14081form, such as
14082
14083@example
14084\begin@{pmatrix@}
14085a & b \\
14086c & d
14087\end@{pmatrix@}
14088@end example
14089
14090@noindent
14091This may be convenient for isolated matrices, but could lead to
14092expressions being displayed like
14093
14094@example
14095\begin@{pmatrix@} \times x
14096a & b \\
14097c & d
14098\end@{pmatrix@}
14099@end example
14100
14101@noindent
14102While this wouldn't bother Calc, it is incorrect La@TeX{}.
14103(Similarly for @TeX{}.)
14104
14105Accents like @code{\tilde} and @code{\bar} translate into function
14106calls internally (@samp{tilde(x)}, @samp{bar(x)}). The @code{\underline}
14107sequence is treated as an accent. The @code{\vec} accent corresponds
14108to the function name @code{Vec}, because @code{vec} is the name of
14109a built-in Calc function. The following table shows the accents
14110in Calc, @TeX{}, La@TeX{} and @dfn{eqn} (described in the next section):
14111
14112@iftex
14113@begingroup
14114@let@calcindexershow=@calcindexernoshow @c Suppress marginal notes
14115@let@calcindexersh=@calcindexernoshow
14116@end iftex
14117@ignore
14118@starindex
14119@end ignore
14120@tindex acute
14121@ignore
14122@starindex
14123@end ignore
14124@tindex Acute
14125@ignore
14126@starindex
14127@end ignore
14128@tindex bar
14129@ignore
14130@starindex
14131@end ignore
14132@tindex Bar
14133@ignore
14134@starindex
14135@end ignore
14136@tindex breve
14137@ignore
14138@starindex
14139@end ignore
14140@tindex Breve
14141@ignore
14142@starindex
14143@end ignore
14144@tindex check
14145@ignore
14146@starindex
14147@end ignore
14148@tindex Check
14149@ignore
14150@starindex
14151@end ignore
14152@tindex dddot
14153@ignore
14154@starindex
14155@end ignore
14156@tindex ddddot
14157@ignore
14158@starindex
14159@end ignore
14160@tindex dot
14161@ignore
14162@starindex
14163@end ignore
14164@tindex Dot
14165@ignore
14166@starindex
14167@end ignore
14168@tindex dotdot
14169@ignore
14170@starindex
14171@end ignore
14172@tindex DotDot
14173@ignore
14174@starindex
14175@end ignore
14176@tindex dyad
14177@ignore
14178@starindex
14179@end ignore
14180@tindex grave
14181@ignore
14182@starindex
14183@end ignore
14184@tindex Grave
14185@ignore
14186@starindex
14187@end ignore
14188@tindex hat
14189@ignore
14190@starindex
14191@end ignore
14192@tindex Hat
14193@ignore
14194@starindex
14195@end ignore
14196@tindex Prime
14197@ignore
14198@starindex
14199@end ignore
14200@tindex tilde
14201@ignore
14202@starindex
14203@end ignore
14204@tindex Tilde
14205@ignore
14206@starindex
14207@end ignore
14208@tindex under
14209@ignore
14210@starindex
14211@end ignore
14212@tindex Vec
14213@ignore
14214@starindex
14215@end ignore
14216@tindex VEC
14217@iftex
14218@endgroup
14219@end iftex
14220@example
14221Calc TeX LaTeX eqn
14222---- --- ----- ---
14223acute \acute \acute
14224Acute \Acute
14225bar \bar \bar bar
14226Bar \Bar
14227breve \breve \breve
14228Breve \Breve
14229check \check \check
14230Check \Check
14231dddot \dddot
14232ddddot \ddddot
14233dot \dot \dot dot
14234Dot \Dot
14235dotdot \ddot \ddot dotdot
14236DotDot \Ddot
14237dyad dyad
14238grave \grave \grave
14239Grave \Grave
14240hat \hat \hat hat
14241Hat \Hat
14242Prime prime
14243tilde \tilde \tilde tilde
14244Tilde \Tilde
14245under \underline \underline under
14246Vec \vec \vec vec
14247VEC \Vec
14248@end example
14249
14250The @samp{=>} (evaluates-to) operator appears as a @code{\to} symbol:
14251@samp{@{@var{a} \to @var{b}@}}. @TeX{} defines @code{\to} as an
14252alias for @code{\rightarrow}. However, if the @samp{=>} is the
14253top-level expression being formatted, a slightly different notation
14254is used: @samp{\evalto @var{a} \to @var{b}}. The @code{\evalto}
14255word is ignored by Calc's input routines, and is undefined in @TeX{}.
14256You will typically want to include one of the following definitions
14257at the top of a @TeX{} file that uses @code{\evalto}:
14258
14259@example
14260\def\evalto@{@}
14261\def\evalto#1\to@{@}
14262@end example
14263
14264The first definition formats evaluates-to operators in the usual
14265way. The second causes only the @var{b} part to appear in the
14266printed document; the @var{a} part and the arrow are hidden.
14267Another definition you may wish to use is @samp{\let\to=\Rightarrow}
14268which causes @code{\to} to appear more like Calc's @samp{=>} symbol.
14269@xref{Evaluates-To Operator}, for a discussion of @code{evalto}.
14270
14271The complete set of @TeX{} control sequences that are ignored during
14272reading is:
14273
14274@example
14275\hbox \mbox \text \left \right
14276\, \> \: \; \! \quad \qquad \hfil \hfill
14277\displaystyle \textstyle \dsize \tsize
14278\scriptstyle \scriptscriptstyle \ssize \ssize
14279\rm \bf \it \sl \roman \bold \italic \slanted
14280\cal \mit \Cal \Bbb \frak \goth
14281\evalto
14282@end example
14283
14284Note that, because these symbols are ignored, reading a @TeX{} or
14285La@TeX{} formula into Calc and writing it back out may lose spacing and
14286font information.
14287
14288Also, the ``discretionary multiplication sign'' @samp{\*} is read
14289the same as @samp{*}.
14290
14291@ifnottex
14292The @TeX{} version of this manual includes some printed examples at the
14293end of this section.
14294@end ifnottex
14295@iftex
14296Here are some examples of how various Calc formulas are formatted in @TeX{}:
14297
14298@example
14299@group
14300sin(a^2 / b_i)
14301\sin\left( {a^2 \over b_i} \right)
14302@end group
14303@end example
14304@tex
14305$$ \sin\left( a^2 \over b_i \right) $$
14306@end tex
14307@sp 1
14308
14309@example
14310@group
14311[(3, 4), 3:4, 3 +/- 4, [3 .. inf)]
14312[3 + 4i, @{3 \over 4@}, 3 \pm 4, [3 \ldots \infty)]
14313@end group
14314@end example
14315@tex
14316\turnoffactive
14317$$ [3 + 4i, {3 \over 4}, 3 \pm 4, [ 3 \ldots \infty)] $$
14318@end tex
14319@sp 1
14320
14321@example
14322@group
14323[abs(a), abs(a / b), floor(a), ceil(a / b)]
14324[|a|, \left| a \over b \right|,
14325 \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
14326@end group
14327@end example
14328@tex
14329$$ [|a|, \left| a \over b \right|,
14330 \lfloor a \rfloor, \left\lceil a \over b \right\rceil] $$
14331@end tex
14332@sp 1
14333
14334@example
14335@group
14336[sin(a), sin(2 a), sin(2 + a), sin(a / b)]
14337[\sin@{a@}, \sin@{2 a@}, \sin(2 + a),
14338 \sin\left( @{a \over b@} \right)]
14339@end group
14340@end example
14341@tex
14342\turnoffactive
14343$$ [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)] $$
14344@end tex
14345@sp 2
14346
14347First with plain @kbd{d T}, then with @kbd{C-u d T}, then finally with
14348@kbd{C-u - d T} (using the example definition
14349@samp{\def\foo#1@{\tilde F(#1)@}}:
14350
14351@example
14352@group
14353[f(a), foo(bar), sin(pi)]
14354[f(a), foo(bar), \sin{\pi}]
14355[f(a), \hbox@{foo@}(\hbox@{bar@}), \sin@{\pi@}]
14356[f(a), \foo@{\hbox@{bar@}@}, \sin@{\pi@}]
14357@end group
14358@end example
14359@tex
14360$$ [f(a), foo(bar), \sin{\pi}] $$
14361$$ [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] $$
14362$$ [f(a), \tilde F(\hbox{bar}), \sin{\pi}] $$
14363@end tex
14364@sp 2
14365
14366First with @samp{\def\evalto@{@}}, then with @samp{\def\evalto#1\to@{@}}:
14367
14368@example
14369@group
143702 + 3 => 5
14371\evalto 2 + 3 \to 5
14372@end group
14373@end example
14374@tex
14375\turnoffactive
14376$$ 2 + 3 \to 5 $$
14377$$ 5 $$
14378@end tex
14379@sp 2
14380
14381First with standard @code{\to}, then with @samp{\let\to\Rightarrow}:
14382
14383@example
14384@group
14385[2 + 3 => 5, a / 2 => (b + c) / 2]
14386[@{2 + 3 \to 5@}, @{@{a \over 2@} \to @{b + c \over 2@}@}]
14387@end group
14388@end example
14389@tex
14390\turnoffactive
14391$$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$
14392{\let\to\Rightarrow
14393$$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$}
14394@end tex
14395@sp 2
14396
14397Matrices normally, then changing @code{\matrix} to @code{\pmatrix}:
14398
14399@example
14400@group
14401[ [ a / b, 0 ], [ 0, 2^(x + 1) ] ]
14402\matrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14403\pmatrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14404@end group
14405@end example
14406@tex
14407\turnoffactive
14408$$ \matrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14409$$ \pmatrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14410@end tex
14411@sp 2
14412@end iftex
14413
702dbfd9 14414@node Eqn Language Mode, Yacas Language Mode, TeX and LaTeX Language Modes, Language Modes
4009494e
GM
14415@subsection Eqn Language Mode
14416
14417@noindent
14418@kindex d E
14419@pindex calc-eqn-language
14420@dfn{Eqn} is another popular formatter for math formulas. It is
14421designed for use with the TROFF text formatter, and comes standard
14422with many versions of Unix. The @kbd{d E} (@code{calc-eqn-language})
14423command selects @dfn{eqn} notation.
14424
14425The @dfn{eqn} language's main idiosyncrasy is that whitespace plays
14426a significant part in the parsing of the language. For example,
14427@samp{sqrt x+1 + y} treats @samp{x+1} as the argument of the
14428@code{sqrt} operator. @dfn{Eqn} also understands more conventional
14429grouping using curly braces: @samp{sqrt@{x+1@} + y}. Braces are
14430required only when the argument contains spaces.
14431
14432In Calc's @dfn{eqn} mode, however, curly braces are required to
14433delimit arguments of operators like @code{sqrt}. The first of the
14434above examples would treat only the @samp{x} as the argument of
14435@code{sqrt}, and in fact @samp{sin x+1} would be interpreted as
14436@samp{sin * x + 1}, because @code{sin} is not a special operator
14437in the @dfn{eqn} language. If you always surround the argument
14438with curly braces, Calc will never misunderstand.
14439
14440Calc also understands parentheses as grouping characters. Another
14441peculiarity of @dfn{eqn}'s syntax makes it advisable to separate
14442words with spaces from any surrounding characters that aren't curly
14443braces, so Calc writes @samp{sin ( x + y )} in @dfn{eqn} mode.
14444(The spaces around @code{sin} are important to make @dfn{eqn}
14445recognize that @code{sin} should be typeset in a roman font, and
14446the spaces around @code{x} and @code{y} are a good idea just in
14447case the @dfn{eqn} document has defined special meanings for these
14448names, too.)
14449
14450Powers and subscripts are written with the @code{sub} and @code{sup}
14451operators, respectively. Note that the caret symbol @samp{^} is
14452treated the same as a space in @dfn{eqn} mode, as is the @samp{~}
14453symbol (these are used to introduce spaces of various widths into
14454the typeset output of @dfn{eqn}).
14455
14456As in La@TeX{} mode, Calc's formatter omits parentheses around the
14457arguments of functions like @code{ln} and @code{sin} if they are
14458``simple-looking''; in this case Calc surrounds the argument with
14459braces, separated by a @samp{~} from the function name: @samp{sin~@{x@}}.
14460
14461Font change codes (like @samp{roman @var{x}}) and positioning codes
14462(like @samp{~} and @samp{down @var{n} @var{x}}) are ignored by the
14463@dfn{eqn} reader. Also ignored are the words @code{left}, @code{right},
14464@code{mark}, and @code{lineup}. Quotation marks in @dfn{eqn} mode input
14465are treated the same as curly braces: @samp{sqrt "1+x"} is equivalent to
14466@samp{sqrt @{1+x@}}; this is only an approximation to the true meaning
14467of quotes in @dfn{eqn}, but it is good enough for most uses.
14468
14469Accent codes (@samp{@var{x} dot}) are handled by treating them as
14470function calls (@samp{dot(@var{x})}) internally.
14471@xref{TeX and LaTeX Language Modes}, for a table of these accent
14472functions. The @code{prime} accent is treated specially if it occurs on
14473a variable or function name: @samp{f prime prime @w{( x prime )}} is
14474stored internally as @samp{f'@w{'}(x')}. For example, taking the
14475derivative of @samp{f(2 x)} with @kbd{a d x} will produce @samp{2 f'(2
14476x)}, which @dfn{eqn} mode will display as @samp{2 f prime ( 2 x )}.
14477
14478Assignments are written with the @samp{<-} (left-arrow) symbol,
14479and @code{evalto} operators are written with @samp{->} or
14480@samp{evalto ... ->} (@pxref{TeX and LaTeX Language Modes}, for a discussion
14481of this). The regular Calc symbols @samp{:=} and @samp{=>} are also
14482recognized for these operators during reading.
14483
14484Vectors in @dfn{eqn} mode use regular Calc square brackets, but
14485matrices are formatted as @samp{matrix @{ ccol @{ a above b @} ... @}}.
14486The words @code{lcol} and @code{rcol} are recognized as synonyms
14487for @code{ccol} during input, and are generated instead of @code{ccol}
14488if the matrix justification mode so specifies.
14489
702dbfd9
JB
14490@node Yacas Language Mode, Maxima Language Mode, Eqn Language Mode, Language Modes
14491@subsection Yacas Language Mode
14492
14493@noindent
14494@kindex d Y
14495@pindex calc-yacas-language
14496@cindex Yacas language
14497The @kbd{d Y} (@code{calc-yacas-language}) command selects the
14498conventions of Yacas, a free computer algebra system. While the
14499operators and functions in Yacas are similar to those of Calc, the names
14500of built-in functions in Yacas are capitalized. The Calc formula
14501@samp{sin(2 x)}, for example, is entered and displayed @samp{Sin(2 x)}
14502in Yacas mode, and `@samp{arcsin(x^2)} is @samp{ArcSin(x^2)} in Yacas
14503mode. Complex numbers are written are written @samp{3 + 4 I}.
14504The standard special constants are written @code{Pi}, @code{E},
14505@code{I}, @code{GoldenRatio} and @code{Gamma}. @code{Infinity}
14506represents both @code{inf} and @code{uinf}, and @code{Undefined}
14507represents @code{nan}.
14508
14509Certain operators on functions, such as @code{D} for differentiation
14510and @code{Integrate} for integration, take a prefix form in Yacas. For
14511example, the derivative of @w{@samp{e^x sin(x)}} can be computed with
14512@w{@samp{D(x) Exp(x)*Sin(x)}}.
14513
14514Other notable differences between Yacas and standard Calc expressions
14515are that vectors and matrices use curly braces in Yacas, and subscripts
14516use square brackets. If, for example, @samp{A} represents the list
14517@samp{@{a,2,c,4@}}, then @samp{A[3]} would equal @samp{c}.
14518
14519
14520@node Maxima Language Mode, Giac Language Mode, Yacas Language Mode, Language Modes
14521@subsection Maxima Language Mode
14522
14523@noindent
14524@kindex d X
14525@pindex calc-maxima-language
14526@cindex Maxima language
14527The @kbd{d X} (@code{calc-maxima-language}) command selects the
14528conventions of Maxima, another free computer algebra system. The
14529function names in Maxima are similar, but not always identical, to Calc.
14530For example, instead of @samp{arcsin(x)}, Maxima will use
14531@samp{asin(x)}. Complex numbers are written @samp{3 + 4 %i}. The
14532standard special constants are written @code{%pi}, @code{%e},
14533@code{%i}, @code{%phi} and @code{%gamma}. In Maxima, @code{inf} means
14534the same as in Calc, but @code{infinity} represents Calc's @code{uinf}.
14535
14536Underscores as well as percent signs are allowed in function and
14537variable names in Maxima mode. The underscore again is equivalent to
14538the @samp{#} in Normal mode, and the percent sign is equivalent to
14539@samp{o'o}.
14540
14541Maxima uses square brackets for lists and vectors, and matrices are
14542written as calls to the function @code{matrix}, given the row vectors of
14543the matrix as arguments. Square brackets are also used as subscripts.
14544
14545@node Giac Language Mode, Mathematica Language Mode, Maxima Language Mode, Language Modes
14546@subsection Giac Language Mode
14547
14548@noindent
14549@kindex d A
14550@pindex calc-giac-language
14551@cindex Giac language
14552The @kbd{d A} (@code{calc-giac-language}) command selects the
14553conventions of Giac, another free computer algebra system. The function
14554names in Giac are similar to Maxima. Complex numbers are written
14555@samp{3 + 4 i}. The standard special constants in Giac are the same as
14556in Calc, except that @code{infinity} represents both Calc's @code{inf}
14557and @code{uinf}.
14558
14559Underscores are allowed in function and variable names in Giac mode.
14560Brackets are used for subscripts. In Giac, indexing of lists begins at
145610, instead of 1 as in Calc. So if @samp{A} represents the list
14562@samp{[a,2,c,4]}, then @samp{A[2]} would equal @samp{c}. In general,
14563@samp{A[n]} in Giac mode corresponds to @samp{A_(n+1)} in Normal mode.
14564
14565The Giac interval notation @samp{2 .. 3} has no surrounding brackets;
14566Calc reads @samp{2 .. 3} as the closed interval @samp{[2 .. 3]} and
14567writes any kind of interval as @samp{2 .. 3}. This means you cannot see
14568the difference between an open and a closed interval while in Giac mode.
14569
14570@node Mathematica Language Mode, Maple Language Mode, Giac Language Mode, Language Modes
4009494e
GM
14571@subsection Mathematica Language Mode
14572
14573@noindent
14574@kindex d M
14575@pindex calc-mathematica-language
14576@cindex Mathematica language
14577The @kbd{d M} (@code{calc-mathematica-language}) command selects the
14578conventions of Mathematica. Notable differences in Mathematica mode
14579are that the names of built-in functions are capitalized, and function
14580calls use square brackets instead of parentheses. Thus the Calc
14581formula @samp{sin(2 x)} is entered and displayed @w{@samp{Sin[2 x]}} in
14582Mathematica mode.
14583
14584Vectors and matrices use curly braces in Mathematica. Complex numbers
14585are written @samp{3 + 4 I}. The standard special constants in Calc are
14586written @code{Pi}, @code{E}, @code{I}, @code{GoldenRatio}, @code{EulerGamma},
14587@code{Infinity}, @code{ComplexInfinity}, and @code{Indeterminate} in
14588Mathematica mode.
14589Non-decimal numbers are written, e.g., @samp{16^^7fff}. Floating-point
14590numbers in scientific notation are written @samp{1.23*10.^3}.
14591Subscripts use double square brackets: @samp{a[[i]]}.
14592
14593@node Maple Language Mode, Compositions, Mathematica Language Mode, Language Modes
14594@subsection Maple Language Mode
14595
14596@noindent
14597@kindex d W
14598@pindex calc-maple-language
14599@cindex Maple language
14600The @kbd{d W} (@code{calc-maple-language}) command selects the
14601conventions of Maple.
14602
14603Maple's language is much like C. Underscores are allowed in symbol
14604names; square brackets are used for subscripts; explicit @samp{*}s for
14605multiplications are required. Use either @samp{^} or @samp{**} to
14606denote powers.
14607
14608Maple uses square brackets for lists and curly braces for sets. Calc
14609interprets both notations as vectors, and displays vectors with square
14610brackets. This means Maple sets will be converted to lists when they
14611pass through Calc. As a special case, matrices are written as calls
14612to the function @code{matrix}, given a list of lists as the argument,
14613and can be read in this form or with all-capitals @code{MATRIX}.
14614
702dbfd9
JB
14615The Maple interval notation @samp{2 .. 3} is like Giac's interval
14616notation, and is handled the same by Calc.
4009494e
GM
14617
14618Maple writes complex numbers as @samp{3 + 4*I}. Its special constants
14619are @code{Pi}, @code{E}, @code{I}, and @code{infinity} (all three of
14620@code{inf}, @code{uinf}, and @code{nan} display as @code{infinity}).
14621Floating-point numbers are written @samp{1.23*10.^3}.
14622
14623Among things not currently handled by Calc's Maple mode are the
14624various quote symbols, procedures and functional operators, and
14625inert (@samp{&}) operators.
14626
14627@node Compositions, Syntax Tables, Maple Language Mode, Language Modes
14628@subsection Compositions
14629
14630@noindent
14631@cindex Compositions
14632There are several @dfn{composition functions} which allow you to get
14633displays in a variety of formats similar to those in Big language
14634mode. Most of these functions do not evaluate to anything; they are
14635placeholders which are left in symbolic form by Calc's evaluator but
14636are recognized by Calc's display formatting routines.
14637
14638Two of these, @code{string} and @code{bstring}, are described elsewhere.
14639@xref{Strings}. For example, @samp{string("ABC")} is displayed as
14640@samp{ABC}. When viewed on the stack it will be indistinguishable from
14641the variable @code{ABC}, but internally it will be stored as
14642@samp{string([65, 66, 67])} and can still be manipulated this way; for
14643example, the selection and vector commands @kbd{j 1 v v j u} would
14644select the vector portion of this object and reverse the elements, then
14645deselect to reveal a string whose characters had been reversed.
14646
14647The composition functions do the same thing in all language modes
14648(although their components will of course be formatted in the current
14649language mode). The one exception is Unformatted mode (@kbd{d U}),
14650which does not give the composition functions any special treatment.
14651The functions are discussed here because of their relationship to
14652the language modes.
14653
14654@menu
14655* Composition Basics::
14656* Horizontal Compositions::
14657* Vertical Compositions::
14658* Other Compositions::
14659* Information about Compositions::
14660* User-Defined Compositions::
14661@end menu
14662
14663@node Composition Basics, Horizontal Compositions, Compositions, Compositions
14664@subsubsection Composition Basics
14665
14666@noindent
14667Compositions are generally formed by stacking formulas together
14668horizontally or vertically in various ways. Those formulas are
14669themselves compositions. @TeX{} users will find this analogous
14670to @TeX{}'s ``boxes.'' Each multi-line composition has a
14671@dfn{baseline}; horizontal compositions use the baselines to
14672decide how formulas should be positioned relative to one another.
14673For example, in the Big mode formula
14674
14675@example
14676@group
14677 2
14678 a + b
1467917 + ------
14680 c
14681@end group
14682@end example
14683
14684@noindent
14685the second term of the sum is four lines tall and has line three as
14686its baseline. Thus when the term is combined with 17, line three
14687is placed on the same level as the baseline of 17.
14688
14689@tex
14690\bigskip
14691@end tex
14692
14693Another important composition concept is @dfn{precedence}. This is
14694an integer that represents the binding strength of various operators.
14695For example, @samp{*} has higher precedence (195) than @samp{+} (180),
14696which means that @samp{(a * b) + c} will be formatted without the
14697parentheses, but @samp{a * (b + c)} will keep the parentheses.
14698
14699The operator table used by normal and Big language modes has the
14700following precedences:
14701
14702@example
0edd2970
JB
14703_ 1200 @r{(subscripts)}
14704% 1100 @r{(as in n}%@r{)}
14705! 1000 @r{(as in }!@r{n)}
4009494e
GM
14706mod 400
14707+/- 300
14708!! 210 @r{(as in n}!!@r{)}
14709! 210 @r{(as in n}!@r{)}
14710^ 200
0edd2970 14711- 197 @r{(as in }-@r{n)}
4009494e
GM
14712* 195 @r{(or implicit multiplication)}
14713/ % \ 190
14714+ - 180 @r{(as in a}+@r{b)}
14715| 170
14716< = 160 @r{(and other relations)}
14717&& 110
14718|| 100
14719? : 90
14720!!! 85
14721&&& 80
14722||| 75
14723:= 50
14724:: 45
14725=> 40
14726@end example
14727
14728The general rule is that if an operator with precedence @expr{n}
14729occurs as an argument to an operator with precedence @expr{m}, then
14730the argument is enclosed in parentheses if @expr{n < m}. Top-level
14731expressions and expressions which are function arguments, vector
14732components, etc., are formatted with precedence zero (so that they
14733normally never get additional parentheses).
14734
14735For binary left-associative operators like @samp{+}, the righthand
14736argument is actually formatted with one-higher precedence than shown
14737in the table. This makes sure @samp{(a + b) + c} omits the parentheses,
14738but the unnatural form @samp{a + (b + c)} keeps its parentheses.
14739Right-associative operators like @samp{^} format the lefthand argument
14740with one-higher precedence.
14741
14742@ignore
14743@starindex
14744@end ignore
14745@tindex cprec
14746The @code{cprec} function formats an expression with an arbitrary
14747precedence. For example, @samp{cprec(abc, 185)} will combine into
14748sums and products as follows: @samp{7 + abc}, @samp{7 (abc)} (because
14749this @code{cprec} form has higher precedence than addition, but lower
14750precedence than multiplication).
14751
14752@tex
14753\bigskip
14754@end tex
14755
14756A final composition issue is @dfn{line breaking}. Calc uses two
14757different strategies for ``flat'' and ``non-flat'' compositions.
14758A non-flat composition is anything that appears on multiple lines
14759(not counting line breaking). Examples would be matrices and Big
14760mode powers and quotients. Non-flat compositions are displayed
14761exactly as specified. If they come out wider than the current
14762window, you must use horizontal scrolling (@kbd{<} and @kbd{>}) to
14763view them.
14764
14765Flat compositions, on the other hand, will be broken across several
14766lines if they are too wide to fit the window. Certain points in a
14767composition are noted internally as @dfn{break points}. Calc's
14768general strategy is to fill each line as much as possible, then to
14769move down to the next line starting at the first break point that
14770didn't fit. However, the line breaker understands the hierarchical
14771structure of formulas. It will not break an ``inner'' formula if
14772it can use an earlier break point from an ``outer'' formula instead.
14773For example, a vector of sums might be formatted as:
14774
14775@example
14776@group
14777[ a + b + c, d + e + f,
14778 g + h + i, j + k + l, m ]
14779@end group
14780@end example
14781
14782@noindent
14783If the @samp{m} can fit, then so, it seems, could the @samp{g}.
14784But Calc prefers to break at the comma since the comma is part
14785of a ``more outer'' formula. Calc would break at a plus sign
14786only if it had to, say, if the very first sum in the vector had
14787itself been too large to fit.
14788
14789Of the composition functions described below, only @code{choriz}
14790generates break points. The @code{bstring} function (@pxref{Strings})
14791also generates breakable items: A break point is added after every
14792space (or group of spaces) except for spaces at the very beginning or
14793end of the string.
14794
14795Composition functions themselves count as levels in the formula
14796hierarchy, so a @code{choriz} that is a component of a larger
14797@code{choriz} will be less likely to be broken. As a special case,
14798if a @code{bstring} occurs as a component of a @code{choriz} or
14799@code{choriz}-like object (such as a vector or a list of arguments
14800in a function call), then the break points in that @code{bstring}
14801will be on the same level as the break points of the surrounding
14802object.
14803
14804@node Horizontal Compositions, Vertical Compositions, Composition Basics, Compositions
14805@subsubsection Horizontal Compositions
14806
14807@noindent
14808@ignore
14809@starindex
14810@end ignore
14811@tindex choriz
14812The @code{choriz} function takes a vector of objects and composes
14813them horizontally. For example, @samp{choriz([17, a b/c, d])} formats
14814as @w{@samp{17a b / cd}} in Normal language mode, or as
14815
14816@example
14817@group
14818 a b
1481917---d
14820 c
14821@end group
14822@end example
14823
14824@noindent
14825in Big language mode. This is actually one case of the general
14826function @samp{choriz(@var{vec}, @var{sep}, @var{prec})}, where
14827either or both of @var{sep} and @var{prec} may be omitted.
14828@var{Prec} gives the @dfn{precedence} to use when formatting
14829each of the components of @var{vec}. The default precedence is
14830the precedence from the surrounding environment.
14831
14832@var{Sep} is a string (i.e., a vector of character codes as might
14833be entered with @code{" "} notation) which should separate components
14834of the composition. Also, if @var{sep} is given, the line breaker
14835will allow lines to be broken after each occurrence of @var{sep}.
14836If @var{sep} is omitted, the composition will not be breakable
14837(unless any of its component compositions are breakable).
14838
14839For example, @samp{2 choriz([a, b c, d = e], " + ", 180)} is
14840formatted as @samp{2 a + b c + (d = e)}. To get the @code{choriz}
14841to have precedence 180 ``outwards'' as well as ``inwards,''
14842enclose it in a @code{cprec} form: @samp{2 cprec(choriz(...), 180)}
14843formats as @samp{2 (a + b c + (d = e))}.
14844
14845The baseline of a horizontal composition is the same as the
14846baselines of the component compositions, which are all aligned.
14847
14848@node Vertical Compositions, Other Compositions, Horizontal Compositions, Compositions
14849@subsubsection Vertical Compositions
14850
14851@noindent
14852@ignore
14853@starindex
14854@end ignore
14855@tindex cvert
14856The @code{cvert} function makes a vertical composition. Each
14857component of the vector is centered in a column. The baseline of
14858the result is by default the top line of the resulting composition.
14859For example, @samp{f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))}
14860formats in Big mode as
14861
14862@example
14863@group
14864f( a , 2 )
14865 bb a + 1
14866 ccc 2
14867 b
14868@end group
14869@end example
14870
14871@ignore
14872@starindex
14873@end ignore
14874@tindex cbase
14875There are several special composition functions that work only as
14876components of a vertical composition. The @code{cbase} function
14877controls the baseline of the vertical composition; the baseline
14878will be the same as the baseline of whatever component is enclosed
14879in @code{cbase}. Thus @samp{f(cvert([a, cbase(bb), ccc]),
14880cvert([a^2 + 1, cbase(b^2)]))} displays as
14881
14882@example
14883@group
14884 2
14885 a + 1
14886 a 2
14887f(bb , b )
14888 ccc
14889@end group
14890@end example
14891
14892@ignore
14893@starindex
14894@end ignore
14895@tindex ctbase
14896@ignore
14897@starindex
14898@end ignore
14899@tindex cbbase
14900There are also @code{ctbase} and @code{cbbase} functions which
14901make the baseline of the vertical composition equal to the top
14902or bottom line (rather than the baseline) of that component.
14903Thus @samp{cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
14904cvert([cbbase(a / b)])} gives
14905
14906@example
14907@group
14908 a
14909a -
14910- + a + b
14911b -
14912 b
14913@end group
14914@end example
14915
14916There should be only one @code{cbase}, @code{ctbase}, or @code{cbbase}
14917function in a given vertical composition. These functions can also
14918be written with no arguments: @samp{ctbase()} is a zero-height object
14919which means the baseline is the top line of the following item, and
14920@samp{cbbase()} means the baseline is the bottom line of the preceding
14921item.
14922
14923@ignore
14924@starindex
14925@end ignore
14926@tindex crule
14927The @code{crule} function builds a ``rule,'' or horizontal line,
14928across a vertical composition. By itself @samp{crule()} uses @samp{-}
14929characters to build the rule. You can specify any other character,
14930e.g., @samp{crule("=")}. The argument must be a character code or
14931vector of exactly one character code. It is repeated to match the
14932width of the widest item in the stack. For example, a quotient
14933with a thick line is @samp{cvert([a + 1, cbase(crule("=")), b^2])}:
14934
14935@example
14936@group
14937a + 1
14938=====
14939 2
14940 b
14941@end group
14942@end example
14943
14944@ignore
14945@starindex
14946@end ignore
14947@tindex clvert
14948@ignore
14949@starindex
14950@end ignore
14951@tindex crvert
14952Finally, the functions @code{clvert} and @code{crvert} act exactly
14953like @code{cvert} except that the items are left- or right-justified
14954in the stack. Thus @samp{clvert([a, bb, ccc]) + crvert([a, bb, ccc])}
14955gives:
14956
14957@example
14958@group
14959a + a
14960bb bb
14961ccc ccc
14962@end group
14963@end example
14964
14965Like @code{choriz}, the vertical compositions accept a second argument
14966which gives the precedence to use when formatting the components.
14967Vertical compositions do not support separator strings.
14968
14969@node Other Compositions, Information about Compositions, Vertical Compositions, Compositions
14970@subsubsection Other Compositions
14971
14972@noindent
14973@ignore
14974@starindex
14975@end ignore
14976@tindex csup
14977The @code{csup} function builds a superscripted expression. For
14978example, @samp{csup(a, b)} looks the same as @samp{a^b} does in Big
14979language mode. This is essentially a horizontal composition of
14980@samp{a} and @samp{b}, where @samp{b} is shifted up so that its
14981bottom line is one above the baseline.
14982
14983@ignore
14984@starindex
14985@end ignore
14986@tindex csub
14987Likewise, the @code{csub} function builds a subscripted expression.
14988This shifts @samp{b} down so that its top line is one below the
14989bottom line of @samp{a} (note that this is not quite analogous to
14990@code{csup}). Other arrangements can be obtained by using
14991@code{choriz} and @code{cvert} directly.
14992
14993@ignore
14994@starindex
14995@end ignore
14996@tindex cflat
14997The @code{cflat} function formats its argument in ``flat'' mode,
14998as obtained by @samp{d O}, if the current language mode is normal
14999or Big. It has no effect in other language modes. For example,
15000@samp{a^(b/c)} is formatted by Big mode like @samp{csup(a, cflat(b/c))}
15001to improve its readability.
15002
15003@ignore
15004@starindex
15005@end ignore
15006@tindex cspace
15007The @code{cspace} function creates horizontal space. For example,
15008@samp{cspace(4)} is effectively the same as @samp{string(" ")}.
15009A second string (i.e., vector of characters) argument is repeated
15010instead of the space character. For example, @samp{cspace(4, "ab")}
15011looks like @samp{abababab}. If the second argument is not a string,
15012it is formatted in the normal way and then several copies of that
15013are composed together: @samp{cspace(4, a^2)} yields
15014
15015@example
15016@group
15017 2 2 2 2
15018a a a a
15019@end group
15020@end example
15021
15022@noindent
15023If the number argument is zero, this is a zero-width object.
15024
15025@ignore
15026@starindex
15027@end ignore
15028@tindex cvspace
15029The @code{cvspace} function creates vertical space, or a vertical
15030stack of copies of a certain string or formatted object. The
15031baseline is the center line of the resulting stack. A numerical
15032argument of zero will produce an object which contributes zero
15033height if used in a vertical composition.
15034
15035@ignore
15036@starindex
15037@end ignore
15038@tindex ctspace
15039@ignore
15040@starindex
15041@end ignore
15042@tindex cbspace
15043There are also @code{ctspace} and @code{cbspace} functions which
15044create vertical space with the baseline the same as the baseline
15045of the top or bottom copy, respectively, of the second argument.
15046Thus @samp{cvspace(2, a/b) + ctspace(2, a/b) + cbspace(2, a/b)}
15047displays as:
15048
15049@example
15050@group
15051 a
15052 -
15053a b
15054- a a
15055b + - + -
15056a b b
15057- a
15058b -
15059 b
15060@end group
15061@end example
15062
15063@node Information about Compositions, User-Defined Compositions, Other Compositions, Compositions
15064@subsubsection Information about Compositions
15065
15066@noindent
15067The functions in this section are actual functions; they compose their
15068arguments according to the current language and other display modes,
15069then return a certain measurement of the composition as an integer.
15070
15071@ignore
15072@starindex
15073@end ignore
15074@tindex cwidth
15075The @code{cwidth} function measures the width, in characters, of a
15076composition. For example, @samp{cwidth(a + b)} is 5, and
15077@samp{cwidth(a / b)} is 5 in Normal mode, 1 in Big mode, and 11 in
15078@TeX{} mode (for @samp{@{a \over b@}}). The argument may involve
15079the composition functions described in this section.
15080
15081@ignore
15082@starindex
15083@end ignore
15084@tindex cheight
15085The @code{cheight} function measures the height of a composition.
15086This is the total number of lines in the argument's printed form.
15087
15088@ignore
15089@starindex
15090@end ignore
15091@tindex cascent
15092@ignore
15093@starindex
15094@end ignore
15095@tindex cdescent
15096The functions @code{cascent} and @code{cdescent} measure the amount
15097of the height that is above (and including) the baseline, or below
15098the baseline, respectively. Thus @samp{cascent(@var{x}) + cdescent(@var{x})}
15099always equals @samp{cheight(@var{x})}. For a one-line formula like
15100@samp{a + b}, @code{cascent} returns 1 and @code{cdescent} returns 0.
15101For @samp{a / b} in Big mode, @code{cascent} returns 2 and @code{cdescent}
15102returns 1. The only formula for which @code{cascent} will return zero
15103is @samp{cvspace(0)} or equivalents.
15104
15105@node User-Defined Compositions, , Information about Compositions, Compositions
15106@subsubsection User-Defined Compositions
15107
15108@noindent
15109@kindex Z C
15110@pindex calc-user-define-composition
15111The @kbd{Z C} (@code{calc-user-define-composition}) command lets you
15112define the display format for any algebraic function. You provide a
15113formula containing a certain number of argument variables on the stack.
15114Any time Calc formats a call to the specified function in the current
15115language mode and with that number of arguments, Calc effectively
15116replaces the function call with that formula with the arguments
15117replaced.
15118
15119Calc builds the default argument list by sorting all the variable names
15120that appear in the formula into alphabetical order. You can edit this
15121argument list before pressing @key{RET} if you wish. Any variables in
15122the formula that do not appear in the argument list will be displayed
15123literally; any arguments that do not appear in the formula will not
15124affect the display at all.
15125
15126You can define formats for built-in functions, for functions you have
15127defined with @kbd{Z F} (@pxref{Algebraic Definitions}), or for functions
15128which have no definitions but are being used as purely syntactic objects.
15129You can define different formats for each language mode, and for each
15130number of arguments, using a succession of @kbd{Z C} commands. When
15131Calc formats a function call, it first searches for a format defined
15132for the current language mode (and number of arguments); if there is
15133none, it uses the format defined for the Normal language mode. If
15134neither format exists, Calc uses its built-in standard format for that
15135function (usually just @samp{@var{func}(@var{args})}).
15136
15137If you execute @kbd{Z C} with the number 0 on the stack instead of a
15138formula, any defined formats for the function in the current language
15139mode will be removed. The function will revert to its standard format.
15140
15141For example, the default format for the binomial coefficient function
15142@samp{choose(n, m)} in the Big language mode is
15143
15144@example
15145@group
15146 n
15147( )
15148 m
15149@end group
15150@end example
15151
15152@noindent
15153You might prefer the notation,
15154
15155@example
15156@group
15157 C
15158n m
15159@end group
15160@end example
15161
15162@noindent
15163To define this notation, first make sure you are in Big mode,
15164then put the formula
15165
15166@smallexample
15167choriz([cvert([cvspace(1), n]), C, cvert([cvspace(1), m])])
15168@end smallexample
15169
15170@noindent
15171on the stack and type @kbd{Z C}. Answer the first prompt with
15172@code{choose}. The second prompt will be the default argument list
15173of @samp{(C m n)}. Edit this list to be @samp{(n m)} and press
15174@key{RET}. Now, try it out: For example, turn simplification
15175off with @kbd{m O} and enter @samp{choose(a,b) + choose(7,3)}
15176as an algebraic entry.
15177
15178@example
15179@group
15180 C + C
15181a b 7 3
15182@end group
15183@end example
15184
15185As another example, let's define the usual notation for Stirling
15186numbers of the first kind, @samp{stir1(n, m)}. This is just like
15187the regular format for binomial coefficients but with square brackets
15188instead of parentheses.
15189
15190@smallexample
15191choriz([string("["), cvert([n, cbase(cvspace(1)), m]), string("]")])
15192@end smallexample
15193
15194Now type @kbd{Z C stir1 @key{RET}}, edit the argument list to
15195@samp{(n m)}, and type @key{RET}.
15196
15197The formula provided to @kbd{Z C} usually will involve composition
15198functions, but it doesn't have to. Putting the formula @samp{a + b + c}
15199onto the stack and typing @kbd{Z C foo @key{RET} @key{RET}} would define
15200the function @samp{foo(x,y,z)} to display like @samp{x + y + z}.
15201This ``sum'' will act exactly like a real sum for all formatting
15202purposes (it will be parenthesized the same, and so on). However
15203it will be computationally unrelated to a sum. For example, the
15204formula @samp{2 * foo(1, 2, 3)} will display as @samp{2 (1 + 2 + 3)}.
15205Operator precedences have caused the ``sum'' to be written in
15206parentheses, but the arguments have not actually been summed.
15207(Generally a display format like this would be undesirable, since
15208it can easily be confused with a real sum.)
15209
15210The special function @code{eval} can be used inside a @kbd{Z C}
15211composition formula to cause all or part of the formula to be
15212evaluated at display time. For example, if the formula is
15213@samp{a + eval(b + c)}, then @samp{foo(1, 2, 3)} will be displayed
15214as @samp{1 + 5}. Evaluation will use the default simplifications,
15215regardless of the current simplification mode. There are also
15216@code{evalsimp} and @code{evalextsimp} which simplify as if by
15217@kbd{a s} and @kbd{a e} (respectively). Note that these ``functions''
15218operate only in the context of composition formulas (and also in
15219rewrite rules, where they serve a similar purpose; @pxref{Rewrite
15220Rules}). On the stack, a call to @code{eval} will be left in
15221symbolic form.
15222
15223It is not a good idea to use @code{eval} except as a last resort.
15224It can cause the display of formulas to be extremely slow. For
15225example, while @samp{eval(a + b)} might seem quite fast and simple,
15226there are several situations where it could be slow. For example,
15227@samp{a} and/or @samp{b} could be polar complex numbers, in which
15228case doing the sum requires trigonometry. Or, @samp{a} could be
15229the factorial @samp{fact(100)} which is unevaluated because you
15230have typed @kbd{m O}; @code{eval} will evaluate it anyway to
15231produce a large, unwieldy integer.
15232
15233You can save your display formats permanently using the @kbd{Z P}
15234command (@pxref{Creating User Keys}).
15235
15236@node Syntax Tables, , Compositions, Language Modes
15237@subsection Syntax Tables
15238
15239@noindent
15240@cindex Syntax tables
15241@cindex Parsing formulas, customized
15242Syntax tables do for input what compositions do for output: They
15243allow you to teach custom notations to Calc's formula parser.
15244Calc keeps a separate syntax table for each language mode.
15245
15246(Note that the Calc ``syntax tables'' discussed here are completely
15247unrelated to the syntax tables described in the Emacs manual.)
15248
15249@kindex Z S
15250@pindex calc-edit-user-syntax
15251The @kbd{Z S} (@code{calc-edit-user-syntax}) command edits the
15252syntax table for the current language mode. If you want your
15253syntax to work in any language, define it in the Normal language
15254mode. Type @kbd{C-c C-c} to finish editing the syntax table, or
15255@kbd{C-x k} to cancel the edit. The @kbd{m m} command saves all
15256the syntax tables along with the other mode settings;
15257@pxref{General Mode Commands}.
15258
15259@menu
15260* Syntax Table Basics::
15261* Precedence in Syntax Tables::
15262* Advanced Syntax Patterns::
15263* Conditional Syntax Rules::
15264@end menu
15265
15266@node Syntax Table Basics, Precedence in Syntax Tables, Syntax Tables, Syntax Tables
15267@subsubsection Syntax Table Basics
15268
15269@noindent
15270@dfn{Parsing} is the process of converting a raw string of characters,
15271such as you would type in during algebraic entry, into a Calc formula.
15272Calc's parser works in two stages. First, the input is broken down
15273into @dfn{tokens}, such as words, numbers, and punctuation symbols
15274like @samp{+}, @samp{:=}, and @samp{+/-}. Space between tokens is
15275ignored (except when it serves to separate adjacent words). Next,
15276the parser matches this string of tokens against various built-in
15277syntactic patterns, such as ``an expression followed by @samp{+}
15278followed by another expression'' or ``a name followed by @samp{(},
15279zero or more expressions separated by commas, and @samp{)}.''
15280
15281A @dfn{syntax table} is a list of user-defined @dfn{syntax rules},
15282which allow you to specify new patterns to define your own
15283favorite input notations. Calc's parser always checks the syntax
15284table for the current language mode, then the table for the Normal
15285language mode, before it uses its built-in rules to parse an
15286algebraic formula you have entered. Each syntax rule should go on
15287its own line; it consists of a @dfn{pattern}, a @samp{:=} symbol,
15288and a Calc formula with an optional @dfn{condition}. (Syntax rules
15289resemble algebraic rewrite rules, but the notation for patterns is
15290completely different.)
15291
15292A syntax pattern is a list of tokens, separated by spaces.
15293Except for a few special symbols, tokens in syntax patterns are
15294matched literally, from left to right. For example, the rule,
15295
15296@example
15297foo ( ) := 2+3
15298@end example
15299
15300@noindent
15301would cause Calc to parse the formula @samp{4+foo()*5} as if it
15302were @samp{4+(2+3)*5}. Notice that the parentheses were written
15303as two separate tokens in the rule. As a result, the rule works
15304for both @samp{foo()} and @w{@samp{foo ( )}}. If we had written
15305the rule as @samp{foo () := 2+3}, then Calc would treat @samp{()}
15306as a single, indivisible token, so that @w{@samp{foo( )}} would
15307not be recognized by the rule. (It would be parsed as a regular
15308zero-argument function call instead.) In fact, this rule would
15309also make trouble for the rest of Calc's parser: An unrelated
15310formula like @samp{bar()} would now be tokenized into @samp{bar ()}
15311instead of @samp{bar ( )}, so that the standard parser for function
15312calls would no longer recognize it!
15313
15314While it is possible to make a token with a mixture of letters
15315and punctuation symbols, this is not recommended. It is better to
15316break it into several tokens, as we did with @samp{foo()} above.
15317
15318The symbol @samp{#} in a syntax pattern matches any Calc expression.
15319On the righthand side, the things that matched the @samp{#}s can
15320be referred to as @samp{#1}, @samp{#2}, and so on (where @samp{#1}
15321matches the leftmost @samp{#} in the pattern). For example, these
15322rules match a user-defined function, prefix operator, infix operator,
15323and postfix operator, respectively:
15324
15325@example
15326foo ( # ) := myfunc(#1)
15327foo # := myprefix(#1)
15328# foo # := myinfix(#1,#2)
15329# foo := mypostfix(#1)
15330@end example
15331
15332Thus @samp{foo(3)} will parse as @samp{myfunc(3)}, and @samp{2+3 foo}
15333will parse as @samp{mypostfix(2+3)}.
15334
15335It is important to write the first two rules in the order shown,
15336because Calc tries rules in order from first to last. If the
15337pattern @samp{foo #} came first, it would match anything that could
15338match the @samp{foo ( # )} rule, since an expression in parentheses
15339is itself a valid expression. Thus the @w{@samp{foo ( # )}} rule would
15340never get to match anything. Likewise, the last two rules must be
15341written in the order shown or else @samp{3 foo 4} will be parsed as
15342@samp{mypostfix(3) * 4}. (Of course, the best way to avoid these
15343ambiguities is not to use the same symbol in more than one way at
15344the same time! In case you're not convinced, try the following
15345exercise: How will the above rules parse the input @samp{foo(3,4)},
15346if at all? Work it out for yourself, then try it in Calc and see.)
15347
15348Calc is quite flexible about what sorts of patterns are allowed.
15349The only rule is that every pattern must begin with a literal
15350token (like @samp{foo} in the first two patterns above), or with
15351a @samp{#} followed by a literal token (as in the last two
15352patterns). After that, any mixture is allowed, although putting
15353two @samp{#}s in a row will not be very useful since two
15354expressions with nothing between them will be parsed as one
15355expression that uses implicit multiplication.
15356
15357As a more practical example, Maple uses the notation
15358@samp{sum(a(i), i=1..10)} for sums, which Calc's Maple mode doesn't
15359recognize at present. To handle this syntax, we simply add the
15360rule,
15361
15362@example
15363sum ( # , # = # .. # ) := sum(#1,#2,#3,#4)
15364@end example
15365
15366@noindent
15367to the Maple mode syntax table. As another example, C mode can't
15368read assignment operators like @samp{++} and @samp{*=}. We can
15369define these operators quite easily:
15370
15371@example
15372# *= # := muleq(#1,#2)
15373# ++ := postinc(#1)
15374++ # := preinc(#1)
15375@end example
15376
15377@noindent
15378To complete the job, we would use corresponding composition functions
15379and @kbd{Z C} to cause these functions to display in their respective
15380Maple and C notations. (Note that the C example ignores issues of
15381operator precedence, which are discussed in the next section.)
15382
15383You can enclose any token in quotes to prevent its usual
15384interpretation in syntax patterns:
15385
15386@example
15387# ":=" # := becomes(#1,#2)
15388@end example
15389
15390Quotes also allow you to include spaces in a token, although once
15391again it is generally better to use two tokens than one token with
15392an embedded space. To include an actual quotation mark in a quoted
15393token, precede it with a backslash. (This also works to include
15394backslashes in tokens.)
15395
15396@example
15397# "bad token" # "/\"\\" # := silly(#1,#2,#3)
15398@end example
15399
15400@noindent
15401This will parse @samp{3 bad token 4 /"\ 5} to @samp{silly(3,4,5)}.
15402
15403The token @kbd{#} has a predefined meaning in Calc's formula parser;
15404it is not valid to use @samp{"#"} in a syntax rule. However, longer
15405tokens that include the @samp{#} character are allowed. Also, while
15406@samp{"$"} and @samp{"\""} are allowed as tokens, their presence in
15407the syntax table will prevent those characters from working in their
15408usual ways (referring to stack entries and quoting strings,
15409respectively).
15410
15411Finally, the notation @samp{%%} anywhere in a syntax table causes
15412the rest of the line to be ignored as a comment.
15413
15414@node Precedence in Syntax Tables, Advanced Syntax Patterns, Syntax Table Basics, Syntax Tables
15415@subsubsection Precedence
15416
15417@noindent
15418Different operators are generally assigned different @dfn{precedences}.
15419By default, an operator defined by a rule like
15420
15421@example
15422# foo # := foo(#1,#2)
15423@end example
15424
15425@noindent
15426will have an extremely low precedence, so that @samp{2*3+4 foo 5 == 6}
15427will be parsed as @samp{(2*3+4) foo (5 == 6)}. To change the
15428precedence of an operator, use the notation @samp{#/@var{p}} in
15429place of @samp{#}, where @var{p} is an integer precedence level.
15430For example, 185 lies between the precedences for @samp{+} and
15431@samp{*}, so if we change this rule to
15432
15433@example
15434#/185 foo #/186 := foo(#1,#2)
15435@end example
15436
15437@noindent
15438then @samp{2+3 foo 4*5} will be parsed as @samp{2+(3 foo (4*5))}.
15439Also, because we've given the righthand expression slightly higher
15440precedence, our new operator will be left-associative:
15441@samp{1 foo 2 foo 3} will be parsed as @samp{(1 foo 2) foo 3}.
15442By raising the precedence of the lefthand expression instead, we
15443can create a right-associative operator.
15444
15445@xref{Composition Basics}, for a table of precedences of the
15446standard Calc operators. For the precedences of operators in other
15447language modes, look in the Calc source file @file{calc-lang.el}.
15448
15449@node Advanced Syntax Patterns, Conditional Syntax Rules, Precedence in Syntax Tables, Syntax Tables
15450@subsubsection Advanced Syntax Patterns
15451
15452@noindent
15453To match a function with a variable number of arguments, you could
15454write
15455
15456@example
15457foo ( # ) := myfunc(#1)
15458foo ( # , # ) := myfunc(#1,#2)
15459foo ( # , # , # ) := myfunc(#1,#2,#3)
15460@end example
15461
15462@noindent
15463but this isn't very elegant. To match variable numbers of items,
15464Calc uses some notations inspired regular expressions and the
15465``extended BNF'' style used by some language designers.
15466
15467@example
15468foo ( @{ # @}*, ) := apply(myfunc,#1)
15469@end example
15470
15471The token @samp{@{} introduces a repeated or optional portion.
15472One of the three tokens @samp{@}*}, @samp{@}+}, or @samp{@}?}
15473ends the portion. These will match zero or more, one or more,
15474or zero or one copies of the enclosed pattern, respectively.
15475In addition, @samp{@}*} and @samp{@}+} can be followed by a
15476separator token (with no space in between, as shown above).
15477Thus @samp{@{ # @}*,} matches nothing, or one expression, or
15478several expressions separated by commas.
15479
15480A complete @samp{@{ ... @}} item matches as a vector of the
15481items that matched inside it. For example, the above rule will
15482match @samp{foo(1,2,3)} to get @samp{apply(myfunc,[1,2,3])}.
15483The Calc @code{apply} function takes a function name and a vector
15484of arguments and builds a call to the function with those
15485arguments, so the net result is the formula @samp{myfunc(1,2,3)}.
15486
15487If the body of a @samp{@{ ... @}} contains several @samp{#}s
15488(or nested @samp{@{ ... @}} constructs), then the items will be
15489strung together into the resulting vector. If the body
15490does not contain anything but literal tokens, the result will
15491always be an empty vector.
15492
15493@example
15494foo ( @{ # , # @}+, ) := bar(#1)
15495foo ( @{ @{ # @}*, @}*; ) := matrix(#1)
15496@end example
15497
15498@noindent
15499will parse @samp{foo(1, 2, 3, 4)} as @samp{bar([1, 2, 3, 4])}, and
15500@samp{foo(1, 2; 3, 4)} as @samp{matrix([[1, 2], [3, 4]])}. Also, after
15501some thought it's easy to see how this pair of rules will parse
15502@samp{foo(1, 2, 3)} as @samp{matrix([[1, 2, 3]])}, since the first
15503rule will only match an even number of arguments. The rule
15504
15505@example
15506foo ( # @{ , # , # @}? ) := bar(#1,#2)
15507@end example
15508
15509@noindent
15510will parse @samp{foo(2,3,4)} as @samp{bar(2,[3,4])}, and
15511@samp{foo(2)} as @samp{bar(2,[])}.
15512
15513The notation @samp{@{ ... @}?.} (note the trailing period) works
15514just the same as regular @samp{@{ ... @}?}, except that it does not
15515count as an argument; the following two rules are equivalent:
15516
15517@example
15518foo ( # , @{ also @}? # ) := bar(#1,#3)
15519foo ( # , @{ also @}?. # ) := bar(#1,#2)
15520@end example
15521
15522@noindent
15523Note that in the first case the optional text counts as @samp{#2},
15524which will always be an empty vector, but in the second case no
15525empty vector is produced.
15526
15527Another variant is @samp{@{ ... @}?$}, which means the body is
15528optional only at the end of the input formula. All built-in syntax
15529rules in Calc use this for closing delimiters, so that during
15530algebraic entry you can type @kbd{[sqrt(2), sqrt(3 @key{RET}}, omitting
15531the closing parenthesis and bracket. Calc does this automatically
15532for trailing @samp{)}, @samp{]}, and @samp{>} tokens in syntax
15533rules, but you can use @samp{@{ ... @}?$} explicitly to get
15534this effect with any token (such as @samp{"@}"} or @samp{end}).
15535Like @samp{@{ ... @}?.}, this notation does not count as an
15536argument. Conversely, you can use quotes, as in @samp{")"}, to
15537prevent a closing-delimiter token from being automatically treated
15538as optional.
15539
15540Calc's parser does not have full backtracking, which means some
15541patterns will not work as you might expect:
15542
15543@example
15544foo ( @{ # , @}? # , # ) := bar(#1,#2,#3)
15545@end example
15546
15547@noindent
15548Here we are trying to make the first argument optional, so that
15549@samp{foo(2,3)} parses as @samp{bar([],2,3)}. Unfortunately, Calc
15550first tries to match @samp{2,} against the optional part of the
15551pattern, finds a match, and so goes ahead to match the rest of the
15552pattern. Later on it will fail to match the second comma, but it
15553doesn't know how to go back and try the other alternative at that
15554point. One way to get around this would be to use two rules:
15555
15556@example
15557foo ( # , # , # ) := bar([#1],#2,#3)
15558foo ( # , # ) := bar([],#1,#2)
15559@end example
15560
15561More precisely, when Calc wants to match an optional or repeated
15562part of a pattern, it scans forward attempting to match that part.
15563If it reaches the end of the optional part without failing, it
15564``finalizes'' its choice and proceeds. If it fails, though, it
15565backs up and tries the other alternative. Thus Calc has ``partial''
15566backtracking. A fully backtracking parser would go on to make sure
15567the rest of the pattern matched before finalizing the choice.
15568
15569@node Conditional Syntax Rules, , Advanced Syntax Patterns, Syntax Tables
15570@subsubsection Conditional Syntax Rules
15571
15572@noindent
15573It is possible to attach a @dfn{condition} to a syntax rule. For
15574example, the rules
15575
15576@example
15577foo ( # ) := ifoo(#1) :: integer(#1)
15578foo ( # ) := gfoo(#1)
15579@end example
15580
15581@noindent
15582will parse @samp{foo(3)} as @samp{ifoo(3)}, but will parse
15583@samp{foo(3.5)} and @samp{foo(x)} as calls to @code{gfoo}. Any
15584number of conditions may be attached; all must be true for the
15585rule to succeed. A condition is ``true'' if it evaluates to a
15586nonzero number. @xref{Logical Operations}, for a list of Calc
15587functions like @code{integer} that perform logical tests.
15588
15589The exact sequence of events is as follows: When Calc tries a
15590rule, it first matches the pattern as usual. It then substitutes
15591@samp{#1}, @samp{#2}, etc., in the conditions, if any. Next, the
15592conditions are simplified and evaluated in order from left to right,
15593as if by the @w{@kbd{a s}} algebra command (@pxref{Simplifying Formulas}).
15594Each result is true if it is a nonzero number, or an expression
15595that can be proven to be nonzero (@pxref{Declarations}). If the
15596results of all conditions are true, the expression (such as
15597@samp{ifoo(#1)}) has its @samp{#}s substituted, and that is the
15598result of the parse. If the result of any condition is false, Calc
15599goes on to try the next rule in the syntax table.
15600
15601Syntax rules also support @code{let} conditions, which operate in
15602exactly the same way as they do in algebraic rewrite rules.
15603@xref{Other Features of Rewrite Rules}, for details. A @code{let}
15604condition is always true, but as a side effect it defines a
15605variable which can be used in later conditions, and also in the
15606expression after the @samp{:=} sign:
15607
15608@example
15609foo ( # ) := hifoo(x) :: let(x := #1 + 0.5) :: dnumint(x)
15610@end example
15611
15612@noindent
15613The @code{dnumint} function tests if a value is numerically an
15614integer, i.e., either a true integer or an integer-valued float.
15615This rule will parse @code{foo} with a half-integer argument,
15616like @samp{foo(3.5)}, to a call like @samp{hifoo(4.)}.
15617
15618The lefthand side of a syntax rule @code{let} must be a simple
15619variable, not the arbitrary pattern that is allowed in rewrite
15620rules.
15621
15622The @code{matches} function is also treated specially in syntax
15623rule conditions (again, in the same way as in rewrite rules).
15624@xref{Matching Commands}. If the matching pattern contains
15625meta-variables, then those meta-variables may be used in later
15626conditions and in the result expression. The arguments to
15627@code{matches} are not evaluated in this situation.
15628
15629@example
15630sum ( # , # ) := sum(#1,a,b,c) :: matches(#2, a=[b..c])
15631@end example
15632
15633@noindent
15634This is another way to implement the Maple mode @code{sum} notation.
15635In this approach, we allow @samp{#2} to equal the whole expression
15636@samp{i=1..10}. Then, we use @code{matches} to break it apart into
15637its components. If the expression turns out not to match the pattern,
15638the syntax rule will fail. Note that @kbd{Z S} always uses Calc's
15639Normal language mode for editing expressions in syntax rules, so we
15640must use regular Calc notation for the interval @samp{[b..c]} that
15641will correspond to the Maple mode interval @samp{1..10}.
15642
15643@node Modes Variable, Calc Mode Line, Language Modes, Mode Settings
15644@section The @code{Modes} Variable
15645
15646@noindent
15647@kindex m g
15648@pindex calc-get-modes
15649The @kbd{m g} (@code{calc-get-modes}) command pushes onto the stack
15650a vector of numbers that describes the various mode settings that
15651are in effect. With a numeric prefix argument, it pushes only the
15652@var{n}th mode, i.e., the @var{n}th element of this vector. Keyboard
15653macros can use the @kbd{m g} command to modify their behavior based
15654on the current mode settings.
15655
15656@cindex @code{Modes} variable
15657@vindex Modes
15658The modes vector is also available in the special variable
15659@code{Modes}. In other words, @kbd{m g} is like @kbd{s r Modes @key{RET}}.
15660It will not work to store into this variable; in fact, if you do,
15661@code{Modes} will cease to track the current modes. (The @kbd{m g}
15662command will continue to work, however.)
15663
15664In general, each number in this vector is suitable as a numeric
15665prefix argument to the associated mode-setting command. (Recall
15666that the @kbd{~} key takes a number from the stack and gives it as
15667a numeric prefix to the next command.)
15668
15669The elements of the modes vector are as follows:
15670
15671@enumerate
15672@item
15673Current precision. Default is 12; associated command is @kbd{p}.
15674
15675@item
15676Binary word size. Default is 32; associated command is @kbd{b w}.
15677
15678@item
15679Stack size (not counting the value about to be pushed by @kbd{m g}).
15680This is zero if @kbd{m g} is executed with an empty stack.
15681
15682@item
15683Number radix. Default is 10; command is @kbd{d r}.
15684
15685@item
15686Floating-point format. This is the number of digits, plus the
15687constant 0 for normal notation, 10000 for scientific notation,
1568820000 for engineering notation, or 30000 for fixed-point notation.
15689These codes are acceptable as prefix arguments to the @kbd{d n}
15690command, but note that this may lose information: For example,
15691@kbd{d s} and @kbd{C-u 12 d s} have similar (but not quite
15692identical) effects if the current precision is 12, but they both
15693produce a code of 10012, which will be treated by @kbd{d n} as
15694@kbd{C-u 12 d s}. If the precision then changes, the float format
15695will still be frozen at 12 significant figures.
15696
15697@item
15698Angular mode. Default is 1 (degrees). Other values are 2 (radians)
15699and 3 (HMS). The @kbd{m d} command accepts these prefixes.
15700
15701@item
15702Symbolic mode. Value is 0 or 1; default is 0. Command is @kbd{m s}.
15703
15704@item
15705Fraction mode. Value is 0 or 1; default is 0. Command is @kbd{m f}.
15706
15707@item
15708Polar mode. Value is 0 (rectangular) or 1 (polar); default is 0.
15709Command is @kbd{m p}.
15710
15711@item
15712Matrix/Scalar mode. Default value is @mathit{-1}. Value is 0 for Scalar
15713mode, @mathit{-2} for Matrix mode, @mathit{-3} for square Matrix mode,
15714or @var{N} for
15715@texline @math{N\times N}
15716@infoline @var{N}x@var{N}
15717Matrix mode. Command is @kbd{m v}.
15718
15719@item
15720Simplification mode. Default is 1. Value is @mathit{-1} for off (@kbd{m O}),
157210 for @kbd{m N}, 2 for @kbd{m B}, 3 for @kbd{m A}, 4 for @kbd{m E},
15722or 5 for @w{@kbd{m U}}. The @kbd{m D} command accepts these prefixes.
15723
15724@item
15725Infinite mode. Default is @mathit{-1} (off). Value is 1 if the mode is on,
15726or 0 if the mode is on with positive zeros. Command is @kbd{m i}.
15727@end enumerate
15728
15729For example, the sequence @kbd{M-1 m g @key{RET} 2 + ~ p} increases the
15730precision by two, leaving a copy of the old precision on the stack.
15731Later, @kbd{~ p} will restore the original precision using that
15732stack value. (This sequence might be especially useful inside a
15733keyboard macro.)
15734
15735As another example, @kbd{M-3 m g 1 - ~ @key{DEL}} deletes all but the
15736oldest (bottommost) stack entry.
15737
15738Yet another example: The HP-48 ``round'' command rounds a number
15739to the current displayed precision. You could roughly emulate this
15740in Calc with the sequence @kbd{M-5 m g 10000 % ~ c c}. (This
15741would not work for fixed-point mode, but it wouldn't be hard to
15742do a full emulation with the help of the @kbd{Z [} and @kbd{Z ]}
15743programming commands. @xref{Conditionals in Macros}.)
15744
15745@node Calc Mode Line, , Modes Variable, Mode Settings
15746@section The Calc Mode Line
15747
15748@noindent
15749@cindex Mode line indicators
15750This section is a summary of all symbols that can appear on the
15751Calc mode line, the highlighted bar that appears under the Calc
15752stack window (or under an editing window in Embedded mode).
15753
15754The basic mode line format is:
15755
15756@example
92e15881 15757--%*-Calc: 12 Deg @var{other modes} (Calculator)
4009494e
GM
15758@end example
15759
92e15881 15760The @samp{%*} indicates that the buffer is ``read-only''; it shows that
4009494e
GM
15761regular Emacs commands are not allowed to edit the stack buffer
15762as if it were text.
15763
15764The word @samp{Calc:} changes to @samp{CalcEmbed:} if Embedded mode
15765is enabled. The words after this describe the various Calc modes
15766that are in effect.
15767
15768The first mode is always the current precision, an integer.
15769The second mode is always the angular mode, either @code{Deg},
15770@code{Rad}, or @code{Hms}.
15771
15772Here is a complete list of the remaining symbols that can appear
15773on the mode line:
15774
15775@table @code
15776@item Alg
15777Algebraic mode (@kbd{m a}; @pxref{Algebraic Entry}).
15778
15779@item Alg[(
15780Incomplete algebraic mode (@kbd{C-u m a}).
15781
15782@item Alg*
15783Total algebraic mode (@kbd{m t}).
15784
15785@item Symb
15786Symbolic mode (@kbd{m s}; @pxref{Symbolic Mode}).
15787
15788@item Matrix
15789Matrix mode (@kbd{m v}; @pxref{Matrix Mode}).
15790
15791@item Matrix@var{n}
15792Dimensioned Matrix mode (@kbd{C-u @var{n} m v}; @pxref{Matrix Mode}).
15793
15794@item SqMatrix
15795Square Matrix mode (@kbd{C-u m v}; @pxref{Matrix Mode}).
15796
15797@item Scalar
15798Scalar mode (@kbd{m v}; @pxref{Matrix Mode}).
15799
15800@item Polar
15801Polar complex mode (@kbd{m p}; @pxref{Polar Mode}).
15802
15803@item Frac
15804Fraction mode (@kbd{m f}; @pxref{Fraction Mode}).
15805
15806@item Inf
15807Infinite mode (@kbd{m i}; @pxref{Infinite Mode}).
15808
15809@item +Inf
15810Positive Infinite mode (@kbd{C-u 0 m i}).
15811
15812@item NoSimp
15813Default simplifications off (@kbd{m O}; @pxref{Simplification Modes}).
15814
15815@item NumSimp
15816Default simplifications for numeric arguments only (@kbd{m N}).
15817
15818@item BinSimp@var{w}
15819Binary-integer simplification mode; word size @var{w} (@kbd{m B}, @kbd{b w}).
15820
15821@item AlgSimp
15822Algebraic simplification mode (@kbd{m A}).
15823
15824@item ExtSimp
15825Extended algebraic simplification mode (@kbd{m E}).
15826
15827@item UnitSimp
15828Units simplification mode (@kbd{m U}).
15829
15830@item Bin
15831Current radix is 2 (@kbd{d 2}; @pxref{Radix Modes}).
15832
15833@item Oct
15834Current radix is 8 (@kbd{d 8}).
15835
15836@item Hex
15837Current radix is 16 (@kbd{d 6}).
15838
15839@item Radix@var{n}
15840Current radix is @var{n} (@kbd{d r}).
15841
15842@item Zero
15843Leading zeros (@kbd{d z}; @pxref{Radix Modes}).
15844
15845@item Big
15846Big language mode (@kbd{d B}; @pxref{Normal Language Modes}).
15847
15848@item Flat
15849One-line normal language mode (@kbd{d O}).
15850
15851@item Unform
15852Unformatted language mode (@kbd{d U}).
15853
15854@item C
15855C language mode (@kbd{d C}; @pxref{C FORTRAN Pascal}).
15856
15857@item Pascal
15858Pascal language mode (@kbd{d P}).
15859
15860@item Fortran
15861FORTRAN language mode (@kbd{d F}).
15862
15863@item TeX
15864@TeX{} language mode (@kbd{d T}; @pxref{TeX and LaTeX Language Modes}).
15865
15866@item LaTeX
15867La@TeX{} language mode (@kbd{d L}; @pxref{TeX and LaTeX Language Modes}).
15868
15869@item Eqn
15870@dfn{Eqn} language mode (@kbd{d E}; @pxref{Eqn Language Mode}).
15871
15872@item Math
15873Mathematica language mode (@kbd{d M}; @pxref{Mathematica Language Mode}).
15874
15875@item Maple
15876Maple language mode (@kbd{d W}; @pxref{Maple Language Mode}).
15877
15878@item Norm@var{n}
15879Normal float mode with @var{n} digits (@kbd{d n}; @pxref{Float Formats}).
15880
15881@item Fix@var{n}
15882Fixed point mode with @var{n} digits after the point (@kbd{d f}).
15883
15884@item Sci
15885Scientific notation mode (@kbd{d s}).
15886
15887@item Sci@var{n}
15888Scientific notation with @var{n} digits (@kbd{d s}).
15889
15890@item Eng
15891Engineering notation mode (@kbd{d e}).
15892
15893@item Eng@var{n}
15894Engineering notation with @var{n} digits (@kbd{d e}).
15895
15896@item Left@var{n}
15897Left-justified display indented by @var{n} (@kbd{d <}; @pxref{Justification}).
15898
15899@item Right
15900Right-justified display (@kbd{d >}).
15901
15902@item Right@var{n}
15903Right-justified display with width @var{n} (@kbd{d >}).
15904
15905@item Center
15906Centered display (@kbd{d =}).
15907
15908@item Center@var{n}
15909Centered display with center column @var{n} (@kbd{d =}).
15910
15911@item Wid@var{n}
15912Line breaking with width @var{n} (@kbd{d b}; @pxref{Normal Language Modes}).
15913
15914@item Wide
15915No line breaking (@kbd{d b}).
15916
15917@item Break
15918Selections show deep structure (@kbd{j b}; @pxref{Making Selections}).
15919
15920@item Save
15921Record modes in @file{~/.calc.el} (@kbd{m R}; @pxref{General Mode Commands}).
15922
15923@item Local
15924Record modes in Embedded buffer (@kbd{m R}).
15925
15926@item LocEdit
15927Record modes as editing-only in Embedded buffer (@kbd{m R}).
15928
15929@item LocPerm
15930Record modes as permanent-only in Embedded buffer (@kbd{m R}).
15931
15932@item Global
15933Record modes as global in Embedded buffer (@kbd{m R}).
15934
15935@item Manual
15936Automatic recomputation turned off (@kbd{m C}; @pxref{Automatic
15937Recomputation}).
15938
15939@item Graph
15940GNUPLOT process is alive in background (@pxref{Graphics}).
15941
15942@item Sel
15943Top-of-stack has a selection (Embedded only; @pxref{Making Selections}).
15944
15945@item Dirty
15946The stack display may not be up-to-date (@pxref{Display Modes}).
15947
15948@item Inv
15949``Inverse'' prefix was pressed (@kbd{I}; @pxref{Inverse and Hyperbolic}).
15950
15951@item Hyp
15952``Hyperbolic'' prefix was pressed (@kbd{H}).
15953
15954@item Keep
15955``Keep-arguments'' prefix was pressed (@kbd{K}).
15956
15957@item Narrow
15958Stack is truncated (@kbd{d t}; @pxref{Truncating the Stack}).
15959@end table
15960
15961In addition, the symbols @code{Active} and @code{~Active} can appear
15962as minor modes on an Embedded buffer's mode line. @xref{Embedded Mode}.
15963
15964@node Arithmetic, Scientific Functions, Mode Settings, Top
15965@chapter Arithmetic Functions
15966
15967@noindent
15968This chapter describes the Calc commands for doing simple calculations
15969on numbers, such as addition, absolute value, and square roots. These
15970commands work by removing the top one or two values from the stack,
15971performing the desired operation, and pushing the result back onto the
15972stack. If the operation cannot be performed, the result pushed is a
15973formula instead of a number, such as @samp{2/0} (because division by zero
15974is invalid) or @samp{sqrt(x)} (because the argument @samp{x} is a formula).
15975
15976Most of the commands described here can be invoked by a single keystroke.
15977Some of the more obscure ones are two-letter sequences beginning with
15978the @kbd{f} (``functions'') prefix key.
15979
15980@xref{Prefix Arguments}, for a discussion of the effect of numeric
15981prefix arguments on commands in this chapter which do not otherwise
15982interpret a prefix argument.
15983
15984@menu
15985* Basic Arithmetic::
15986* Integer Truncation::
15987* Complex Number Functions::
15988* Conversions::
15989* Date Arithmetic::
15990* Financial Functions::
15991* Binary Functions::
15992@end menu
15993
15994@node Basic Arithmetic, Integer Truncation, Arithmetic, Arithmetic
15995@section Basic Arithmetic
15996
15997@noindent
15998@kindex +
15999@pindex calc-plus
16000@ignore
16001@mindex @null
16002@end ignore
16003@tindex +
16004The @kbd{+} (@code{calc-plus}) command adds two numbers. The numbers may
16005be any of the standard Calc data types. The resulting sum is pushed back
16006onto the stack.
16007
16008If both arguments of @kbd{+} are vectors or matrices (of matching dimensions),
16009the result is a vector or matrix sum. If one argument is a vector and the
16010other a scalar (i.e., a non-vector), the scalar is added to each of the
16011elements of the vector to form a new vector. If the scalar is not a
16012number, the operation is left in symbolic form: Suppose you added @samp{x}
16013to the vector @samp{[1,2]}. You may want the result @samp{[1+x,2+x]}, or
16014you may plan to substitute a 2-vector for @samp{x} in the future. Since
16015the Calculator can't tell which interpretation you want, it makes the
16016safest assumption. @xref{Reducing and Mapping}, for a way to add @samp{x}
16017to every element of a vector.
16018
16019If either argument of @kbd{+} is a complex number, the result will in general
16020be complex. If one argument is in rectangular form and the other polar,
16021the current Polar mode determines the form of the result. If Symbolic
16022mode is enabled, the sum may be left as a formula if the necessary
16023conversions for polar addition are non-trivial.
16024
16025If both arguments of @kbd{+} are HMS forms, the forms are added according to
16026the usual conventions of hours-minutes-seconds notation. If one argument
16027is an HMS form and the other is a number, that number is converted from
16028degrees or radians (depending on the current Angular mode) to HMS format
16029and then the two HMS forms are added.
16030
16031If one argument of @kbd{+} is a date form, the other can be either a
16032real number, which advances the date by a certain number of days, or
16033an HMS form, which advances the date by a certain amount of time.
16034Subtracting two date forms yields the number of days between them.
16035Adding two date forms is meaningless, but Calc interprets it as the
16036subtraction of one date form and the negative of the other. (The
16037negative of a date form can be understood by remembering that dates
16038are stored as the number of days before or after Jan 1, 1 AD.)
16039
16040If both arguments of @kbd{+} are error forms, the result is an error form
16041with an appropriately computed standard deviation. If one argument is an
16042error form and the other is a number, the number is taken to have zero error.
16043Error forms may have symbolic formulas as their mean and/or error parts;
16044adding these will produce a symbolic error form result. However, adding an
16045error form to a plain symbolic formula (as in @samp{(a +/- b) + c}) will not
16046work, for the same reasons just mentioned for vectors. Instead you must
16047write @samp{(a +/- b) + (c +/- 0)}.
16048
16049If both arguments of @kbd{+} are modulo forms with equal values of @expr{M},
16050or if one argument is a modulo form and the other a plain number, the
16051result is a modulo form which represents the sum, modulo @expr{M}, of
16052the two values.
16053
16054If both arguments of @kbd{+} are intervals, the result is an interval
16055which describes all possible sums of the possible input values. If
16056one argument is a plain number, it is treated as the interval
16057@w{@samp{[x ..@: x]}}.
16058
16059If one argument of @kbd{+} is an infinity and the other is not, the
16060result is that same infinity. If both arguments are infinite and in
16061the same direction, the result is the same infinity, but if they are
16062infinite in different directions the result is @code{nan}.
16063
16064@kindex -
16065@pindex calc-minus
16066@ignore
16067@mindex @null
16068@end ignore
16069@tindex -
16070The @kbd{-} (@code{calc-minus}) command subtracts two values. The top
16071number on the stack is subtracted from the one behind it, so that the
16072computation @kbd{5 @key{RET} 2 -} produces 3, not @mathit{-3}. All options
16073available for @kbd{+} are available for @kbd{-} as well.
16074
16075@kindex *
16076@pindex calc-times
16077@ignore
16078@mindex @null
16079@end ignore
16080@tindex *
16081The @kbd{*} (@code{calc-times}) command multiplies two numbers. If one
16082argument is a vector and the other a scalar, the scalar is multiplied by
16083the elements of the vector to produce a new vector. If both arguments
16084are vectors, the interpretation depends on the dimensions of the
16085vectors: If both arguments are matrices, a matrix multiplication is
16086done. If one argument is a matrix and the other a plain vector, the
16087vector is interpreted as a row vector or column vector, whichever is
16088dimensionally correct. If both arguments are plain vectors, the result
16089is a single scalar number which is the dot product of the two vectors.
16090
16091If one argument of @kbd{*} is an HMS form and the other a number, the
16092HMS form is multiplied by that amount. It is an error to multiply two
16093HMS forms together, or to attempt any multiplication involving date
16094forms. Error forms, modulo forms, and intervals can be multiplied;
16095see the comments for addition of those forms. When two error forms
16096or intervals are multiplied they are considered to be statistically
16097independent; thus, @samp{[-2 ..@: 3] * [-2 ..@: 3]} is @samp{[-6 ..@: 9]},
16098whereas @w{@samp{[-2 ..@: 3] ^ 2}} is @samp{[0 ..@: 9]}.
16099
16100@kindex /
16101@pindex calc-divide
16102@ignore
16103@mindex @null
16104@end ignore
16105@tindex /
16106The @kbd{/} (@code{calc-divide}) command divides two numbers.
16107
16108When combining multiplication and division in an algebraic formula, it
16109is good style to use parentheses to distinguish between possible
16110interpretations; the expression @samp{a/b*c} should be written
16111@samp{(a/b)*c} or @samp{a/(b*c)}, as appropriate. Without the
16112parentheses, Calc will interpret @samp{a/b*c} as @samp{a/(b*c)}, since
16113in algebraic entry Calc gives division a lower precedence than
16114multiplication. (This is not standard across all computer languages, and
16115Calc may change the precedence depending on the language mode being used.
16116@xref{Language Modes}.) This default ordering can be changed by setting
16117the customizable variable @code{calc-multiplication-has-precedence} to
16118@code{nil} (@pxref{Customizing Calc}); this will give multiplication and
16119division equal precedences. Note that Calc's default choice of
16120precedence allows @samp{a b / c d} to be used as a shortcut for
16121@smallexample
16122@group
16123a b
16124---.
16125c d
16126@end group
16127@end smallexample
16128
16129When dividing a scalar @expr{B} by a square matrix @expr{A}, the
16130computation performed is @expr{B} times the inverse of @expr{A}. This
16131also occurs if @expr{B} is itself a vector or matrix, in which case the
16132effect is to solve the set of linear equations represented by @expr{B}.
16133If @expr{B} is a matrix with the same number of rows as @expr{A}, or a
16134plain vector (which is interpreted here as a column vector), then the
16135equation @expr{A X = B} is solved for the vector or matrix @expr{X}.
16136Otherwise, if @expr{B} is a non-square matrix with the same number of
16137@emph{columns} as @expr{A}, the equation @expr{X A = B} is solved. If
16138you wish a vector @expr{B} to be interpreted as a row vector to be
16139solved as @expr{X A = B}, make it into a one-row matrix with @kbd{C-u 1
16140v p} first. To force a left-handed solution with a square matrix
16141@expr{B}, transpose @expr{A} and @expr{B} before dividing, then
16142transpose the result.
16143
16144HMS forms can be divided by real numbers or by other HMS forms. Error
16145forms can be divided in any combination of ways. Modulo forms where both
16146values and the modulo are integers can be divided to get an integer modulo
16147form result. Intervals can be divided; dividing by an interval that
16148encompasses zero or has zero as a limit will result in an infinite
16149interval.
16150
16151@kindex ^
16152@pindex calc-power
16153@ignore
16154@mindex @null
16155@end ignore
16156@tindex ^
16157The @kbd{^} (@code{calc-power}) command raises a number to a power. If
16158the power is an integer, an exact result is computed using repeated
16159multiplications. For non-integer powers, Calc uses Newton's method or
16160logarithms and exponentials. Square matrices can be raised to integer
16161powers. If either argument is an error (or interval or modulo) form,
16162the result is also an error (or interval or modulo) form.
16163
16164@kindex I ^
16165@tindex nroot
16166If you press the @kbd{I} (inverse) key first, the @kbd{I ^} command
16167computes an Nth root: @kbd{125 @key{RET} 3 I ^} computes the number 5.
16168(This is entirely equivalent to @kbd{125 @key{RET} 1:3 ^}.)
16169
16170@kindex \
16171@pindex calc-idiv
16172@tindex idiv
16173@ignore
16174@mindex @null
16175@end ignore
16176@tindex \
16177The @kbd{\} (@code{calc-idiv}) command divides two numbers on the stack
16178to produce an integer result. It is equivalent to dividing with
16179@key{/}, then rounding down with @kbd{F} (@code{calc-floor}), only a bit
16180more convenient and efficient. Also, since it is an all-integer
16181operation when the arguments are integers, it avoids problems that
16182@kbd{/ F} would have with floating-point roundoff.
16183
16184@kindex %
16185@pindex calc-mod
16186@ignore
16187@mindex @null
16188@end ignore
16189@tindex %
16190The @kbd{%} (@code{calc-mod}) command performs a ``modulo'' (or ``remainder'')
16191operation. Mathematically, @samp{a%b = a - (a\b)*b}, and is defined
16192for all real numbers @expr{a} and @expr{b} (except @expr{b=0}). For
16193positive @expr{b}, the result will always be between 0 (inclusive) and
16194@expr{b} (exclusive). Modulo does not work for HMS forms and error forms.
16195If @expr{a} is a modulo form, its modulo is changed to @expr{b}, which
16196must be positive real number.
16197
16198@kindex :
16199@pindex calc-fdiv
16200@tindex fdiv
16201The @kbd{:} (@code{calc-fdiv}) [@code{fdiv}] command
16202divides the two integers on the top of the stack to produce a fractional
16203result. This is a convenient shorthand for enabling Fraction mode (with
16204@kbd{m f}) temporarily and using @samp{/}. Note that during numeric entry
16205the @kbd{:} key is interpreted as a fraction separator, so to divide 8 by 6
16206you would have to type @kbd{8 @key{RET} 6 @key{RET} :}. (Of course, in
16207this case, it would be much easier simply to enter the fraction directly
16208as @kbd{8:6 @key{RET}}!)
16209
16210@kindex n
16211@pindex calc-change-sign
16212The @kbd{n} (@code{calc-change-sign}) command negates the number on the top
16213of the stack. It works on numbers, vectors and matrices, HMS forms, date
16214forms, error forms, intervals, and modulo forms.
16215
16216@kindex A
16217@pindex calc-abs
16218@tindex abs
16219The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the absolute
16220value of a number. The result of @code{abs} is always a nonnegative
16221real number: With a complex argument, it computes the complex magnitude.
16222With a vector or matrix argument, it computes the Frobenius norm, i.e.,
16223the square root of the sum of the squares of the absolute values of the
16224elements. The absolute value of an error form is defined by replacing
16225the mean part with its absolute value and leaving the error part the same.
16226The absolute value of a modulo form is undefined. The absolute value of
16227an interval is defined in the obvious way.
16228
16229@kindex f A
16230@pindex calc-abssqr
16231@tindex abssqr
16232The @kbd{f A} (@code{calc-abssqr}) [@code{abssqr}] command computes the
16233absolute value squared of a number, vector or matrix, or error form.
16234
16235@kindex f s
16236@pindex calc-sign
16237@tindex sign
16238The @kbd{f s} (@code{calc-sign}) [@code{sign}] command returns 1 if its
16239argument is positive, @mathit{-1} if its argument is negative, or 0 if its
16240argument is zero. In algebraic form, you can also write @samp{sign(a,x)}
16241which evaluates to @samp{x * sign(a)}, i.e., either @samp{x}, @samp{-x}, or
16242zero depending on the sign of @samp{a}.
16243
16244@kindex &
16245@pindex calc-inv
16246@tindex inv
16247@cindex Reciprocal
16248The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
16249reciprocal of a number, i.e., @expr{1 / x}. Operating on a square
16250matrix, it computes the inverse of that matrix.
16251
16252@kindex Q
16253@pindex calc-sqrt
16254@tindex sqrt
16255The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] command computes the square
16256root of a number. For a negative real argument, the result will be a
16257complex number whose form is determined by the current Polar mode.
16258
16259@kindex f h
16260@pindex calc-hypot
16261@tindex hypot
16262The @kbd{f h} (@code{calc-hypot}) [@code{hypot}] command computes the square
16263root of the sum of the squares of two numbers. That is, @samp{hypot(a,b)}
16264is the length of the hypotenuse of a right triangle with sides @expr{a}
16265and @expr{b}. If the arguments are complex numbers, their squared
16266magnitudes are used.
16267
16268@kindex f Q
16269@pindex calc-isqrt
16270@tindex isqrt
16271The @kbd{f Q} (@code{calc-isqrt}) [@code{isqrt}] command computes the
16272integer square root of an integer. This is the true square root of the
16273number, rounded down to an integer. For example, @samp{isqrt(10)}
16274produces 3. Note that, like @kbd{\} [@code{idiv}], this uses exact
16275integer arithmetic throughout to avoid roundoff problems. If the input
16276is a floating-point number or other non-integer value, this is exactly
16277the same as @samp{floor(sqrt(x))}.
16278
16279@kindex f n
16280@kindex f x
16281@pindex calc-min
16282@tindex min
16283@pindex calc-max
16284@tindex max
16285The @kbd{f n} (@code{calc-min}) [@code{min}] and @kbd{f x} (@code{calc-max})
16286[@code{max}] commands take the minimum or maximum of two real numbers,
16287respectively. These commands also work on HMS forms, date forms,
16288intervals, and infinities. (In algebraic expressions, these functions
16289take any number of arguments and return the maximum or minimum among
16290all the arguments.)
16291
16292@kindex f M
16293@kindex f X
16294@pindex calc-mant-part
16295@tindex mant
16296@pindex calc-xpon-part
16297@tindex xpon
16298The @kbd{f M} (@code{calc-mant-part}) [@code{mant}] function extracts
16299the ``mantissa'' part @expr{m} of its floating-point argument; @kbd{f X}
16300(@code{calc-xpon-part}) [@code{xpon}] extracts the ``exponent'' part
16301@expr{e}. The original number is equal to
16302@texline @math{m \times 10^e},
16303@infoline @expr{m * 10^e},
16304where @expr{m} is in the interval @samp{[1.0 ..@: 10.0)} except that
16305@expr{m=e=0} if the original number is zero. For integers
16306and fractions, @code{mant} returns the number unchanged and @code{xpon}
16307returns zero. The @kbd{v u} (@code{calc-unpack}) command can also be
16308used to ``unpack'' a floating-point number; this produces an integer
16309mantissa and exponent, with the constraint that the mantissa is not
16310a multiple of ten (again except for the @expr{m=e=0} case).
16311
16312@kindex f S
16313@pindex calc-scale-float
16314@tindex scf
16315The @kbd{f S} (@code{calc-scale-float}) [@code{scf}] function scales a number
16316by a given power of ten. Thus, @samp{scf(mant(x), xpon(x)) = x} for any
16317real @samp{x}. The second argument must be an integer, but the first
16318may actually be any numeric value. For example, @samp{scf(5,-2) = 0.05}
16319or @samp{1:20} depending on the current Fraction mode.
16320
16321@kindex f [
16322@kindex f ]
16323@pindex calc-decrement
16324@pindex calc-increment
16325@tindex decr
16326@tindex incr
16327The @kbd{f [} (@code{calc-decrement}) [@code{decr}] and @kbd{f ]}
16328(@code{calc-increment}) [@code{incr}] functions decrease or increase
16329a number by one unit. For integers, the effect is obvious. For
16330floating-point numbers, the change is by one unit in the last place.
16331For example, incrementing @samp{12.3456} when the current precision
16332is 6 digits yields @samp{12.3457}. If the current precision had been
163338 digits, the result would have been @samp{12.345601}. Incrementing
16334@samp{0.0} produces
16335@texline @math{10^{-p}},
16336@infoline @expr{10^-p},
16337where @expr{p} is the current
16338precision. These operations are defined only on integers and floats.
16339With numeric prefix arguments, they change the number by @expr{n} units.
16340
16341Note that incrementing followed by decrementing, or vice-versa, will
16342almost but not quite always cancel out. Suppose the precision is
163436 digits and the number @samp{9.99999} is on the stack. Incrementing
16344will produce @samp{10.0000}; decrementing will produce @samp{9.9999}.
16345One digit has been dropped. This is an unavoidable consequence of the
16346way floating-point numbers work.
16347
16348Incrementing a date/time form adjusts it by a certain number of seconds.
16349Incrementing a pure date form adjusts it by a certain number of days.
16350
16351@node Integer Truncation, Complex Number Functions, Basic Arithmetic, Arithmetic
16352@section Integer Truncation
16353
16354@noindent
16355There are four commands for truncating a real number to an integer,
16356differing mainly in their treatment of negative numbers. All of these
16357commands have the property that if the argument is an integer, the result
16358is the same integer. An integer-valued floating-point argument is converted
16359to integer form.
16360
16361If you press @kbd{H} (@code{calc-hyperbolic}) first, the result will be
16362expressed as an integer-valued floating-point number.
16363
16364@cindex Integer part of a number
16365@kindex F
16366@pindex calc-floor
16367@tindex floor
16368@tindex ffloor
16369@ignore
16370@mindex @null
16371@end ignore
16372@kindex H F
16373The @kbd{F} (@code{calc-floor}) [@code{floor} or @code{ffloor}] command
16374truncates a real number to the next lower integer, i.e., toward minus
16375infinity. Thus @kbd{3.6 F} produces 3, but @kbd{_3.6 F} produces
16376@mathit{-4}.
16377
16378@kindex I F
16379@pindex calc-ceiling
16380@tindex ceil
16381@tindex fceil
16382@ignore
16383@mindex @null
16384@end ignore
16385@kindex H I F
16386The @kbd{I F} (@code{calc-ceiling}) [@code{ceil} or @code{fceil}]
16387command truncates toward positive infinity. Thus @kbd{3.6 I F} produces
163884, and @kbd{_3.6 I F} produces @mathit{-3}.
16389
16390@kindex R
16391@pindex calc-round
16392@tindex round
16393@tindex fround
16394@ignore
16395@mindex @null
16396@end ignore
16397@kindex H R
16398The @kbd{R} (@code{calc-round}) [@code{round} or @code{fround}] command
16399rounds to the nearest integer. When the fractional part is .5 exactly,
16400this command rounds away from zero. (All other rounding in the
16401Calculator uses this convention as well.) Thus @kbd{3.5 R} produces 4
16402but @kbd{3.4 R} produces 3; @kbd{_3.5 R} produces @mathit{-4}.
16403
16404@kindex I R
16405@pindex calc-trunc
16406@tindex trunc
16407@tindex ftrunc
16408@ignore
16409@mindex @null
16410@end ignore
16411@kindex H I R
16412The @kbd{I R} (@code{calc-trunc}) [@code{trunc} or @code{ftrunc}]
16413command truncates toward zero. In other words, it ``chops off''
16414everything after the decimal point. Thus @kbd{3.6 I R} produces 3 and
16415@kbd{_3.6 I R} produces @mathit{-3}.
16416
16417These functions may not be applied meaningfully to error forms, but they
16418do work for intervals. As a convenience, applying @code{floor} to a
16419modulo form floors the value part of the form. Applied to a vector,
16420these functions operate on all elements of the vector one by one.
16421Applied to a date form, they operate on the internal numerical
16422representation of dates, converting a date/time form into a pure date.
16423
16424@ignore
16425@starindex
16426@end ignore
16427@tindex rounde
16428@ignore
16429@starindex
16430@end ignore
16431@tindex roundu
16432@ignore
16433@starindex
16434@end ignore
16435@tindex frounde
16436@ignore
16437@starindex
16438@end ignore
16439@tindex froundu
16440There are two more rounding functions which can only be entered in
16441algebraic notation. The @code{roundu} function is like @code{round}
16442except that it rounds up, toward plus infinity, when the fractional
16443part is .5. This distinction matters only for negative arguments.
16444Also, @code{rounde} rounds to an even number in the case of a tie,
16445rounding up or down as necessary. For example, @samp{rounde(3.5)} and
16446@samp{rounde(4.5)} both return 4, but @samp{rounde(5.5)} returns 6.
16447The advantage of round-to-even is that the net error due to rounding
16448after a long calculation tends to cancel out to zero. An important
16449subtle point here is that the number being fed to @code{rounde} will
16450already have been rounded to the current precision before @code{rounde}
16451begins. For example, @samp{rounde(2.500001)} with a current precision
16452of 6 will incorrectly, or at least surprisingly, yield 2 because the
16453argument will first have been rounded down to @expr{2.5} (which
16454@code{rounde} sees as an exact tie between 2 and 3).
16455
16456Each of these functions, when written in algebraic formulas, allows
16457a second argument which specifies the number of digits after the
16458decimal point to keep. For example, @samp{round(123.4567, 2)} will
16459produce the answer 123.46, and @samp{round(123.4567, -1)} will
16460produce 120 (i.e., the cutoff is one digit to the @emph{left} of
16461the decimal point). A second argument of zero is equivalent to
16462no second argument at all.
16463
16464@cindex Fractional part of a number
16465To compute the fractional part of a number (i.e., the amount which, when
16466added to `@tfn{floor(}@var{n}@tfn{)}', will produce @var{n}) just take @var{n}
16467modulo 1 using the @code{%} command.
16468
16469Note also the @kbd{\} (integer quotient), @kbd{f I} (integer logarithm),
16470and @kbd{f Q} (integer square root) commands, which are analogous to
16471@kbd{/}, @kbd{B}, and @kbd{Q}, respectively, except that they take integer
16472arguments and return the result rounded down to an integer.
16473
16474@node Complex Number Functions, Conversions, Integer Truncation, Arithmetic
16475@section Complex Number Functions
16476
16477@noindent
16478@kindex J
16479@pindex calc-conj
16480@tindex conj
16481The @kbd{J} (@code{calc-conj}) [@code{conj}] command computes the
16482complex conjugate of a number. For complex number @expr{a+bi}, the
16483complex conjugate is @expr{a-bi}. If the argument is a real number,
16484this command leaves it the same. If the argument is a vector or matrix,
16485this command replaces each element by its complex conjugate.
16486
16487@kindex G
16488@pindex calc-argument
16489@tindex arg
16490The @kbd{G} (@code{calc-argument}) [@code{arg}] command computes the
16491``argument'' or polar angle of a complex number. For a number in polar
16492notation, this is simply the second component of the pair
16493@texline `@tfn{(}@var{r}@tfn{;}@math{\theta}@tfn{)}'.
16494@infoline `@tfn{(}@var{r}@tfn{;}@var{theta}@tfn{)}'.
16495The result is expressed according to the current angular mode and will
16496be in the range @mathit{-180} degrees (exclusive) to @mathit{+180} degrees
16497(inclusive), or the equivalent range in radians.
16498
16499@pindex calc-imaginary
16500The @code{calc-imaginary} command multiplies the number on the
16501top of the stack by the imaginary number @expr{i = (0,1)}. This
16502command is not normally bound to a key in Calc, but it is available
16503on the @key{IMAG} button in Keypad mode.
16504
16505@kindex f r
16506@pindex calc-re
16507@tindex re
16508The @kbd{f r} (@code{calc-re}) [@code{re}] command replaces a complex number
16509by its real part. This command has no effect on real numbers. (As an
16510added convenience, @code{re} applied to a modulo form extracts
16511the value part.)
16512
16513@kindex f i
16514@pindex calc-im
16515@tindex im
16516The @kbd{f i} (@code{calc-im}) [@code{im}] command replaces a complex number
16517by its imaginary part; real numbers are converted to zero. With a vector
16518or matrix argument, these functions operate element-wise.
16519
16520@ignore
16521@mindex v p
16522@end ignore
16523@kindex v p (complex)
16524@pindex calc-pack
16525The @kbd{v p} (@code{calc-pack}) command can pack the top two numbers on
16526the stack into a composite object such as a complex number. With
16527a prefix argument of @mathit{-1}, it produces a rectangular complex number;
16528with an argument of @mathit{-2}, it produces a polar complex number.
16529(Also, @pxref{Building Vectors}.)
16530
16531@ignore
16532@mindex v u
16533@end ignore
16534@kindex v u (complex)
16535@pindex calc-unpack
16536The @kbd{v u} (@code{calc-unpack}) command takes the complex number
16537(or other composite object) on the top of the stack and unpacks it
16538into its separate components.
16539
16540@node Conversions, Date Arithmetic, Complex Number Functions, Arithmetic
16541@section Conversions
16542
16543@noindent
16544The commands described in this section convert numbers from one form
16545to another; they are two-key sequences beginning with the letter @kbd{c}.
16546
16547@kindex c f
16548@pindex calc-float
16549@tindex pfloat
16550The @kbd{c f} (@code{calc-float}) [@code{pfloat}] command converts the
16551number on the top of the stack to floating-point form. For example,
16552@expr{23} is converted to @expr{23.0}, @expr{3:2} is converted to
16553@expr{1.5}, and @expr{2.3} is left the same. If the value is a composite
16554object such as a complex number or vector, each of the components is
16555converted to floating-point. If the value is a formula, all numbers
16556in the formula are converted to floating-point. Note that depending
16557on the current floating-point precision, conversion to floating-point
16558format may lose information.
16559
16560As a special exception, integers which appear as powers or subscripts
16561are not floated by @kbd{c f}. If you really want to float a power,
16562you can use a @kbd{j s} command to select the power followed by @kbd{c f}.
16563Because @kbd{c f} cannot examine the formula outside of the selection,
16564it does not notice that the thing being floated is a power.
16565@xref{Selecting Subformulas}.
16566
16567The normal @kbd{c f} command is ``pervasive'' in the sense that it
16568applies to all numbers throughout the formula. The @code{pfloat}
16569algebraic function never stays around in a formula; @samp{pfloat(a + 1)}
16570changes to @samp{a + 1.0} as soon as it is evaluated.
16571
16572@kindex H c f
16573@tindex float
16574With the Hyperbolic flag, @kbd{H c f} [@code{float}] operates
16575only on the number or vector of numbers at the top level of its
16576argument. Thus, @samp{float(1)} is 1.0, but @samp{float(a + 1)}
16577is left unevaluated because its argument is not a number.
16578
16579You should use @kbd{H c f} if you wish to guarantee that the final
16580value, once all the variables have been assigned, is a float; you
16581would use @kbd{c f} if you wish to do the conversion on the numbers
16582that appear right now.
16583
16584@kindex c F
16585@pindex calc-fraction
16586@tindex pfrac
16587The @kbd{c F} (@code{calc-fraction}) [@code{pfrac}] command converts a
16588floating-point number into a fractional approximation. By default, it
16589produces a fraction whose decimal representation is the same as the
16590input number, to within the current precision. You can also give a
16591numeric prefix argument to specify a tolerance, either directly, or,
16592if the prefix argument is zero, by using the number on top of the stack
16593as the tolerance. If the tolerance is a positive integer, the fraction
16594is correct to within that many significant figures. If the tolerance is
16595a non-positive integer, it specifies how many digits fewer than the current
16596precision to use. If the tolerance is a floating-point number, the
16597fraction is correct to within that absolute amount.
16598
16599@kindex H c F
16600@tindex frac
16601The @code{pfrac} function is pervasive, like @code{pfloat}.
16602There is also a non-pervasive version, @kbd{H c F} [@code{frac}],
16603which is analogous to @kbd{H c f} discussed above.
16604
16605@kindex c d
16606@pindex calc-to-degrees
16607@tindex deg
16608The @kbd{c d} (@code{calc-to-degrees}) [@code{deg}] command converts a
16609number into degrees form. The value on the top of the stack may be an
16610HMS form (interpreted as degrees-minutes-seconds), or a real number which
16611will be interpreted in radians regardless of the current angular mode.
16612
16613@kindex c r
16614@pindex calc-to-radians
16615@tindex rad
16616The @kbd{c r} (@code{calc-to-radians}) [@code{rad}] command converts an
16617HMS form or angle in degrees into an angle in radians.
16618
16619@kindex c h
16620@pindex calc-to-hms
16621@tindex hms
16622The @kbd{c h} (@code{calc-to-hms}) [@code{hms}] command converts a real
16623number, interpreted according to the current angular mode, to an HMS
16624form describing the same angle. In algebraic notation, the @code{hms}
16625function also accepts three arguments: @samp{hms(@var{h}, @var{m}, @var{s})}.
16626(The three-argument version is independent of the current angular mode.)
16627
16628@pindex calc-from-hms
16629The @code{calc-from-hms} command converts the HMS form on the top of the
16630stack into a real number according to the current angular mode.
16631
16632@kindex c p
16633@kindex I c p
16634@pindex calc-polar
16635@tindex polar
16636@tindex rect
16637The @kbd{c p} (@code{calc-polar}) command converts the complex number on
16638the top of the stack from polar to rectangular form, or from rectangular
16639to polar form, whichever is appropriate. Real numbers are left the same.
16640This command is equivalent to the @code{rect} or @code{polar}
16641functions in algebraic formulas, depending on the direction of
16642conversion. (It uses @code{polar}, except that if the argument is
16643already a polar complex number, it uses @code{rect} instead. The
16644@kbd{I c p} command always uses @code{rect}.)
16645
16646@kindex c c
16647@pindex calc-clean
16648@tindex pclean
16649The @kbd{c c} (@code{calc-clean}) [@code{pclean}] command ``cleans'' the
16650number on the top of the stack. Floating point numbers are re-rounded
16651according to the current precision. Polar numbers whose angular
16652components have strayed from the @mathit{-180} to @mathit{+180} degree range
16653are normalized. (Note that results will be undesirable if the current
16654angular mode is different from the one under which the number was
16655produced!) Integers and fractions are generally unaffected by this
16656operation. Vectors and formulas are cleaned by cleaning each component
16657number (i.e., pervasively).
16658
16659If the simplification mode is set below the default level, it is raised
16660to the default level for the purposes of this command. Thus, @kbd{c c}
16661applies the default simplifications even if their automatic application
16662is disabled. @xref{Simplification Modes}.
16663
16664@cindex Roundoff errors, correcting
16665A numeric prefix argument to @kbd{c c} sets the floating-point precision
16666to that value for the duration of the command. A positive prefix (of at
16667least 3) sets the precision to the specified value; a negative or zero
16668prefix decreases the precision by the specified amount.
16669
16670@kindex c 0-9
16671@pindex calc-clean-num
16672The keystroke sequences @kbd{c 0} through @kbd{c 9} are equivalent
16673to @kbd{c c} with the corresponding negative prefix argument. If roundoff
16674errors have changed 2.0 into 1.999999, typing @kbd{c 1} to clip off one
16675decimal place often conveniently does the trick.
16676
16677The @kbd{c c} command with a numeric prefix argument, and the @kbd{c 0}
16678through @kbd{c 9} commands, also ``clip'' very small floating-point
16679numbers to zero. If the exponent is less than or equal to the negative
16680of the specified precision, the number is changed to 0.0. For example,
16681if the current precision is 12, then @kbd{c 2} changes the vector
16682@samp{[1e-8, 1e-9, 1e-10, 1e-11]} to @samp{[1e-8, 1e-9, 0, 0]}.
16683Numbers this small generally arise from roundoff noise.
16684
16685If the numbers you are using really are legitimately this small,
16686you should avoid using the @kbd{c 0} through @kbd{c 9} commands.
16687(The plain @kbd{c c} command rounds to the current precision but
16688does not clip small numbers.)
16689
16690One more property of @kbd{c 0} through @kbd{c 9}, and of @kbd{c c} with
16691a prefix argument, is that integer-valued floats are converted to
16692plain integers, so that @kbd{c 1} on @samp{[1., 1.5, 2., 2.5, 3.]}
16693produces @samp{[1, 1.5, 2, 2.5, 3]}. This is not done for huge
16694numbers (@samp{1e100} is technically an integer-valued float, but
16695you wouldn't want it automatically converted to a 100-digit integer).
16696
16697@kindex H c 0-9
16698@kindex H c c
16699@tindex clean
16700With the Hyperbolic flag, @kbd{H c c} and @kbd{H c 0} through @kbd{H c 9}
16701operate non-pervasively [@code{clean}].
16702
16703@node Date Arithmetic, Financial Functions, Conversions, Arithmetic
16704@section Date Arithmetic
16705
16706@noindent
16707@cindex Date arithmetic, additional functions
16708The commands described in this section perform various conversions
16709and calculations involving date forms (@pxref{Date Forms}). They
16710use the @kbd{t} (for time/date) prefix key followed by shifted
16711letters.
16712
16713The simplest date arithmetic is done using the regular @kbd{+} and @kbd{-}
16714commands. In particular, adding a number to a date form advances the
16715date form by a certain number of days; adding an HMS form to a date
16716form advances the date by a certain amount of time; and subtracting two
16717date forms produces a difference measured in days. The commands
16718described here provide additional, more specialized operations on dates.
16719
16720Many of these commands accept a numeric prefix argument; if you give
16721plain @kbd{C-u} as the prefix, these commands will instead take the
16722additional argument from the top of the stack.
16723
16724@menu
16725* Date Conversions::
16726* Date Functions::
16727* Time Zones::
16728* Business Days::
16729@end menu
16730
16731@node Date Conversions, Date Functions, Date Arithmetic, Date Arithmetic
16732@subsection Date Conversions
16733
16734@noindent
16735@kindex t D
16736@pindex calc-date
16737@tindex date
16738The @kbd{t D} (@code{calc-date}) [@code{date}] command converts a
16739date form into a number, measured in days since Jan 1, 1 AD. The
16740result will be an integer if @var{date} is a pure date form, or a
16741fraction or float if @var{date} is a date/time form. Or, if its
16742argument is a number, it converts this number into a date form.
16743
16744With a numeric prefix argument, @kbd{t D} takes that many objects
16745(up to six) from the top of the stack and interprets them in one
16746of the following ways:
16747
16748The @samp{date(@var{year}, @var{month}, @var{day})} function
16749builds a pure date form out of the specified year, month, and
16750day, which must all be integers. @var{Year} is a year number,
16751such as 1991 (@emph{not} the same as 91!). @var{Month} must be
16752an integer in the range 1 to 12; @var{day} must be in the range
167531 to 31. If the specified month has fewer than 31 days and
16754@var{day} is too large, the equivalent day in the following
16755month will be used.
16756
16757The @samp{date(@var{month}, @var{day})} function builds a
16758pure date form using the current year, as determined by the
16759real-time clock.
16760
16761The @samp{date(@var{year}, @var{month}, @var{day}, @var{hms})}
16762function builds a date/time form using an @var{hms} form.
16763
16764The @samp{date(@var{year}, @var{month}, @var{day}, @var{hour},
16765@var{minute}, @var{second})} function builds a date/time form.
16766@var{hour} should be an integer in the range 0 to 23;
16767@var{minute} should be an integer in the range 0 to 59;
16768@var{second} should be any real number in the range @samp{[0 .. 60)}.
16769The last two arguments default to zero if omitted.
16770
16771@kindex t J
16772@pindex calc-julian
16773@tindex julian
16774@cindex Julian day counts, conversions
16775The @kbd{t J} (@code{calc-julian}) [@code{julian}] command converts
16776a date form into a Julian day count, which is the number of days
7c1a0036
GM
16777since noon (GMT) on Jan 1, 4713 BC. A pure date is converted to an
16778integer Julian count representing noon of that day. A date/time form
16779is converted to an exact floating-point Julian count, adjusted to
4009494e
GM
16780interpret the date form in the current time zone but the Julian
16781day count in Greenwich Mean Time. A numeric prefix argument allows
16782you to specify the time zone; @pxref{Time Zones}. Use a prefix of
16783zero to suppress the time zone adjustment. Note that pure date forms
16784are never time-zone adjusted.
16785
16786This command can also do the opposite conversion, from a Julian day
16787count (either an integer day, or a floating-point day and time in
16788the GMT zone), into a pure date form or a date/time form in the
16789current or specified time zone.
16790
16791@kindex t U
16792@pindex calc-unix-time
16793@tindex unixtime
16794@cindex Unix time format, conversions
16795The @kbd{t U} (@code{calc-unix-time}) [@code{unixtime}] command
16796converts a date form into a Unix time value, which is the number of
16797seconds since midnight on Jan 1, 1970, or vice-versa. The numeric result
16798will be an integer if the current precision is 12 or less; for higher
16799precisions, the result may be a float with (@var{precision}@minus{}12)
16800digits after the decimal. Just as for @kbd{t J}, the numeric time
16801is interpreted in the GMT time zone and the date form is interpreted
16802in the current or specified zone. Some systems use Unix-like
16803numbering but with the local time zone; give a prefix of zero to
16804suppress the adjustment if so.
16805
16806@kindex t C
16807@pindex calc-convert-time-zones
16808@tindex tzconv
16809@cindex Time Zones, converting between
16810The @kbd{t C} (@code{calc-convert-time-zones}) [@code{tzconv}]
16811command converts a date form from one time zone to another. You
16812are prompted for each time zone name in turn; you can answer with
16813any suitable Calc time zone expression (@pxref{Time Zones}).
16814If you answer either prompt with a blank line, the local time
16815zone is used for that prompt. You can also answer the first
16816prompt with @kbd{$} to take the two time zone names from the
16817stack (and the date to be converted from the third stack level).
16818
16819@node Date Functions, Business Days, Date Conversions, Date Arithmetic
16820@subsection Date Functions
16821
16822@noindent
16823@kindex t N
16824@pindex calc-now
16825@tindex now
16826The @kbd{t N} (@code{calc-now}) [@code{now}] command pushes the
16827current date and time on the stack as a date form. The time is
16828reported in terms of the specified time zone; with no numeric prefix
16829argument, @kbd{t N} reports for the current time zone.
16830
16831@kindex t P
16832@pindex calc-date-part
16833The @kbd{t P} (@code{calc-date-part}) command extracts one part
16834of a date form. The prefix argument specifies the part; with no
16835argument, this command prompts for a part code from 1 to 9.
16836The various part codes are described in the following paragraphs.
16837
16838@tindex year
16839The @kbd{M-1 t P} [@code{year}] function extracts the year number
16840from a date form as an integer, e.g., 1991. This and the
16841following functions will also accept a real number for an
16842argument, which is interpreted as a standard Calc day number.
16843Note that this function will never return zero, since the year
168441 BC immediately precedes the year 1 AD.
16845
16846@tindex month
16847The @kbd{M-2 t P} [@code{month}] function extracts the month number
16848from a date form as an integer in the range 1 to 12.
16849
16850@tindex day
16851The @kbd{M-3 t P} [@code{day}] function extracts the day number
16852from a date form as an integer in the range 1 to 31.
16853
16854@tindex hour
16855The @kbd{M-4 t P} [@code{hour}] function extracts the hour from
16856a date form as an integer in the range 0 (midnight) to 23. Note
16857that 24-hour time is always used. This returns zero for a pure
16858date form. This function (and the following two) also accept
16859HMS forms as input.
16860
16861@tindex minute
16862The @kbd{M-5 t P} [@code{minute}] function extracts the minute
16863from a date form as an integer in the range 0 to 59.
16864
16865@tindex second
16866The @kbd{M-6 t P} [@code{second}] function extracts the second
16867from a date form. If the current precision is 12 or less,
16868the result is an integer in the range 0 to 59. For higher
16869precisions, the result may instead be a floating-point number.
16870
16871@tindex weekday
16872The @kbd{M-7 t P} [@code{weekday}] function extracts the weekday
16873number from a date form as an integer in the range 0 (Sunday)
16874to 6 (Saturday).
16875
16876@tindex yearday
16877The @kbd{M-8 t P} [@code{yearday}] function extracts the day-of-year
16878number from a date form as an integer in the range 1 (January 1)
16879to 366 (December 31 of a leap year).
16880
16881@tindex time
16882The @kbd{M-9 t P} [@code{time}] function extracts the time portion
16883of a date form as an HMS form. This returns @samp{0@@ 0' 0"}
16884for a pure date form.
16885
16886@kindex t M
16887@pindex calc-new-month
16888@tindex newmonth
16889The @kbd{t M} (@code{calc-new-month}) [@code{newmonth}] command
16890computes a new date form that represents the first day of the month
16891specified by the input date. The result is always a pure date
16892form; only the year and month numbers of the input are retained.
16893With a numeric prefix argument @var{n} in the range from 1 to 31,
16894@kbd{t M} computes the @var{n}th day of the month. (If @var{n}
16895is greater than the actual number of days in the month, or if
16896@var{n} is zero, the last day of the month is used.)
16897
16898@kindex t Y
16899@pindex calc-new-year
16900@tindex newyear
16901The @kbd{t Y} (@code{calc-new-year}) [@code{newyear}] command
16902computes a new pure date form that represents the first day of
16903the year specified by the input. The month, day, and time
16904of the input date form are lost. With a numeric prefix argument
16905@var{n} in the range from 1 to 366, @kbd{t Y} computes the
16906@var{n}th day of the year (366 is treated as 365 in non-leap
16907years). A prefix argument of 0 computes the last day of the
16908year (December 31). A negative prefix argument from @mathit{-1} to
16909@mathit{-12} computes the first day of the @var{n}th month of the year.
16910
16911@kindex t W
16912@pindex calc-new-week
16913@tindex newweek
16914The @kbd{t W} (@code{calc-new-week}) [@code{newweek}] command
16915computes a new pure date form that represents the Sunday on or before
16916the input date. With a numeric prefix argument, it can be made to
16917use any day of the week as the starting day; the argument must be in
16918the range from 0 (Sunday) to 6 (Saturday). This function always
16919subtracts between 0 and 6 days from the input date.
16920
16921Here's an example use of @code{newweek}: Find the date of the next
16922Wednesday after a given date. Using @kbd{M-3 t W} or @samp{newweek(d, 3)}
16923will give you the @emph{preceding} Wednesday, so @samp{newweek(d+7, 3)}
16924will give you the following Wednesday. A further look at the definition
16925of @code{newweek} shows that if the input date is itself a Wednesday,
16926this formula will return the Wednesday one week in the future. An
16927exercise for the reader is to modify this formula to yield the same day
16928if the input is already a Wednesday. Another interesting exercise is
16929to preserve the time-of-day portion of the input (@code{newweek} resets
16930the time to midnight; hint:@: how can @code{newweek} be defined in terms
16931of the @code{weekday} function?).
16932
16933@ignore
16934@starindex
16935@end ignore
16936@tindex pwday
16937The @samp{pwday(@var{date})} function (not on any key) computes the
16938day-of-month number of the Sunday on or before @var{date}. With
16939two arguments, @samp{pwday(@var{date}, @var{day})} computes the day
16940number of the Sunday on or before day number @var{day} of the month
16941specified by @var{date}. The @var{day} must be in the range from
169427 to 31; if the day number is greater than the actual number of days
16943in the month, the true number of days is used instead. Thus
16944@samp{pwday(@var{date}, 7)} finds the first Sunday of the month, and
16945@samp{pwday(@var{date}, 31)} finds the last Sunday of the month.
16946With a third @var{weekday} argument, @code{pwday} can be made to look
16947for any day of the week instead of Sunday.
16948
16949@kindex t I
16950@pindex calc-inc-month
16951@tindex incmonth
16952The @kbd{t I} (@code{calc-inc-month}) [@code{incmonth}] command
16953increases a date form by one month, or by an arbitrary number of
16954months specified by a numeric prefix argument. The time portion,
16955if any, of the date form stays the same. The day also stays the
16956same, except that if the new month has fewer days the day
16957number may be reduced to lie in the valid range. For example,
16958@samp{incmonth(<Jan 31, 1991>)} produces @samp{<Feb 28, 1991>}.
16959Because of this, @kbd{t I t I} and @kbd{M-2 t I} do not always give
16960the same results (@samp{<Mar 28, 1991>} versus @samp{<Mar 31, 1991>}
16961in this case).
16962
16963@ignore
16964@starindex
16965@end ignore
16966@tindex incyear
16967The @samp{incyear(@var{date}, @var{step})} function increases
16968a date form by the specified number of years, which may be
16969any positive or negative integer. Note that @samp{incyear(d, n)}
16970is equivalent to @w{@samp{incmonth(d, 12*n)}}, but these do not have
16971simple equivalents in terms of day arithmetic because
16972months and years have varying lengths. If the @var{step}
16973argument is omitted, 1 year is assumed. There is no keyboard
16974command for this function; use @kbd{C-u 12 t I} instead.
16975
16976There is no @code{newday} function at all because @kbd{F} [@code{floor}]
16977serves this purpose. Similarly, instead of @code{incday} and
16978@code{incweek} simply use @expr{d + n} or @expr{d + 7 n}.
16979
16980@xref{Basic Arithmetic}, for the @kbd{f ]} [@code{incr}] command
16981which can adjust a date/time form by a certain number of seconds.
16982
16983@node Business Days, Time Zones, Date Functions, Date Arithmetic
16984@subsection Business Days
16985
16986@noindent
16987Often time is measured in ``business days'' or ``working days,''
16988where weekends and holidays are skipped. Calc's normal date
16989arithmetic functions use calendar days, so that subtracting two
16990consecutive Mondays will yield a difference of 7 days. By contrast,
16991subtracting two consecutive Mondays would yield 5 business days
16992(assuming two-day weekends and the absence of holidays).
16993
16994@kindex t +
16995@kindex t -
16996@tindex badd
16997@tindex bsub
16998@pindex calc-business-days-plus
16999@pindex calc-business-days-minus
17000The @kbd{t +} (@code{calc-business-days-plus}) [@code{badd}]
17001and @kbd{t -} (@code{calc-business-days-minus}) [@code{bsub}]
17002commands perform arithmetic using business days. For @kbd{t +},
17003one argument must be a date form and the other must be a real
17004number (positive or negative). If the number is not an integer,
17005then a certain amount of time is added as well as a number of
17006days; for example, adding 0.5 business days to a time in Friday
17007evening will produce a time in Monday morning. It is also
17008possible to add an HMS form; adding @samp{12@@ 0' 0"} also adds
17009half a business day. For @kbd{t -}, the arguments are either a
17010date form and a number or HMS form, or two date forms, in which
17011case the result is the number of business days between the two
17012dates.
17013
17014@cindex @code{Holidays} variable
17015@vindex Holidays
17016By default, Calc considers any day that is not a Saturday or
17017Sunday to be a business day. You can define any number of
17018additional holidays by editing the variable @code{Holidays}.
17019(There is an @w{@kbd{s H}} convenience command for editing this
17020variable.) Initially, @code{Holidays} contains the vector
17021@samp{[sat, sun]}. Entries in the @code{Holidays} vector may
17022be any of the following kinds of objects:
17023
17024@itemize @bullet
17025@item
17026Date forms (pure dates, not date/time forms). These specify
17027particular days which are to be treated as holidays.
17028
17029@item
17030Intervals of date forms. These specify a range of days, all of
17031which are holidays (e.g., Christmas week). @xref{Interval Forms}.
17032
17033@item
17034Nested vectors of date forms. Each date form in the vector is
17035considered to be a holiday.
17036
17037@item
17038Any Calc formula which evaluates to one of the above three things.
17039If the formula involves the variable @expr{y}, it stands for a
17040yearly repeating holiday; @expr{y} will take on various year
17041numbers like 1992. For example, @samp{date(y, 12, 25)} specifies
17042Christmas day, and @samp{newweek(date(y, 11, 7), 4) + 21} specifies
17043Thanksgiving (which is held on the fourth Thursday of November).
17044If the formula involves the variable @expr{m}, that variable
17045takes on month numbers from 1 to 12: @samp{date(y, m, 15)} is
17046a holiday that takes place on the 15th of every month.
17047
17048@item
17049A weekday name, such as @code{sat} or @code{sun}. This is really
17050a variable whose name is a three-letter, lower-case day name.
17051
17052@item
17053An interval of year numbers (integers). This specifies the span of
17054years over which this holiday list is to be considered valid. Any
17055business-day arithmetic that goes outside this range will result
17056in an error message. Use this if you are including an explicit
17057list of holidays, rather than a formula to generate them, and you
17058want to make sure you don't accidentally go beyond the last point
17059where the holidays you entered are complete. If there is no
17060limiting interval in the @code{Holidays} vector, the default
17061@samp{[1 .. 2737]} is used. (This is the absolute range of years
17062for which Calc's business-day algorithms will operate.)
17063
17064@item
17065An interval of HMS forms. This specifies the span of hours that
17066are to be considered one business day. For example, if this
17067range is @samp{[9@@ 0' 0" .. 17@@ 0' 0"]} (i.e., 9am to 5pm), then
17068the business day is only eight hours long, so that @kbd{1.5 t +}
17069on @samp{<4:00pm Fri Dec 13, 1991>} will add one business day and
17070four business hours to produce @samp{<12:00pm Tue Dec 17, 1991>}.
17071Likewise, @kbd{t -} will now express differences in time as
17072fractions of an eight-hour day. Times before 9am will be treated
17073as 9am by business date arithmetic, and times at or after 5pm will
17074be treated as 4:59:59pm. If there is no HMS interval in @code{Holidays},
17075the full 24-hour day @samp{[0@ 0' 0" .. 24@ 0' 0"]} is assumed.
17076(Regardless of the type of bounds you specify, the interval is
17077treated as inclusive on the low end and exclusive on the high end,
17078so that the work day goes from 9am up to, but not including, 5pm.)
17079@end itemize
17080
17081If the @code{Holidays} vector is empty, then @kbd{t +} and
17082@kbd{t -} will act just like @kbd{+} and @kbd{-} because there will
17083then be no difference between business days and calendar days.
17084
17085Calc expands the intervals and formulas you give into a complete
17086list of holidays for internal use. This is done mainly to make
17087sure it can detect multiple holidays. (For example,
17088@samp{<Jan 1, 1989>} is both New Year's Day and a Sunday, but
17089Calc's algorithms take care to count it only once when figuring
17090the number of holidays between two dates.)
17091
17092Since the complete list of holidays for all the years from 1 to
170932737 would be huge, Calc actually computes only the part of the
17094list between the smallest and largest years that have been involved
17095in business-day calculations so far. Normally, you won't have to
17096worry about this. Keep in mind, however, that if you do one
17097calculation for 1992, and another for 1792, even if both involve
17098only a small range of years, Calc will still work out all the
17099holidays that fall in that 200-year span.
17100
17101If you add a (positive) number of days to a date form that falls on a
17102weekend or holiday, the date form is treated as if it were the most
17103recent business day. (Thus adding one business day to a Friday,
17104Saturday, or Sunday will all yield the following Monday.) If you
17105subtract a number of days from a weekend or holiday, the date is
17106effectively on the following business day. (So subtracting one business
17107day from Saturday, Sunday, or Monday yields the preceding Friday.) The
17108difference between two dates one or both of which fall on holidays
17109equals the number of actual business days between them. These
17110conventions are consistent in the sense that, if you add @var{n}
17111business days to any date, the difference between the result and the
17112original date will come out to @var{n} business days. (It can't be
17113completely consistent though; a subtraction followed by an addition
17114might come out a bit differently, since @kbd{t +} is incapable of
17115producing a date that falls on a weekend or holiday.)
17116
17117@ignore
17118@starindex
17119@end ignore
17120@tindex holiday
17121There is a @code{holiday} function, not on any keys, that takes
17122any date form and returns 1 if that date falls on a weekend or
17123holiday, as defined in @code{Holidays}, or 0 if the date is a
17124business day.
17125
17126@node Time Zones, , Business Days, Date Arithmetic
17127@subsection Time Zones
17128
17129@noindent
17130@cindex Time zones
17131@cindex Daylight saving time
17132Time zones and daylight saving time are a complicated business.
17133The conversions to and from Julian and Unix-style dates automatically
17134compute the correct time zone and daylight saving adjustment to use,
17135provided they can figure out this information. This section describes
17136Calc's time zone adjustment algorithm in detail, in case you want to
17137do conversions in different time zones or in case Calc's algorithms
17138can't determine the right correction to use.
17139
17140Adjustments for time zones and daylight saving time are done by
17141@kbd{t U}, @kbd{t J}, @kbd{t N}, and @kbd{t C}, but not by any other
17142commands. In particular, @samp{<may 1 1991> - <apr 1 1991>} evaluates
17143to exactly 30 days even though there is a daylight-saving
17144transition in between. This is also true for Julian pure dates:
17145@samp{julian(<may 1 1991>) - julian(<apr 1 1991>)}. But Julian
17146and Unix date/times will adjust for daylight saving time: using Calc's
17147default daylight saving time rule (see the explanation below),
17148@samp{julian(<12am may 1 1991>) - julian(<12am apr 1 1991>)}
17149evaluates to @samp{29.95833} (that's 29 days and 23 hours)
17150because one hour was lost when daylight saving commenced on
17151April 7, 1991.
17152
17153In brief, the idiom @samp{julian(@var{date1}) - julian(@var{date2})}
17154computes the actual number of 24-hour periods between two dates, whereas
17155@samp{@var{date1} - @var{date2}} computes the number of calendar
17156days between two dates without taking daylight saving into account.
17157
17158@pindex calc-time-zone
17159@ignore
17160@starindex
17161@end ignore
17162@tindex tzone
17163The @code{calc-time-zone} [@code{tzone}] command converts the time
17164zone specified by its numeric prefix argument into a number of
17165seconds difference from Greenwich mean time (GMT). If the argument
17166is a number, the result is simply that value multiplied by 3600.
17167Typical arguments for North America are 5 (Eastern) or 8 (Pacific). If
17168Daylight Saving time is in effect, one hour should be subtracted from
17169the normal difference.
17170
17171If you give a prefix of plain @kbd{C-u}, @code{calc-time-zone} (like other
17172date arithmetic commands that include a time zone argument) takes the
17173zone argument from the top of the stack. (In the case of @kbd{t J}
17174and @kbd{t U}, the normal argument is then taken from the second-to-top
17175stack position.) This allows you to give a non-integer time zone
17176adjustment. The time-zone argument can also be an HMS form, or
17177it can be a variable which is a time zone name in upper- or lower-case.
17178For example @samp{tzone(PST) = tzone(8)} and @samp{tzone(pdt) = tzone(7)}
17179(for Pacific standard and daylight saving times, respectively).
17180
17181North American and European time zone names are defined as follows;
17182note that for each time zone there is one name for standard time,
17183another for daylight saving time, and a third for ``generalized'' time
17184in which the daylight saving adjustment is computed from context.
17185
17186@smallexample
17187@group
17188YST PST MST CST EST AST NST GMT WET MET MEZ
17189 9 8 7 6 5 4 3.5 0 -1 -2 -2
17190
17191YDT PDT MDT CDT EDT ADT NDT BST WETDST METDST MESZ
17192 8 7 6 5 4 3 2.5 -1 -2 -3 -3
17193
17194YGT PGT MGT CGT EGT AGT NGT BGT WEGT MEGT MEGZ
171959/8 8/7 7/6 6/5 5/4 4/3 3.5/2.5 0/-1 -1/-2 -2/-3 -2/-3
17196@end group
17197@end smallexample
17198
17199@vindex math-tzone-names
17200To define time zone names that do not appear in the above table,
17201you must modify the Lisp variable @code{math-tzone-names}. This
17202is a list of lists describing the different time zone names; its
17203structure is best explained by an example. The three entries for
17204Pacific Time look like this:
17205
17206@smallexample
17207@group
17208( ( "PST" 8 0 ) ; Name as an upper-case string, then standard
17209 ( "PDT" 8 -1 ) ; adjustment, then daylight saving adjustment.
17210 ( "PGT" 8 "PST" "PDT" ) ) ; Generalized time zone.
17211@end group
17212@end smallexample
17213
17214@cindex @code{TimeZone} variable
17215@vindex TimeZone
17216With no arguments, @code{calc-time-zone} or @samp{tzone()} will by
17217default get the time zone and daylight saving information from the
17218calendar (@pxref{Daylight Saving,Calendar/Diary,The Calendar and the Diary,
17219emacs,The GNU Emacs Manual}). To use a different time zone, or if the
17220calendar does not give the desired result, you can set the Calc variable
17221@code{TimeZone} (which is by default @code{nil}) to an appropriate
17222time zone name. (The easiest way to do this is to edit the
17223@code{TimeZone} variable using Calc's @kbd{s T} command, then use the
17224@kbd{s p} (@code{calc-permanent-variable}) command to save the value of
17225@code{TimeZone} permanently.)
17226If the time zone given by @code{TimeZone} is a generalized time zone,
17227e.g., @code{EGT}, Calc examines the date being converted to tell whether
17228to use standard or daylight saving time. But if the current time zone
17229is explicit, e.g., @code{EST} or @code{EDT}, then that adjustment is
17230used exactly and Calc's daylight saving algorithm is not consulted.
17231The special time zone name @code{local}
17232is equivalent to no argument; i.e., it uses the information obtained
17233from the calendar.
17234
17235The @kbd{t J} and @code{t U} commands with no numeric prefix
17236arguments do the same thing as @samp{tzone()}; namely, use the
17237information from the calendar if @code{TimeZone} is @code{nil},
17238otherwise use the time zone given by @code{TimeZone}.
17239
17240@vindex math-daylight-savings-hook
17241@findex math-std-daylight-savings
17242When Calc computes the daylight saving information itself (i.e., when
17243the @code{TimeZone} variable is set), it will by default consider
17244daylight saving time to begin at 2 a.m.@: on the second Sunday of March
17245(for years from 2007 on) or on the last Sunday in April (for years
17246before 2007), and to end at 2 a.m.@: on the first Sunday of
17247November. (for years from 2007 on) or the last Sunday in October (for
17248years before 2007). These are the rules that have been in effect in
17249much of North America since 1966 and take into account the rule change
17250that began in 2007. If you are in a country that uses different rules
17251for computing daylight saving time, you have two choices: Write your own
17252daylight saving hook, or control time zones explicitly by setting the
17253@code{TimeZone} variable and/or always giving a time-zone argument for
17254the conversion functions.
17255
17256The Lisp variable @code{math-daylight-savings-hook} holds the
17257name of a function that is used to compute the daylight saving
17258adjustment for a given date. The default is
17259@code{math-std-daylight-savings}, which computes an adjustment
17260(either 0 or @mathit{-1}) using the North American rules given above.
17261
17262The daylight saving hook function is called with four arguments:
17263The date, as a floating-point number in standard Calc format;
17264a six-element list of the date decomposed into year, month, day,
17265hour, minute, and second, respectively; a string which contains
17266the generalized time zone name in upper-case, e.g., @code{"WEGT"};
17267and a special adjustment to be applied to the hour value when
17268converting into a generalized time zone (see below).
17269
17270@findex math-prev-weekday-in-month
17271The Lisp function @code{math-prev-weekday-in-month} is useful for
17272daylight saving computations. This is an internal version of
17273the user-level @code{pwday} function described in the previous
17274section. It takes four arguments: The floating-point date value,
17275the corresponding six-element date list, the day-of-month number,
17276and the weekday number (0-6).
17277
17278The default daylight saving hook ignores the time zone name, but a
17279more sophisticated hook could use different algorithms for different
17280time zones. It would also be possible to use different algorithms
17281depending on the year number, but the default hook always uses the
17282algorithm for 1987 and later. Here is a listing of the default
17283daylight saving hook:
17284
17285@smallexample
17286(defun math-std-daylight-savings (date dt zone bump)
17287 (cond ((< (nth 1 dt) 4) 0)
17288 ((= (nth 1 dt) 4)
17289 (let ((sunday (math-prev-weekday-in-month date dt 7 0)))
17290 (cond ((< (nth 2 dt) sunday) 0)
17291 ((= (nth 2 dt) sunday)
17292 (if (>= (nth 3 dt) (+ 3 bump)) -1 0))
17293 (t -1))))
17294 ((< (nth 1 dt) 10) -1)
17295 ((= (nth 1 dt) 10)
17296 (let ((sunday (math-prev-weekday-in-month date dt 31 0)))
17297 (cond ((< (nth 2 dt) sunday) -1)
17298 ((= (nth 2 dt) sunday)
17299 (if (>= (nth 3 dt) (+ 2 bump)) 0 -1))
17300 (t 0))))
17301 (t 0))
17302)
17303@end smallexample
17304
17305@noindent
17306The @code{bump} parameter is equal to zero when Calc is converting
17307from a date form in a generalized time zone into a GMT date value.
17308It is @mathit{-1} when Calc is converting in the other direction. The
17309adjustments shown above ensure that the conversion behaves correctly
17310and reasonably around the 2 a.m.@: transition in each direction.
17311
17312There is a ``missing'' hour between 2 a.m.@: and 3 a.m.@: at the
17313beginning of daylight saving time; converting a date/time form that
17314falls in this hour results in a time value for the following hour,
17315from 3 a.m.@: to 4 a.m. At the end of daylight saving time, the
17316hour from 1 a.m.@: to 2 a.m.@: repeats itself; converting a date/time
17317form that falls in this hour results in a time value for the first
17318manifestation of that time (@emph{not} the one that occurs one hour
17319later).
17320
17321If @code{math-daylight-savings-hook} is @code{nil}, then the
17322daylight saving adjustment is always taken to be zero.
17323
17324In algebraic formulas, @samp{tzone(@var{zone}, @var{date})}
17325computes the time zone adjustment for a given zone name at a
17326given date. The @var{date} is ignored unless @var{zone} is a
17327generalized time zone. If @var{date} is a date form, the
17328daylight saving computation is applied to it as it appears.
17329If @var{date} is a numeric date value, it is adjusted for the
17330daylight-saving version of @var{zone} before being given to
17331the daylight saving hook. This odd-sounding rule ensures
17332that the daylight-saving computation is always done in
17333local time, not in the GMT time that a numeric @var{date}
17334is typically represented in.
17335
17336@ignore
17337@starindex
17338@end ignore
17339@tindex dsadj
17340The @samp{dsadj(@var{date}, @var{zone})} function computes the
17341daylight saving adjustment that is appropriate for @var{date} in
17342time zone @var{zone}. If @var{zone} is explicitly in or not in
17343daylight saving time (e.g., @code{PDT} or @code{PST}) the
17344@var{date} is ignored. If @var{zone} is a generalized time zone,
17345the algorithms described above are used. If @var{zone} is omitted,
17346the computation is done for the current time zone.
17347
4009494e
GM
17348@node Financial Functions, Binary Functions, Date Arithmetic, Arithmetic
17349@section Financial Functions
17350
17351@noindent
17352Calc's financial or business functions use the @kbd{b} prefix
17353key followed by a shifted letter. (The @kbd{b} prefix followed by
17354a lower-case letter is used for operations on binary numbers.)
17355
17356Note that the rate and the number of intervals given to these
17357functions must be on the same time scale, e.g., both months or
17358both years. Mixing an annual interest rate with a time expressed
17359in months will give you very wrong answers!
17360
17361It is wise to compute these functions to a higher precision than
17362you really need, just to make sure your answer is correct to the
17363last penny; also, you may wish to check the definitions at the end
17364of this section to make sure the functions have the meaning you expect.
17365
17366@menu
17367* Percentages::
17368* Future Value::
17369* Present Value::
17370* Related Financial Functions::
17371* Depreciation Functions::
17372* Definitions of Financial Functions::
17373@end menu
17374
17375@node Percentages, Future Value, Financial Functions, Financial Functions
17376@subsection Percentages
17377
17378@kindex M-%
17379@pindex calc-percent
17380@tindex %
17381@tindex percent
17382The @kbd{M-%} (@code{calc-percent}) command takes a percentage value,
17383say 5.4, and converts it to an equivalent actual number. For example,
17384@kbd{5.4 M-%} enters 0.054 on the stack. (That's the @key{META} or
17385@key{ESC} key combined with @kbd{%}.)
17386
17387Actually, @kbd{M-%} creates a formula of the form @samp{5.4%}.
17388You can enter @samp{5.4%} yourself during algebraic entry. The
17389@samp{%} operator simply means, ``the preceding value divided by
17390100.'' The @samp{%} operator has very high precedence, so that
17391@samp{1+8%} is interpreted as @samp{1+(8%)}, not as @samp{(1+8)%}.
17392(The @samp{%} operator is just a postfix notation for the
17393@code{percent} function, just like @samp{20!} is the notation for
17394@samp{fact(20)}, or twenty-factorial.)
17395
17396The formula @samp{5.4%} would normally evaluate immediately to
173970.054, but the @kbd{M-%} command suppresses evaluation as it puts
17398the formula onto the stack. However, the next Calc command that
17399uses the formula @samp{5.4%} will evaluate it as its first step.
17400The net effect is that you get to look at @samp{5.4%} on the stack,
17401but Calc commands see it as @samp{0.054}, which is what they expect.
17402
17403In particular, @samp{5.4%} and @samp{0.054} are suitable values
17404for the @var{rate} arguments of the various financial functions,
17405but the number @samp{5.4} is probably @emph{not} suitable---it
17406represents a rate of 540 percent!
17407
17408The key sequence @kbd{M-% *} effectively means ``percent-of.''
17409For example, @kbd{68 @key{RET} 25 M-% *} computes 17, which is 25% of
1741068 (and also 68% of 25, which comes out to the same thing).
17411
17412@kindex c %
17413@pindex calc-convert-percent
17414The @kbd{c %} (@code{calc-convert-percent}) command converts the
17415value on the top of the stack from numeric to percentage form.
17416For example, if 0.08 is on the stack, @kbd{c %} converts it to
17417@samp{8%}. The quantity is the same, it's just represented
17418differently. (Contrast this with @kbd{M-%}, which would convert
17419this number to @samp{0.08%}.) The @kbd{=} key is a convenient way
17420to convert a formula like @samp{8%} back to numeric form, 0.08.
17421
17422To compute what percentage one quantity is of another quantity,
17423use @kbd{/ c %}. For example, @w{@kbd{17 @key{RET} 68 / c %}} displays
17424@samp{25%}.
17425
17426@kindex b %
17427@pindex calc-percent-change
17428@tindex relch
17429The @kbd{b %} (@code{calc-percent-change}) [@code{relch}] command
17430calculates the percentage change from one number to another.
17431For example, @kbd{40 @key{RET} 50 b %} produces the answer @samp{25%},
17432since 50 is 25% larger than 40. A negative result represents a
17433decrease: @kbd{50 @key{RET} 40 b %} produces @samp{-20%}, since 40 is
1743420% smaller than 50. (The answers are different in magnitude
17435because, in the first case, we're increasing by 25% of 40, but
17436in the second case, we're decreasing by 20% of 50.) The effect
17437of @kbd{40 @key{RET} 50 b %} is to compute @expr{(50-40)/40}, converting
17438the answer to percentage form as if by @kbd{c %}.
17439
17440@node Future Value, Present Value, Percentages, Financial Functions
17441@subsection Future Value
17442
17443@noindent
17444@kindex b F
17445@pindex calc-fin-fv
17446@tindex fv
17447The @kbd{b F} (@code{calc-fin-fv}) [@code{fv}] command computes
17448the future value of an investment. It takes three arguments
17449from the stack: @samp{fv(@var{rate}, @var{n}, @var{payment})}.
17450If you give payments of @var{payment} every year for @var{n}
17451years, and the money you have paid earns interest at @var{rate} per
17452year, then this function tells you what your investment would be
17453worth at the end of the period. (The actual interval doesn't
17454have to be years, as long as @var{n} and @var{rate} are expressed
17455in terms of the same intervals.) This function assumes payments
17456occur at the @emph{end} of each interval.
17457
17458@kindex I b F
17459@tindex fvb
17460The @kbd{I b F} [@code{fvb}] command does the same computation,
17461but assuming your payments are at the beginning of each interval.
17462Suppose you plan to deposit $1000 per year in a savings account
17463earning 5.4% interest, starting right now. How much will be
17464in the account after five years? @code{fvb(5.4%, 5, 1000) = 5870.73}.
17465Thus you will have earned $870 worth of interest over the years.
17466Using the stack, this calculation would have been
17467@kbd{5.4 M-% 5 @key{RET} 1000 I b F}. Note that the rate is expressed
17468as a number between 0 and 1, @emph{not} as a percentage.
17469
17470@kindex H b F
17471@tindex fvl
17472The @kbd{H b F} [@code{fvl}] command computes the future value
17473of an initial lump sum investment. Suppose you could deposit
17474those five thousand dollars in the bank right now; how much would
17475they be worth in five years? @code{fvl(5.4%, 5, 5000) = 6503.89}.
17476
17477The algebraic functions @code{fv} and @code{fvb} accept an optional
17478fourth argument, which is used as an initial lump sum in the sense
17479of @code{fvl}. In other words, @code{fv(@var{rate}, @var{n},
17480@var{payment}, @var{initial}) = fv(@var{rate}, @var{n}, @var{payment})
17481+ fvl(@var{rate}, @var{n}, @var{initial})}.
17482
17483To illustrate the relationships between these functions, we could
17484do the @code{fvb} calculation ``by hand'' using @code{fvl}. The
17485final balance will be the sum of the contributions of our five
17486deposits at various times. The first deposit earns interest for
17487five years: @code{fvl(5.4%, 5, 1000) = 1300.78}. The second
17488deposit only earns interest for four years: @code{fvl(5.4%, 4, 1000) =
174891234.13}. And so on down to the last deposit, which earns one
17490year's interest: @code{fvl(5.4%, 1, 1000) = 1054.00}. The sum of
17491these five values is, sure enough, $5870.73, just as was computed
17492by @code{fvb} directly.
17493
17494What does @code{fv(5.4%, 5, 1000) = 5569.96} mean? The payments
17495are now at the ends of the periods. The end of one year is the same
17496as the beginning of the next, so what this really means is that we've
17497lost the payment at year zero (which contributed $1300.78), but we're
17498now counting the payment at year five (which, since it didn't have
17499a chance to earn interest, counts as $1000). Indeed, @expr{5569.96 =
175005870.73 - 1300.78 + 1000} (give or take a bit of roundoff error).
17501
17502@node Present Value, Related Financial Functions, Future Value, Financial Functions
17503@subsection Present Value
17504
17505@noindent
17506@kindex b P
17507@pindex calc-fin-pv
17508@tindex pv
17509The @kbd{b P} (@code{calc-fin-pv}) [@code{pv}] command computes
17510the present value of an investment. Like @code{fv}, it takes
17511three arguments: @code{pv(@var{rate}, @var{n}, @var{payment})}.
17512It computes the present value of a series of regular payments.
17513Suppose you have the chance to make an investment that will
17514pay $2000 per year over the next four years; as you receive
17515these payments you can put them in the bank at 9% interest.
17516You want to know whether it is better to make the investment, or
17517to keep the money in the bank where it earns 9% interest right
17518from the start. The calculation @code{pv(9%, 4, 2000)} gives the
17519result 6479.44. If your initial investment must be less than this,
17520say, $6000, then the investment is worthwhile. But if you had to
17521put up $7000, then it would be better just to leave it in the bank.
17522
17523Here is the interpretation of the result of @code{pv}: You are
17524trying to compare the return from the investment you are
17525considering, which is @code{fv(9%, 4, 2000) = 9146.26}, with
17526the return from leaving the money in the bank, which is
17527@code{fvl(9%, 4, @var{x})} where @var{x} is the amount of money
17528you would have to put up in advance. The @code{pv} function
17529finds the break-even point, @expr{x = 6479.44}, at which
17530@code{fvl(9%, 4, 6479.44)} is also equal to 9146.26. This is
17531the largest amount you should be willing to invest.
17532
17533@kindex I b P
17534@tindex pvb
17535The @kbd{I b P} [@code{pvb}] command solves the same problem,
17536but with payments occurring at the beginning of each interval.
17537It has the same relationship to @code{fvb} as @code{pv} has
17538to @code{fv}. For example @code{pvb(9%, 4, 2000) = 7062.59},
17539a larger number than @code{pv} produced because we get to start
17540earning interest on the return from our investment sooner.
17541
17542@kindex H b P
17543@tindex pvl
17544The @kbd{H b P} [@code{pvl}] command computes the present value of
17545an investment that will pay off in one lump sum at the end of the
17546period. For example, if we get our $8000 all at the end of the
17547four years, @code{pvl(9%, 4, 8000) = 5667.40}. This is much
17548less than @code{pv} reported, because we don't earn any interest
17549on the return from this investment. Note that @code{pvl} and
17550@code{fvl} are simple inverses: @code{fvl(9%, 4, 5667.40) = 8000}.
17551
17552You can give an optional fourth lump-sum argument to @code{pv}
17553and @code{pvb}; this is handled in exactly the same way as the
17554fourth argument for @code{fv} and @code{fvb}.
17555
17556@kindex b N
17557@pindex calc-fin-npv
17558@tindex npv
17559The @kbd{b N} (@code{calc-fin-npv}) [@code{npv}] command computes
17560the net present value of a series of irregular investments.
17561The first argument is the interest rate. The second argument is
17562a vector which represents the expected return from the investment
17563at the end of each interval. For example, if the rate represents
17564a yearly interest rate, then the vector elements are the return
17565from the first year, second year, and so on.
17566
17567Thus, @code{npv(9%, [2000,2000,2000,2000]) = pv(9%, 4, 2000) = 6479.44}.
17568Obviously this function is more interesting when the payments are
17569not all the same!
17570
17571The @code{npv} function can actually have two or more arguments.
17572Multiple arguments are interpreted in the same way as for the
17573vector statistical functions like @code{vsum}.
17574@xref{Single-Variable Statistics}. Basically, if there are several
17575payment arguments, each either a vector or a plain number, all these
17576values are collected left-to-right into the complete list of payments.
17577A numeric prefix argument on the @kbd{b N} command says how many
17578payment values or vectors to take from the stack.
17579
17580@kindex I b N
17581@tindex npvb
17582The @kbd{I b N} [@code{npvb}] command computes the net present
17583value where payments occur at the beginning of each interval
17584rather than at the end.
17585
17586@node Related Financial Functions, Depreciation Functions, Present Value, Financial Functions
17587@subsection Related Financial Functions
17588
17589@noindent
17590The functions in this section are basically inverses of the
17591present value functions with respect to the various arguments.
17592
17593@kindex b M
17594@pindex calc-fin-pmt
17595@tindex pmt
17596The @kbd{b M} (@code{calc-fin-pmt}) [@code{pmt}] command computes
17597the amount of periodic payment necessary to amortize a loan.
17598Thus @code{pmt(@var{rate}, @var{n}, @var{amount})} equals the
17599value of @var{payment} such that @code{pv(@var{rate}, @var{n},
17600@var{payment}) = @var{amount}}.
17601
17602@kindex I b M
17603@tindex pmtb
17604The @kbd{I b M} [@code{pmtb}] command does the same computation
17605but using @code{pvb} instead of @code{pv}. Like @code{pv} and
17606@code{pvb}, these functions can also take a fourth argument which
17607represents an initial lump-sum investment.
17608
17609@kindex H b M
17610The @kbd{H b M} key just invokes the @code{fvl} function, which is
17611the inverse of @code{pvl}. There is no explicit @code{pmtl} function.
17612
17613@kindex b #
17614@pindex calc-fin-nper
17615@tindex nper
17616The @kbd{b #} (@code{calc-fin-nper}) [@code{nper}] command computes
17617the number of regular payments necessary to amortize a loan.
17618Thus @code{nper(@var{rate}, @var{payment}, @var{amount})} equals
17619the value of @var{n} such that @code{pv(@var{rate}, @var{n},
17620@var{payment}) = @var{amount}}. If @var{payment} is too small
17621ever to amortize a loan for @var{amount} at interest rate @var{rate},
17622the @code{nper} function is left in symbolic form.
17623
17624@kindex I b #
17625@tindex nperb
17626The @kbd{I b #} [@code{nperb}] command does the same computation
17627but using @code{pvb} instead of @code{pv}. You can give a fourth
17628lump-sum argument to these functions, but the computation will be
17629rather slow in the four-argument case.
17630
17631@kindex H b #
17632@tindex nperl
17633The @kbd{H b #} [@code{nperl}] command does the same computation
17634using @code{pvl}. By exchanging @var{payment} and @var{amount} you
17635can also get the solution for @code{fvl}. For example,
17636@code{nperl(8%, 2000, 1000) = 9.006}, so if you place $1000 in a
17637bank account earning 8%, it will take nine years to grow to $2000.
17638
17639@kindex b T
17640@pindex calc-fin-rate
17641@tindex rate
17642The @kbd{b T} (@code{calc-fin-rate}) [@code{rate}] command computes
17643the rate of return on an investment. This is also an inverse of @code{pv}:
17644@code{rate(@var{n}, @var{payment}, @var{amount})} computes the value of
17645@var{rate} such that @code{pv(@var{rate}, @var{n}, @var{payment}) =
17646@var{amount}}. The result is expressed as a formula like @samp{6.3%}.
17647
17648@kindex I b T
17649@kindex H b T
17650@tindex rateb
17651@tindex ratel
17652The @kbd{I b T} [@code{rateb}] and @kbd{H b T} [@code{ratel}]
17653commands solve the analogous equations with @code{pvb} or @code{pvl}
17654in place of @code{pv}. Also, @code{rate} and @code{rateb} can
17655accept an optional fourth argument just like @code{pv} and @code{pvb}.
17656To redo the above example from a different perspective,
17657@code{ratel(9, 2000, 1000) = 8.00597%}, which says you will need an
17658interest rate of 8% in order to double your account in nine years.
17659
17660@kindex b I
17661@pindex calc-fin-irr
17662@tindex irr
17663The @kbd{b I} (@code{calc-fin-irr}) [@code{irr}] command is the
17664analogous function to @code{rate} but for net present value.
17665Its argument is a vector of payments. Thus @code{irr(@var{payments})}
17666computes the @var{rate} such that @code{npv(@var{rate}, @var{payments}) = 0};
17667this rate is known as the @dfn{internal rate of return}.
17668
17669@kindex I b I
17670@tindex irrb
17671The @kbd{I b I} [@code{irrb}] command computes the internal rate of
17672return assuming payments occur at the beginning of each period.
17673
17674@node Depreciation Functions, Definitions of Financial Functions, Related Financial Functions, Financial Functions
17675@subsection Depreciation Functions
17676
17677@noindent
17678The functions in this section calculate @dfn{depreciation}, which is
17679the amount of value that a possession loses over time. These functions
17680are characterized by three parameters: @var{cost}, the original cost
17681of the asset; @var{salvage}, the value the asset will have at the end
17682of its expected ``useful life''; and @var{life}, the number of years
17683(or other periods) of the expected useful life.
17684
17685There are several methods for calculating depreciation that differ in
17686the way they spread the depreciation over the lifetime of the asset.
17687
17688@kindex b S
17689@pindex calc-fin-sln
17690@tindex sln
17691The @kbd{b S} (@code{calc-fin-sln}) [@code{sln}] command computes the
17692``straight-line'' depreciation. In this method, the asset depreciates
17693by the same amount every year (or period). For example,
17694@samp{sln(12000, 2000, 5)} returns 2000. The asset costs $12000
17695initially and will be worth $2000 after five years; it loses $2000
17696per year.
17697
17698@kindex b Y
17699@pindex calc-fin-syd
17700@tindex syd
17701The @kbd{b Y} (@code{calc-fin-syd}) [@code{syd}] command computes the
17702accelerated ``sum-of-years'-digits'' depreciation. Here the depreciation
17703is higher during the early years of the asset's life. Since the
17704depreciation is different each year, @kbd{b Y} takes a fourth @var{period}
17705parameter which specifies which year is requested, from 1 to @var{life}.
17706If @var{period} is outside this range, the @code{syd} function will
17707return zero.
17708
17709@kindex b D
17710@pindex calc-fin-ddb
17711@tindex ddb
17712The @kbd{b D} (@code{calc-fin-ddb}) [@code{ddb}] command computes an
17713accelerated depreciation using the double-declining balance method.
17714It also takes a fourth @var{period} parameter.
17715
17716For symmetry, the @code{sln} function will accept a @var{period}
17717parameter as well, although it will ignore its value except that the
17718return value will as usual be zero if @var{period} is out of range.
17719
17720For example, pushing the vector @expr{[1,2,3,4,5]} (perhaps with @kbd{v x 5})
17721and then mapping @kbd{V M ' [sln(12000,2000,5,$), syd(12000,2000,5,$),
17722ddb(12000,2000,5,$)] @key{RET}} produces a matrix that allows us to compare
17723the three depreciation methods:
17724
17725@example
17726@group
17727[ [ 2000, 3333, 4800 ]
17728 [ 2000, 2667, 2880 ]
17729 [ 2000, 2000, 1728 ]
17730 [ 2000, 1333, 592 ]
17731 [ 2000, 667, 0 ] ]
17732@end group
17733@end example
17734
17735@noindent
17736(Values have been rounded to nearest integers in this figure.)
17737We see that @code{sln} depreciates by the same amount each year,
17738@kbd{syd} depreciates more at the beginning and less at the end,
17739and @kbd{ddb} weights the depreciation even more toward the beginning.
17740
17741Summing columns with @kbd{V R : +} yields @expr{[10000, 10000, 10000]};
17742the total depreciation in any method is (by definition) the
17743difference between the cost and the salvage value.
17744
17745@node Definitions of Financial Functions, , Depreciation Functions, Financial Functions
17746@subsection Definitions
17747
17748@noindent
17749For your reference, here are the actual formulas used to compute
17750Calc's financial functions.
17751
17752Calc will not evaluate a financial function unless the @var{rate} or
17753@var{n} argument is known. However, @var{payment} or @var{amount} can
17754be a variable. Calc expands these functions according to the
17755formulas below for symbolic arguments only when you use the @kbd{a "}
17756(@code{calc-expand-formula}) command, or when taking derivatives or
17757integrals or solving equations involving the functions.
17758
17759@ifnottex
17760These formulas are shown using the conventions of Big display
17761mode (@kbd{d B}); for example, the formula for @code{fv} written
17762linearly is @samp{pmt * ((1 + rate)^n) - 1) / rate}.
17763
17764@example
17765 n
17766 (1 + rate) - 1
17767fv(rate, n, pmt) = pmt * ---------------
17768 rate
17769
17770 n
17771 ((1 + rate) - 1) (1 + rate)
17772fvb(rate, n, pmt) = pmt * ----------------------------
17773 rate
17774
17775 n
17776fvl(rate, n, pmt) = pmt * (1 + rate)
17777
17778 -n
17779 1 - (1 + rate)
17780pv(rate, n, pmt) = pmt * ----------------
17781 rate
17782
17783 -n
17784 (1 - (1 + rate) ) (1 + rate)
17785pvb(rate, n, pmt) = pmt * -----------------------------
17786 rate
17787
17788 -n
17789pvl(rate, n, pmt) = pmt * (1 + rate)
17790
17791 -1 -2 -3
17792npv(rate, [a, b, c]) = a*(1 + rate) + b*(1 + rate) + c*(1 + rate)
17793
17794 -1 -2
17795npvb(rate, [a, b, c]) = a + b*(1 + rate) + c*(1 + rate)
17796
17797 -n
17798 (amt - x * (1 + rate) ) * rate
17799pmt(rate, n, amt, x) = -------------------------------
17800 -n
17801 1 - (1 + rate)
17802
17803 -n
17804 (amt - x * (1 + rate) ) * rate
17805pmtb(rate, n, amt, x) = -------------------------------
17806 -n
17807 (1 - (1 + rate) ) (1 + rate)
17808
17809 amt * rate
17810nper(rate, pmt, amt) = - log(1 - ------------, 1 + rate)
17811 pmt
17812
17813 amt * rate
17814nperb(rate, pmt, amt) = - log(1 - ---------------, 1 + rate)
17815 pmt * (1 + rate)
17816
17817 amt
17818nperl(rate, pmt, amt) = - log(---, 1 + rate)
17819 pmt
17820
17821 1/n
17822 pmt
17823ratel(n, pmt, amt) = ------ - 1
17824 1/n
17825 amt
17826
17827 cost - salv
17828sln(cost, salv, life) = -----------
17829 life
17830
17831 (cost - salv) * (life - per + 1)
17832syd(cost, salv, life, per) = --------------------------------
17833 life * (life + 1) / 2
17834
17835 book * 2
17836ddb(cost, salv, life, per) = --------, book = cost - depreciation so far
17837 life
17838@end example
17839@end ifnottex
17840@tex
17841\turnoffactive
17842$$ \code{fv}(r, n, p) = p { (1 + r)^n - 1 \over r } $$
17843$$ \code{fvb}(r, n, p) = p { ((1 + r)^n - 1) (1 + r) \over r } $$
17844$$ \code{fvl}(r, n, p) = p (1 + r)^n $$
17845$$ \code{pv}(r, n, p) = p { 1 - (1 + r)^{-n} \over r } $$
17846$$ \code{pvb}(r, n, p) = p { (1 - (1 + r)^{-n}) (1 + r) \over r } $$
17847$$ \code{pvl}(r, n, p) = p (1 + r)^{-n} $$
17848$$ \code{npv}(r, [a,b,c]) = a (1 + r)^{-1} + b (1 + r)^{-2} + c (1 + r)^{-3} $$
17849$$ \code{npvb}(r, [a,b,c]) = a + b (1 + r)^{-1} + c (1 + r)^{-2} $$
17850$$ \code{pmt}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over 1 - (1 + r)^{-n} }$$
17851$$ \code{pmtb}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over
17852 (1 - (1 + r)^{-n}) (1 + r) } $$
17853$$ \code{nper}(r, p, a) = -\code{log}(1 - { a r \over p }, 1 + r) $$
17854$$ \code{nperb}(r, p, a) = -\code{log}(1 - { a r \over p (1 + r) }, 1 + r) $$
17855$$ \code{nperl}(r, p, a) = -\code{log}({a \over p}, 1 + r) $$
17856$$ \code{ratel}(n, p, a) = { p^{1/n} \over a^{1/n} } - 1 $$
17857$$ \code{sln}(c, s, l) = { c - s \over l } $$
17858$$ \code{syd}(c, s, l, p) = { (c - s) (l - p + 1) \over l (l+1) / 2 } $$
17859$$ \code{ddb}(c, s, l, p) = { 2 (c - \hbox{depreciation so far}) \over l } $$
17860@end tex
17861
17862@noindent
17863In @code{pmt} and @code{pmtb}, @expr{x=0} if omitted.
17864
17865These functions accept any numeric objects, including error forms,
17866intervals, and even (though not very usefully) complex numbers. The
17867above formulas specify exactly the behavior of these functions with
17868all sorts of inputs.
17869
17870Note that if the first argument to the @code{log} in @code{nper} is
17871negative, @code{nper} leaves itself in symbolic form rather than
17872returning a (financially meaningless) complex number.
17873
17874@samp{rate(num, pmt, amt)} solves the equation
17875@samp{pv(rate, num, pmt) = amt} for @samp{rate} using @kbd{H a R}
17876(@code{calc-find-root}), with the interval @samp{[.01% .. 100%]}
17877for an initial guess. The @code{rateb} function is the same except
17878that it uses @code{pvb}. Note that @code{ratel} can be solved
17879directly; its formula is shown in the above list.
17880
17881Similarly, @samp{irr(pmts)} solves the equation @samp{npv(rate, pmts) = 0}
17882for @samp{rate}.
17883
17884If you give a fourth argument to @code{nper} or @code{nperb}, Calc
17885will also use @kbd{H a R} to solve the equation using an initial
17886guess interval of @samp{[0 .. 100]}.
17887
17888A fourth argument to @code{fv} simply sums the two components
17889calculated from the above formulas for @code{fv} and @code{fvl}.
17890The same is true of @code{fvb}, @code{pv}, and @code{pvb}.
17891
17892The @kbd{ddb} function is computed iteratively; the ``book'' value
17893starts out equal to @var{cost}, and decreases according to the above
17894formula for the specified number of periods. If the book value
17895would decrease below @var{salvage}, it only decreases to @var{salvage}
17896and the depreciation is zero for all subsequent periods. The @code{ddb}
17897function returns the amount the book value decreased in the specified
17898period.
17899
17900@node Binary Functions, , Financial Functions, Arithmetic
17901@section Binary Number Functions
17902
17903@noindent
17904The commands in this chapter all use two-letter sequences beginning with
17905the @kbd{b} prefix.
17906
17907@cindex Binary numbers
17908The ``binary'' operations actually work regardless of the currently
17909displayed radix, although their results make the most sense in a radix
17910like 2, 8, or 16 (as obtained by the @kbd{d 2}, @kbd{d 8}, or @w{@kbd{d 6}}
17911commands, respectively). You may also wish to enable display of leading
17912zeros with @kbd{d z}. @xref{Radix Modes}.
17913
17914@cindex Word size for binary operations
17915The Calculator maintains a current @dfn{word size} @expr{w}, an
17916arbitrary positive or negative integer. For a positive word size, all
17917of the binary operations described here operate modulo @expr{2^w}. In
17918particular, negative arguments are converted to positive integers modulo
17919@expr{2^w} by all binary functions.
17920
17921If the word size is negative, binary operations produce 2's complement
17922integers from
17923@texline @math{-2^{-w-1}}
17924@infoline @expr{-(2^(-w-1))}
17925to
17926@texline @math{2^{-w-1}-1}
17927@infoline @expr{2^(-w-1)-1}
17928inclusive. Either mode accepts inputs in any range; the sign of
17929@expr{w} affects only the results produced.
17930
17931@kindex b c
17932@pindex calc-clip
17933@tindex clip
17934The @kbd{b c} (@code{calc-clip})
17935[@code{clip}] command can be used to clip a number by reducing it modulo
17936@expr{2^w}. The commands described in this chapter automatically clip
17937their results to the current word size. Note that other operations like
17938addition do not use the current word size, since integer addition
17939generally is not ``binary.'' (However, @pxref{Simplification Modes},
17940@code{calc-bin-simplify-mode}.) For example, with a word size of 8
17941bits @kbd{b c} converts a number to the range 0 to 255; with a word
17942size of @mathit{-8} @kbd{b c} converts to the range @mathit{-128} to 127.
17943
17944@kindex b w
17945@pindex calc-word-size
17946The default word size is 32 bits. All operations except the shifts and
17947rotates allow you to specify a different word size for that one
17948operation by giving a numeric prefix argument: @kbd{C-u 8 b c} clips the
17949top of stack to the range 0 to 255 regardless of the current word size.
17950To set the word size permanently, use @kbd{b w} (@code{calc-word-size}).
17951This command displays a prompt with the current word size; press @key{RET}
17952immediately to keep this word size, or type a new word size at the prompt.
17953
17954When the binary operations are written in symbolic form, they take an
17955optional second (or third) word-size parameter. When a formula like
17956@samp{and(a,b)} is finally evaluated, the word size current at that time
17957will be used, but when @samp{and(a,b,-8)} is evaluated, a word size of
17958@mathit{-8} will always be used. A symbolic binary function will be left
17959in symbolic form unless the all of its argument(s) are integers or
17960integer-valued floats.
17961
17962If either or both arguments are modulo forms for which @expr{M} is a
17963power of two, that power of two is taken as the word size unless a
17964numeric prefix argument overrides it. The current word size is never
17965consulted when modulo-power-of-two forms are involved.
17966
17967@kindex b a
17968@pindex calc-and
17969@tindex and
17970The @kbd{b a} (@code{calc-and}) [@code{and}] command computes the bitwise
17971AND of the two numbers on the top of the stack. In other words, for each
17972of the @expr{w} binary digits of the two numbers (pairwise), the corresponding
17973bit of the result is 1 if and only if both input bits are 1:
17974@samp{and(2#1100, 2#1010) = 2#1000}.
17975
17976@kindex b o
17977@pindex calc-or
17978@tindex or
17979The @kbd{b o} (@code{calc-or}) [@code{or}] command computes the bitwise
17980inclusive OR of two numbers. A bit is 1 if either of the input bits, or
17981both, are 1: @samp{or(2#1100, 2#1010) = 2#1110}.
17982
17983@kindex b x
17984@pindex calc-xor
17985@tindex xor
17986The @kbd{b x} (@code{calc-xor}) [@code{xor}] command computes the bitwise
17987exclusive OR of two numbers. A bit is 1 if exactly one of the input bits
17988is 1: @samp{xor(2#1100, 2#1010) = 2#0110}.
17989
17990@kindex b d
17991@pindex calc-diff
17992@tindex diff
17993The @kbd{b d} (@code{calc-diff}) [@code{diff}] command computes the bitwise
17994difference of two numbers; this is defined by @samp{diff(a,b) = and(a,not(b))},
17995so that @samp{diff(2#1100, 2#1010) = 2#0100}.
17996
17997@kindex b n
17998@pindex calc-not
17999@tindex not
18000The @kbd{b n} (@code{calc-not}) [@code{not}] command computes the bitwise
18001NOT of a number. A bit is 1 if the input bit is 0 and vice-versa.
18002
18003@kindex b l
18004@pindex calc-lshift-binary
18005@tindex lsh
18006The @kbd{b l} (@code{calc-lshift-binary}) [@code{lsh}] command shifts a
18007number left by one bit, or by the number of bits specified in the numeric
18008prefix argument. A negative prefix argument performs a logical right shift,
18009in which zeros are shifted in on the left. In symbolic form, @samp{lsh(a)}
18010is short for @samp{lsh(a,1)}, which in turn is short for @samp{lsh(a,n,w)}.
18011Bits shifted ``off the end,'' according to the current word size, are lost.
18012
18013@kindex H b l
18014@kindex H b r
18015@ignore
18016@mindex @idots
18017@end ignore
18018@kindex H b L
18019@ignore
18020@mindex @null
18021@end ignore
18022@kindex H b R
18023@ignore
18024@mindex @null
18025@end ignore
18026@kindex H b t
18027The @kbd{H b l} command also does a left shift, but it takes two arguments
18028from the stack (the value to shift, and, at top-of-stack, the number of
18029bits to shift). This version interprets the prefix argument just like
18030the regular binary operations, i.e., as a word size. The Hyperbolic flag
18031has a similar effect on the rest of the binary shift and rotate commands.
18032
18033@kindex b r
18034@pindex calc-rshift-binary
18035@tindex rsh
18036The @kbd{b r} (@code{calc-rshift-binary}) [@code{rsh}] command shifts a
18037number right by one bit, or by the number of bits specified in the numeric
18038prefix argument: @samp{rsh(a,n) = lsh(a,-n)}.
18039
18040@kindex b L
18041@pindex calc-lshift-arith
18042@tindex ash
18043The @kbd{b L} (@code{calc-lshift-arith}) [@code{ash}] command shifts a
18044number left. It is analogous to @code{lsh}, except that if the shift
18045is rightward (the prefix argument is negative), an arithmetic shift
18046is performed as described below.
18047
18048@kindex b R
18049@pindex calc-rshift-arith
18050@tindex rash
18051The @kbd{b R} (@code{calc-rshift-arith}) [@code{rash}] command performs
18052an ``arithmetic'' shift to the right, in which the leftmost bit (according
18053to the current word size) is duplicated rather than shifting in zeros.
18054This corresponds to dividing by a power of two where the input is interpreted
18055as a signed, twos-complement number. (The distinction between the @samp{rsh}
18056and @samp{rash} operations is totally independent from whether the word
18057size is positive or negative.) With a negative prefix argument, this
18058performs a standard left shift.
18059
18060@kindex b t
18061@pindex calc-rotate-binary
18062@tindex rot
18063The @kbd{b t} (@code{calc-rotate-binary}) [@code{rot}] command rotates a
18064number one bit to the left. The leftmost bit (according to the current
18065word size) is dropped off the left and shifted in on the right. With a
18066numeric prefix argument, the number is rotated that many bits to the left
18067or right.
18068
18069@xref{Set Operations}, for the @kbd{b p} and @kbd{b u} commands that
18070pack and unpack binary integers into sets. (For example, @kbd{b u}
18071unpacks the number @samp{2#11001} to the set of bit-numbers
18072@samp{[0, 3, 4]}.) Type @kbd{b u V #} to count the number of ``1''
18073bits in a binary integer.
18074
18075Another interesting use of the set representation of binary integers
18076is to reverse the bits in, say, a 32-bit integer. Type @kbd{b u} to
18077unpack; type @kbd{31 @key{TAB} -} to replace each bit-number in the set
18078with 31 minus that bit-number; type @kbd{b p} to pack the set back
18079into a binary integer.
18080
18081@node Scientific Functions, Matrix Functions, Arithmetic, Top
18082@chapter Scientific Functions
18083
18084@noindent
18085The functions described here perform trigonometric and other transcendental
18086calculations. They generally produce floating-point answers correct to the
18087full current precision. The @kbd{H} (Hyperbolic) and @kbd{I} (Inverse)
18088flag keys must be used to get some of these functions from the keyboard.
18089
18090@kindex P
18091@pindex calc-pi
18092@cindex @code{pi} variable
18093@vindex pi
18094@kindex H P
18095@cindex @code{e} variable
18096@vindex e
18097@kindex I P
18098@cindex @code{gamma} variable
18099@vindex gamma
18100@cindex Gamma constant, Euler's
18101@cindex Euler's gamma constant
18102@kindex H I P
18103@cindex @code{phi} variable
18104@cindex Phi, golden ratio
18105@cindex Golden ratio
18106One miscellaneous command is shift-@kbd{P} (@code{calc-pi}), which pushes
18107the value of @cpi{} (at the current precision) onto the stack. With the
18108Hyperbolic flag, it pushes the value @expr{e}, the base of natural logarithms.
18109With the Inverse flag, it pushes Euler's constant
18110@texline @math{\gamma}
18111@infoline @expr{gamma}
18112(about 0.5772). With both Inverse and Hyperbolic, it
18113pushes the ``golden ratio''
18114@texline @math{\phi}
18115@infoline @expr{phi}
18116(about 1.618). (At present, Euler's constant is not available
18117to unlimited precision; Calc knows only the first 100 digits.)
18118In Symbolic mode, these commands push the
18119actual variables @samp{pi}, @samp{e}, @samp{gamma}, and @samp{phi},
18120respectively, instead of their values; @pxref{Symbolic Mode}.
18121
18122@ignore
18123@mindex Q
18124@end ignore
18125@ignore
18126@mindex I Q
18127@end ignore
18128@kindex I Q
18129@tindex sqr
18130The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] function is described elsewhere;
18131@pxref{Basic Arithmetic}. With the Inverse flag [@code{sqr}], this command
18132computes the square of the argument.
18133
18134@xref{Prefix Arguments}, for a discussion of the effect of numeric
18135prefix arguments on commands in this chapter which do not otherwise
18136interpret a prefix argument.
18137
18138@menu
18139* Logarithmic Functions::
18140* Trigonometric and Hyperbolic Functions::
18141* Advanced Math Functions::
18142* Branch Cuts::
18143* Random Numbers::
18144* Combinatorial Functions::
18145* Probability Distribution Functions::
18146@end menu
18147
18148@node Logarithmic Functions, Trigonometric and Hyperbolic Functions, Scientific Functions, Scientific Functions
18149@section Logarithmic Functions
18150
18151@noindent
18152@kindex L
18153@pindex calc-ln
18154@tindex ln
18155@ignore
18156@mindex @null
18157@end ignore
18158@kindex I E
18159The shift-@kbd{L} (@code{calc-ln}) [@code{ln}] command computes the natural
18160logarithm of the real or complex number on the top of the stack. With
18161the Inverse flag it computes the exponential function instead, although
18162this is redundant with the @kbd{E} command.
18163
18164@kindex E
18165@pindex calc-exp
18166@tindex exp
18167@ignore
18168@mindex @null
18169@end ignore
18170@kindex I L
18171The shift-@kbd{E} (@code{calc-exp}) [@code{exp}] command computes the
18172exponential, i.e., @expr{e} raised to the power of the number on the stack.
18173The meanings of the Inverse and Hyperbolic flags follow from those for
18174the @code{calc-ln} command.
18175
18176@kindex H L
18177@kindex H E
18178@pindex calc-log10
18179@tindex log10
18180@tindex exp10
18181@ignore
18182@mindex @null
18183@end ignore
18184@kindex H I L
18185@ignore
18186@mindex @null
18187@end ignore
18188@kindex H I E
18189The @kbd{H L} (@code{calc-log10}) [@code{log10}] command computes the common
18190(base-10) logarithm of a number. (With the Inverse flag [@code{exp10}],
18191it raises ten to a given power.) Note that the common logarithm of a
18192complex number is computed by taking the natural logarithm and dividing
18193by
18194@texline @math{\ln10}.
18195@infoline @expr{ln(10)}.
18196
18197@kindex B
18198@kindex I B
18199@pindex calc-log
18200@tindex log
18201@tindex alog
18202The @kbd{B} (@code{calc-log}) [@code{log}] command computes a logarithm
18203to any base. For example, @kbd{1024 @key{RET} 2 B} produces 10, since
18204@texline @math{2^{10} = 1024}.
18205@infoline @expr{2^10 = 1024}.
18206In certain cases like @samp{log(3,9)}, the result
18207will be either @expr{1:2} or @expr{0.5} depending on the current Fraction
18208mode setting. With the Inverse flag [@code{alog}], this command is
18209similar to @kbd{^} except that the order of the arguments is reversed.
18210
18211@kindex f I
18212@pindex calc-ilog
18213@tindex ilog
18214The @kbd{f I} (@code{calc-ilog}) [@code{ilog}] command computes the
18215integer logarithm of a number to any base. The number and the base must
18216themselves be positive integers. This is the true logarithm, rounded
18217down to an integer. Thus @kbd{ilog(x,10)} is 3 for all @expr{x} in the
18218range from 1000 to 9999. If both arguments are positive integers, exact
18219integer arithmetic is used; otherwise, this is equivalent to
18220@samp{floor(log(x,b))}.
18221
18222@kindex f E
18223@pindex calc-expm1
18224@tindex expm1
18225The @kbd{f E} (@code{calc-expm1}) [@code{expm1}] command computes
18226@texline @math{e^x - 1},
18227@infoline @expr{exp(x)-1},
18228but using an algorithm that produces a more accurate
18229answer when the result is close to zero, i.e., when
18230@texline @math{e^x}
18231@infoline @expr{exp(x)}
18232is close to one.
18233
18234@kindex f L
18235@pindex calc-lnp1
18236@tindex lnp1
18237The @kbd{f L} (@code{calc-lnp1}) [@code{lnp1}] command computes
18238@texline @math{\ln(x+1)},
18239@infoline @expr{ln(x+1)},
18240producing a more accurate answer when @expr{x} is close to zero.
18241
18242@node Trigonometric and Hyperbolic Functions, Advanced Math Functions, Logarithmic Functions, Scientific Functions
18243@section Trigonometric/Hyperbolic Functions
18244
18245@noindent
18246@kindex S
18247@pindex calc-sin
18248@tindex sin
18249The shift-@kbd{S} (@code{calc-sin}) [@code{sin}] command computes the sine
18250of an angle or complex number. If the input is an HMS form, it is interpreted
18251as degrees-minutes-seconds; otherwise, the input is interpreted according
18252to the current angular mode. It is best to use Radians mode when operating
18253on complex numbers.
18254
18255Calc's ``units'' mechanism includes angular units like @code{deg},
18256@code{rad}, and @code{grad}. While @samp{sin(45 deg)} is not evaluated
18257all the time, the @kbd{u s} (@code{calc-simplify-units}) command will
18258simplify @samp{sin(45 deg)} by taking the sine of 45 degrees, regardless
18259of the current angular mode. @xref{Basic Operations on Units}.
18260
18261Also, the symbolic variable @code{pi} is not ordinarily recognized in
18262arguments to trigonometric functions, as in @samp{sin(3 pi / 4)}, but
18263the @kbd{a s} (@code{calc-simplify}) command recognizes many such
18264formulas when the current angular mode is Radians @emph{and} Symbolic
18265mode is enabled; this example would be replaced by @samp{sqrt(2) / 2}.
18266@xref{Symbolic Mode}. Beware, this simplification occurs even if you
18267have stored a different value in the variable @samp{pi}; this is one
18268reason why changing built-in variables is a bad idea. Arguments of
18269the form @expr{x} plus a multiple of @cpiover{2} are also simplified.
18270Calc includes similar formulas for @code{cos} and @code{tan}.
18271
18272The @kbd{a s} command knows all angles which are integer multiples of
18273@cpiover{12}, @cpiover{10}, or @cpiover{8} radians. In Degrees mode,
18274analogous simplifications occur for integer multiples of 15 or 18
18275degrees, and for arguments plus multiples of 90 degrees.
18276
18277@kindex I S
18278@pindex calc-arcsin
18279@tindex arcsin
18280With the Inverse flag, @code{calc-sin} computes an arcsine. This is also
18281available as the @code{calc-arcsin} command or @code{arcsin} algebraic
18282function. The returned argument is converted to degrees, radians, or HMS
18283notation depending on the current angular mode.
18284
18285@kindex H S
18286@pindex calc-sinh
18287@tindex sinh
18288@kindex H I S
18289@pindex calc-arcsinh
18290@tindex arcsinh
18291With the Hyperbolic flag, @code{calc-sin} computes the hyperbolic
18292sine, also available as @code{calc-sinh} [@code{sinh}]. With the
18293Hyperbolic and Inverse flags, it computes the hyperbolic arcsine
18294(@code{calc-arcsinh}) [@code{arcsinh}].
18295
18296@kindex C
18297@pindex calc-cos
18298@tindex cos
18299@ignore
18300@mindex @idots
18301@end ignore
18302@kindex I C
18303@pindex calc-arccos
18304@ignore
18305@mindex @null
18306@end ignore
18307@tindex arccos
18308@ignore
18309@mindex @null
18310@end ignore
18311@kindex H C
18312@pindex calc-cosh
18313@ignore
18314@mindex @null
18315@end ignore
18316@tindex cosh
18317@ignore
18318@mindex @null
18319@end ignore
18320@kindex H I C
18321@pindex calc-arccosh
18322@ignore
18323@mindex @null
18324@end ignore
18325@tindex arccosh
18326@ignore
18327@mindex @null
18328@end ignore
18329@kindex T
18330@pindex calc-tan
18331@ignore
18332@mindex @null
18333@end ignore
18334@tindex tan
18335@ignore
18336@mindex @null
18337@end ignore
18338@kindex I T
18339@pindex calc-arctan
18340@ignore
18341@mindex @null
18342@end ignore
18343@tindex arctan
18344@ignore
18345@mindex @null
18346@end ignore
18347@kindex H T
18348@pindex calc-tanh
18349@ignore
18350@mindex @null
18351@end ignore
18352@tindex tanh
18353@ignore
18354@mindex @null
18355@end ignore
18356@kindex H I T
18357@pindex calc-arctanh
18358@ignore
18359@mindex @null
18360@end ignore
18361@tindex arctanh
18362The shift-@kbd{C} (@code{calc-cos}) [@code{cos}] command computes the cosine
18363of an angle or complex number, and shift-@kbd{T} (@code{calc-tan}) [@code{tan}]
18364computes the tangent, along with all the various inverse and hyperbolic
18365variants of these functions.
18366
18367@kindex f T
18368@pindex calc-arctan2
18369@tindex arctan2
18370The @kbd{f T} (@code{calc-arctan2}) [@code{arctan2}] command takes two
18371numbers from the stack and computes the arc tangent of their ratio. The
18372result is in the full range from @mathit{-180} (exclusive) to @mathit{+180}
18373(inclusive) degrees, or the analogous range in radians. A similar
18374result would be obtained with @kbd{/} followed by @kbd{I T}, but the
18375value would only be in the range from @mathit{-90} to @mathit{+90} degrees
18376since the division loses information about the signs of the two
18377components, and an error might result from an explicit division by zero
18378which @code{arctan2} would avoid. By (arbitrary) definition,
18379@samp{arctan2(0,0)=0}.
18380
18381@pindex calc-sincos
18382@ignore
18383@starindex
18384@end ignore
18385@tindex sincos
18386@ignore
18387@starindex
18388@end ignore
18389@ignore
18390@mindex arc@idots
18391@end ignore
18392@tindex arcsincos
18393The @code{calc-sincos} [@code{sincos}] command computes the sine and
18394cosine of a number, returning them as a vector of the form
18395@samp{[@var{cos}, @var{sin}]}.
18396With the Inverse flag [@code{arcsincos}], this command takes a two-element
18397vector as an argument and computes @code{arctan2} of the elements.
18398(This command does not accept the Hyperbolic flag.)
18399
18400@pindex calc-sec
18401@tindex sec
18402@pindex calc-csc
18403@tindex csc
18404@pindex calc-cot
18405@tindex cot
18406@pindex calc-sech
18407@tindex sech
18408@pindex calc-csch
18409@tindex csch
18410@pindex calc-coth
18411@tindex coth
18412The remaining trigonometric functions, @code{calc-sec} [@code{sec}],
4bb49b43 18413@code{calc-csc} [@code{csc}] and @code{calc-cot} [@code{cot}], are also
4009494e
GM
18414available. With the Hyperbolic flag, these compute their hyperbolic
18415counterparts, which are also available separately as @code{calc-sech}
4bb49b43 18416[@code{sech}], @code{calc-csch} [@code{csch}] and @code{calc-coth}
9c264403 18417[@code{coth}]. (These commands do not accept the Inverse flag.)
4009494e
GM
18418
18419@node Advanced Math Functions, Branch Cuts, Trigonometric and Hyperbolic Functions, Scientific Functions
18420@section Advanced Mathematical Functions
18421
18422@noindent
18423Calc can compute a variety of less common functions that arise in
18424various branches of mathematics. All of the functions described in
18425this section allow arbitrary complex arguments and, except as noted,
18426will work to arbitrarily large precisions. They can not at present
18427handle error forms or intervals as arguments.
18428
18429NOTE: These functions are still experimental. In particular, their
18430accuracy is not guaranteed in all domains. It is advisable to set the
18431current precision comfortably higher than you actually need when
18432using these functions. Also, these functions may be impractically
18433slow for some values of the arguments.
18434
18435@kindex f g
18436@pindex calc-gamma
18437@tindex gamma
18438The @kbd{f g} (@code{calc-gamma}) [@code{gamma}] command computes the Euler
18439gamma function. For positive integer arguments, this is related to the
18440factorial function: @samp{gamma(n+1) = fact(n)}. For general complex
18441arguments the gamma function can be defined by the following definite
18442integral:
18443@texline @math{\Gamma(a) = \int_0^\infty t^{a-1} e^t dt}.
18444@infoline @expr{gamma(a) = integ(t^(a-1) exp(t), t, 0, inf)}.
18445(The actual implementation uses far more efficient computational methods.)
18446
18447@kindex f G
18448@tindex gammaP
18449@ignore
18450@mindex @idots
18451@end ignore
18452@kindex I f G
18453@ignore
18454@mindex @null
18455@end ignore
18456@kindex H f G
18457@ignore
18458@mindex @null
18459@end ignore
18460@kindex H I f G
18461@pindex calc-inc-gamma
18462@ignore
18463@mindex @null
18464@end ignore
18465@tindex gammaQ
18466@ignore
18467@mindex @null
18468@end ignore
18469@tindex gammag
18470@ignore
18471@mindex @null
18472@end ignore
18473@tindex gammaG
18474The @kbd{f G} (@code{calc-inc-gamma}) [@code{gammaP}] command computes
18475the incomplete gamma function, denoted @samp{P(a,x)}. This is defined by
18476the integral,
18477@texline @math{P(a,x) = \left( \int_0^x t^{a-1} e^t dt \right) / \Gamma(a)}.
18478@infoline @expr{gammaP(a,x) = integ(t^(a-1) exp(t), t, 0, x) / gamma(a)}.
18479This implies that @samp{gammaP(a,inf) = 1} for any @expr{a} (see the
18480definition of the normal gamma function).
18481
18482Several other varieties of incomplete gamma function are defined.
18483The complement of @expr{P(a,x)}, called @expr{Q(a,x) = 1-P(a,x)} by
18484some authors, is computed by the @kbd{I f G} [@code{gammaQ}] command.
18485You can think of this as taking the other half of the integral, from
18486@expr{x} to infinity.
18487
18488@ifnottex
18489The functions corresponding to the integrals that define @expr{P(a,x)}
18490and @expr{Q(a,x)} but without the normalizing @expr{1/gamma(a)}
18491factor are called @expr{g(a,x)} and @expr{G(a,x)}, respectively
18492(where @expr{g} and @expr{G} represent the lower- and upper-case Greek
18493letter gamma). You can obtain these using the @kbd{H f G} [@code{gammag}]
18494and @kbd{H I f G} [@code{gammaG}] commands.
18495@end ifnottex
18496@tex
18497\turnoffactive
18498The functions corresponding to the integrals that define $P(a,x)$
18499and $Q(a,x)$ but without the normalizing $1/\Gamma(a)$
18500factor are called $\gamma(a,x)$ and $\Gamma(a,x)$, respectively.
18501You can obtain these using the \kbd{H f G} [\code{gammag}] and
18502\kbd{I H f G} [\code{gammaG}] commands.
18503@end tex
18504
18505@kindex f b
18506@pindex calc-beta
18507@tindex beta
18508The @kbd{f b} (@code{calc-beta}) [@code{beta}] command computes the
18509Euler beta function, which is defined in terms of the gamma function as
18510@texline @math{B(a,b) = \Gamma(a) \Gamma(b) / \Gamma(a+b)},
18511@infoline @expr{beta(a,b) = gamma(a) gamma(b) / gamma(a+b)},
18512or by
18513@texline @math{B(a,b) = \int_0^1 t^{a-1} (1-t)^{b-1} dt}.
18514@infoline @expr{beta(a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, 1)}.
18515
18516@kindex f B
18517@kindex H f B
18518@pindex calc-inc-beta
18519@tindex betaI
18520@tindex betaB
18521The @kbd{f B} (@code{calc-inc-beta}) [@code{betaI}] command computes
18522the incomplete beta function @expr{I(x,a,b)}. It is defined by
18523@texline @math{I(x,a,b) = \left( \int_0^x t^{a-1} (1-t)^{b-1} dt \right) / B(a,b)}.
18524@infoline @expr{betaI(x,a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, x) / beta(a,b)}.
18525Once again, the @kbd{H} (hyperbolic) prefix gives the corresponding
18526un-normalized version [@code{betaB}].
18527
18528@kindex f e
18529@kindex I f e
18530@pindex calc-erf
18531@tindex erf
18532@tindex erfc
18533The @kbd{f e} (@code{calc-erf}) [@code{erf}] command computes the
18534error function
18535@texline @math{\hbox{erf}(x) = {2 \over \sqrt{\pi}} \int_0^x e^{-t^2} dt}.
18536@infoline @expr{erf(x) = 2 integ(exp(-(t^2)), t, 0, x) / sqrt(pi)}.
18537The complementary error function @kbd{I f e} (@code{calc-erfc}) [@code{erfc}]
18538is the corresponding integral from @samp{x} to infinity; the sum
18539@texline @math{\hbox{erf}(x) + \hbox{erfc}(x) = 1}.
18540@infoline @expr{erf(x) + erfc(x) = 1}.
18541
18542@kindex f j
18543@kindex f y
18544@pindex calc-bessel-J
18545@pindex calc-bessel-Y
18546@tindex besJ
18547@tindex besY
18548The @kbd{f j} (@code{calc-bessel-J}) [@code{besJ}] and @kbd{f y}
18549(@code{calc-bessel-Y}) [@code{besY}] commands compute the Bessel
18550functions of the first and second kinds, respectively.
18551In @samp{besJ(n,x)} and @samp{besY(n,x)} the ``order'' parameter
18552@expr{n} is often an integer, but is not required to be one.
18553Calc's implementation of the Bessel functions currently limits the
18554precision to 8 digits, and may not be exact even to that precision.
18555Use with care!
18556
18557@node Branch Cuts, Random Numbers, Advanced Math Functions, Scientific Functions
18558@section Branch Cuts and Principal Values
18559
18560@noindent
18561@cindex Branch cuts
18562@cindex Principal values
18563All of the logarithmic, trigonometric, and other scientific functions are
18564defined for complex numbers as well as for reals.
18565This section describes the values
18566returned in cases where the general result is a family of possible values.
18567Calc follows section 12.5.3 of Steele's @dfn{Common Lisp, the Language},
18568second edition, in these matters. This section will describe each
18569function briefly; for a more detailed discussion (including some nifty
18570diagrams), consult Steele's book.
18571
18572Note that the branch cuts for @code{arctan} and @code{arctanh} were
18573changed between the first and second editions of Steele. Versions of
18574Calc starting with 2.00 follow the second edition.
18575
18576The new branch cuts exactly match those of the HP-28/48 calculators.
18577They also match those of Mathematica 1.2, except that Mathematica's
18578@code{arctan} cut is always in the right half of the complex plane,
18579and its @code{arctanh} cut is always in the top half of the plane.
18580Calc's cuts are continuous with quadrants I and III for @code{arctan},
18581or II and IV for @code{arctanh}.
18582
18583Note: The current implementations of these functions with complex arguments
18584are designed with proper behavior around the branch cuts in mind, @emph{not}
18585efficiency or accuracy. You may need to increase the floating precision
18586and wait a while to get suitable answers from them.
18587
18588For @samp{sqrt(a+bi)}: When @expr{a<0} and @expr{b} is small but positive
18589or zero, the result is close to the @expr{+i} axis. For @expr{b} small and
18590negative, the result is close to the @expr{-i} axis. The result always lies
18591in the right half of the complex plane.
18592
18593For @samp{ln(a+bi)}: The real part is defined as @samp{ln(abs(a+bi))}.
18594The imaginary part is defined as @samp{arg(a+bi) = arctan2(b,a)}.
18595Thus the branch cuts for @code{sqrt} and @code{ln} both lie on the
18596negative real axis.
18597
18598The following table describes these branch cuts in another way.
18599If the real and imaginary parts of @expr{z} are as shown, then
18600the real and imaginary parts of @expr{f(z)} will be as shown.
18601Here @code{eps} stands for a small positive value; each
18602occurrence of @code{eps} may stand for a different small value.
18603
18604@smallexample
18605 z sqrt(z) ln(z)
18606----------------------------------------
18607 +, 0 +, 0 any, 0
18608 -, 0 0, + any, pi
18609 -, +eps +eps, + +eps, +
18610 -, -eps +eps, - +eps, -
18611@end smallexample
18612
18613For @samp{z1^z2}: This is defined by @samp{exp(ln(z1)*z2)}.
18614One interesting consequence of this is that @samp{(-8)^1:3} does
18615not evaluate to @mathit{-2} as you might expect, but to the complex
18616number @expr{(1., 1.732)}. Both of these are valid cube roots
18617of @mathit{-8} (as is @expr{(1., -1.732)}); Calc chooses a perhaps
18618less-obvious root for the sake of mathematical consistency.
18619
18620For @samp{arcsin(z)}: This is defined by @samp{-i*ln(i*z + sqrt(1-z^2))}.
18621The branch cuts are on the real axis, less than @mathit{-1} and greater than 1.
18622
18623For @samp{arccos(z)}: This is defined by @samp{-i*ln(z + i*sqrt(1-z^2))},
18624or equivalently by @samp{pi/2 - arcsin(z)}. The branch cuts are on
18625the real axis, less than @mathit{-1} and greater than 1.
18626
18627For @samp{arctan(z)}: This is defined by
18628@samp{(ln(1+i*z) - ln(1-i*z)) / (2*i)}. The branch cuts are on the
18629imaginary axis, below @expr{-i} and above @expr{i}.
18630
18631For @samp{arcsinh(z)}: This is defined by @samp{ln(z + sqrt(1+z^2))}.
18632The branch cuts are on the imaginary axis, below @expr{-i} and
18633above @expr{i}.
18634
18635For @samp{arccosh(z)}: This is defined by
18636@samp{ln(z + (z+1)*sqrt((z-1)/(z+1)))}. The branch cut is on the
18637real axis less than 1.
18638
18639For @samp{arctanh(z)}: This is defined by @samp{(ln(1+z) - ln(1-z)) / 2}.
18640The branch cuts are on the real axis, less than @mathit{-1} and greater than 1.
18641
18642The following tables for @code{arcsin}, @code{arccos}, and
18643@code{arctan} assume the current angular mode is Radians. The
18644hyperbolic functions operate independently of the angular mode.
18645
18646@smallexample
18647 z arcsin(z) arccos(z)
18648-------------------------------------------------------
18649 (-1..1), 0 (-pi/2..pi/2), 0 (0..pi), 0
18650 (-1..1), +eps (-pi/2..pi/2), +eps (0..pi), -eps
18651 (-1..1), -eps (-pi/2..pi/2), -eps (0..pi), +eps
18652 <-1, 0 -pi/2, + pi, -
18653 <-1, +eps -pi/2 + eps, + pi - eps, -
18654 <-1, -eps -pi/2 + eps, - pi - eps, +
18655 >1, 0 pi/2, - 0, +
18656 >1, +eps pi/2 - eps, + +eps, -
18657 >1, -eps pi/2 - eps, - +eps, +
18658@end smallexample
18659
18660@smallexample
18661 z arccosh(z) arctanh(z)
18662-----------------------------------------------------
18663 (-1..1), 0 0, (0..pi) any, 0
18664 (-1..1), +eps +eps, (0..pi) any, +eps
18665 (-1..1), -eps +eps, (-pi..0) any, -eps
18666 <-1, 0 +, pi -, pi/2
18667 <-1, +eps +, pi - eps -, pi/2 - eps
18668 <-1, -eps +, -pi + eps -, -pi/2 + eps
18669 >1, 0 +, 0 +, -pi/2
18670 >1, +eps +, +eps +, pi/2 - eps
18671 >1, -eps +, -eps +, -pi/2 + eps
18672@end smallexample
18673
18674@smallexample
18675 z arcsinh(z) arctan(z)
18676-----------------------------------------------------
18677 0, (-1..1) 0, (-pi/2..pi/2) 0, any
18678 0, <-1 -, -pi/2 -pi/2, -
18679 +eps, <-1 +, -pi/2 + eps pi/2 - eps, -
18680 -eps, <-1 -, -pi/2 + eps -pi/2 + eps, -
18681 0, >1 +, pi/2 pi/2, +
18682 +eps, >1 +, pi/2 - eps pi/2 - eps, +
18683 -eps, >1 -, pi/2 - eps -pi/2 + eps, +
18684@end smallexample
18685
18686Finally, the following identities help to illustrate the relationship
18687between the complex trigonometric and hyperbolic functions. They
18688are valid everywhere, including on the branch cuts.
18689
18690@smallexample
18691sin(i*z) = i*sinh(z) arcsin(i*z) = i*arcsinh(z)
18692cos(i*z) = cosh(z) arcsinh(i*z) = i*arcsin(z)
18693tan(i*z) = i*tanh(z) arctan(i*z) = i*arctanh(z)
18694sinh(i*z) = i*sin(z) cosh(i*z) = cos(z)
18695@end smallexample
18696
18697The ``advanced math'' functions (gamma, Bessel, etc.@:) are also defined
18698for general complex arguments, but their branch cuts and principal values
18699are not rigorously specified at present.
18700
18701@node Random Numbers, Combinatorial Functions, Branch Cuts, Scientific Functions
18702@section Random Numbers
18703
18704@noindent
18705@kindex k r
18706@pindex calc-random
18707@tindex random
18708The @kbd{k r} (@code{calc-random}) [@code{random}] command produces
18709random numbers of various sorts.
18710
18711Given a positive numeric prefix argument @expr{M}, it produces a random
18712integer @expr{N} in the range
18713@texline @math{0 \le N < M}.
18714@infoline @expr{0 <= N < M}.
f10d0e80 18715Each possible value @expr{N} appears with equal probability.
4009494e
GM
18716
18717With no numeric prefix argument, the @kbd{k r} command takes its argument
18718from the stack instead. Once again, if this is a positive integer @expr{M}
18719the result is a random integer less than @expr{M}. However, note that
18720while numeric prefix arguments are limited to six digits or so, an @expr{M}
18721taken from the stack can be arbitrarily large. If @expr{M} is negative,
18722the result is a random integer in the range
18723@texline @math{M < N \le 0}.
18724@infoline @expr{M < N <= 0}.
18725
18726If the value on the stack is a floating-point number @expr{M}, the result
18727is a random floating-point number @expr{N} in the range
18728@texline @math{0 \le N < M}
18729@infoline @expr{0 <= N < M}
18730or
18731@texline @math{M < N \le 0},
18732@infoline @expr{M < N <= 0},
18733according to the sign of @expr{M}.
18734
18735If @expr{M} is zero, the result is a Gaussian-distributed random real
18736number; the distribution has a mean of zero and a standard deviation
18737of one. The algorithm used generates random numbers in pairs; thus,
18738every other call to this function will be especially fast.
18739
18740If @expr{M} is an error form
18741@texline @math{m} @code{+/-} @math{\sigma}
18742@infoline @samp{m +/- s}
18743where @var{m} and
18744@texline @math{\sigma}
18745@infoline @var{s}
18746are both real numbers, the result uses a Gaussian distribution with mean
18747@var{m} and standard deviation
18748@texline @math{\sigma}.
18749@infoline @var{s}.
18750
18751If @expr{M} is an interval form, the lower and upper bounds specify the
18752acceptable limits of the random numbers. If both bounds are integers,
18753the result is a random integer in the specified range. If either bound
18754is floating-point, the result is a random real number in the specified
18755range. If the interval is open at either end, the result will be sure
18756not to equal that end value. (This makes a big difference for integer
18757intervals, but for floating-point intervals it's relatively minor:
18758with a precision of 6, @samp{random([1.0..2.0))} will return any of one
18759million numbers from 1.00000 to 1.99999; @samp{random([1.0..2.0])} may
18760additionally return 2.00000, but the probability of this happening is
18761extremely small.)
18762
18763If @expr{M} is a vector, the result is one element taken at random from
18764the vector. All elements of the vector are given equal probabilities.
18765
18766@vindex RandSeed
18767The sequence of numbers produced by @kbd{k r} is completely random by
18768default, i.e., the sequence is seeded each time you start Calc using
18769the current time and other information. You can get a reproducible
18770sequence by storing a particular ``seed value'' in the Calc variable
18771@code{RandSeed}. Any integer will do for a seed; integers of from 1
18772to 12 digits are good. If you later store a different integer into
18773@code{RandSeed}, Calc will switch to a different pseudo-random
18774sequence. If you ``unstore'' @code{RandSeed}, Calc will re-seed itself
18775from the current time. If you store the same integer that you used
18776before back into @code{RandSeed}, you will get the exact same sequence
18777of random numbers as before.
18778
18779@pindex calc-rrandom
18780The @code{calc-rrandom} command (not on any key) produces a random real
18781number between zero and one. It is equivalent to @samp{random(1.0)}.
18782
18783@kindex k a
18784@pindex calc-random-again
18785The @kbd{k a} (@code{calc-random-again}) command produces another random
18786number, re-using the most recent value of @expr{M}. With a numeric
18787prefix argument @var{n}, it produces @var{n} more random numbers using
18788that value of @expr{M}.
18789
18790@kindex k h
18791@pindex calc-shuffle
18792@tindex shuffle
18793The @kbd{k h} (@code{calc-shuffle}) command produces a vector of several
18794random values with no duplicates. The value on the top of the stack
18795specifies the set from which the random values are drawn, and may be any
18796of the @expr{M} formats described above. The numeric prefix argument
18797gives the length of the desired list. (If you do not provide a numeric
18798prefix argument, the length of the list is taken from the top of the
18799stack, and @expr{M} from second-to-top.)
18800
18801If @expr{M} is a floating-point number, zero, or an error form (so
18802that the random values are being drawn from the set of real numbers)
18803there is little practical difference between using @kbd{k h} and using
18804@kbd{k r} several times. But if the set of possible values consists
18805of just a few integers, or the elements of a vector, then there is
18806a very real chance that multiple @kbd{k r}'s will produce the same
18807number more than once. The @kbd{k h} command produces a vector whose
18808elements are always distinct. (Actually, there is a slight exception:
18809If @expr{M} is a vector, no given vector element will be drawn more
18810than once, but if several elements of @expr{M} are equal, they may
18811each make it into the result vector.)
18812
18813One use of @kbd{k h} is to rearrange a list at random. This happens
18814if the prefix argument is equal to the number of values in the list:
18815@kbd{[1, 1.5, 2, 2.5, 3] 5 k h} might produce the permuted list
18816@samp{[2.5, 1, 1.5, 3, 2]}. As a convenient feature, if the argument
18817@var{n} is negative it is replaced by the size of the set represented
18818by @expr{M}. Naturally, this is allowed only when @expr{M} specifies
18819a small discrete set of possibilities.
18820
18821To do the equivalent of @kbd{k h} but with duplications allowed,
18822given @expr{M} on the stack and with @var{n} just entered as a numeric
18823prefix, use @kbd{v b} to build a vector of copies of @expr{M}, then use
18824@kbd{V M k r} to ``map'' the normal @kbd{k r} function over the
18825elements of this vector. @xref{Matrix Functions}.
18826
18827@menu
18828* Random Number Generator:: (Complete description of Calc's algorithm)
18829@end menu
18830
18831@node Random Number Generator, , Random Numbers, Random Numbers
18832@subsection Random Number Generator
18833
18834Calc's random number generator uses several methods to ensure that
18835the numbers it produces are highly random. Knuth's @emph{Art of
18836Computer Programming}, Volume II, contains a thorough description
18837of the theory of random number generators and their measurement and
18838characterization.
18839
18840If @code{RandSeed} has no stored value, Calc calls Emacs' built-in
18841@code{random} function to get a stream of random numbers, which it
18842then treats in various ways to avoid problems inherent in the simple
18843random number generators that many systems use to implement @code{random}.
18844
18845When Calc's random number generator is first invoked, it ``seeds''
18846the low-level random sequence using the time of day, so that the
18847random number sequence will be different every time you use Calc.
18848
18849Since Emacs Lisp doesn't specify the range of values that will be
18850returned by its @code{random} function, Calc exercises the function
18851several times to estimate the range. When Calc subsequently uses
18852the @code{random} function, it takes only 10 bits of the result
18853near the most-significant end. (It avoids at least the bottom
18854four bits, preferably more, and also tries to avoid the top two
18855bits.) This strategy works well with the linear congruential
18856generators that are typically used to implement @code{random}.
18857
18858If @code{RandSeed} contains an integer, Calc uses this integer to
18859seed an ``additive congruential'' method (Knuth's algorithm 3.2.2A,
18860computing
18861@texline @math{X_{n-55} - X_{n-24}}.
18862@infoline @expr{X_n-55 - X_n-24}).
18863This method expands the seed
18864value into a large table which is maintained internally; the variable
18865@code{RandSeed} is changed from, e.g., 42 to the vector @expr{[42]}
18866to indicate that the seed has been absorbed into this table. When
18867@code{RandSeed} contains a vector, @kbd{k r} and related commands
18868continue to use the same internal table as last time. There is no
18869way to extract the complete state of the random number generator
18870so that you can restart it from any point; you can only restart it
18871from the same initial seed value. A simple way to restart from the
18872same seed is to type @kbd{s r RandSeed} to get the seed vector,
18873@kbd{v u} to unpack it back into a number, then @kbd{s t RandSeed}
18874to reseed the generator with that number.
18875
18876Calc uses a ``shuffling'' method as described in algorithm 3.2.2B
18877of Knuth. It fills a table with 13 random 10-bit numbers. Then,
18878to generate a new random number, it uses the previous number to
18879index into the table, picks the value it finds there as the new
18880random number, then replaces that table entry with a new value
18881obtained from a call to the base random number generator (either
18882the additive congruential generator or the @code{random} function
18883supplied by the system). If there are any flaws in the base
18884generator, shuffling will tend to even them out. But if the system
18885provides an excellent @code{random} function, shuffling will not
18886damage its randomness.
18887
18888To create a random integer of a certain number of digits, Calc
18889builds the integer three decimal digits at a time. For each group
18890of three digits, Calc calls its 10-bit shuffling random number generator
18891(which returns a value from 0 to 1023); if the random value is 1000
18892or more, Calc throws it out and tries again until it gets a suitable
18893value.
18894
18895To create a random floating-point number with precision @var{p}, Calc
18896simply creates a random @var{p}-digit integer and multiplies by
18897@texline @math{10^{-p}}.
18898@infoline @expr{10^-p}.
18899The resulting random numbers should be very clean, but note
18900that relatively small numbers will have few significant random digits.
18901In other words, with a precision of 12, you will occasionally get
18902numbers on the order of
18903@texline @math{10^{-9}}
18904@infoline @expr{10^-9}
18905or
18906@texline @math{10^{-10}},
18907@infoline @expr{10^-10},
18908but those numbers will only have two or three random digits since they
18909correspond to small integers times
18910@texline @math{10^{-12}}.
18911@infoline @expr{10^-12}.
18912
18913To create a random integer in the interval @samp{[0 .. @var{m})}, Calc
18914counts the digits in @var{m}, creates a random integer with three
18915additional digits, then reduces modulo @var{m}. Unless @var{m} is a
18916power of ten the resulting values will be very slightly biased toward
18917the lower numbers, but this bias will be less than 0.1%. (For example,
18918if @var{m} is 42, Calc will reduce a random integer less than 100000
18919modulo 42 to get a result less than 42. It is easy to show that the
18920numbers 40 and 41 will be only 2380/2381 as likely to result from this
18921modulo operation as numbers 39 and below.) If @var{m} is a power of
18922ten, however, the numbers should be completely unbiased.
18923
18924The Gaussian random numbers generated by @samp{random(0.0)} use the
18925``polar'' method described in Knuth section 3.4.1C. This method
18926generates a pair of Gaussian random numbers at a time, so only every
18927other call to @samp{random(0.0)} will require significant calculations.
18928
18929@node Combinatorial Functions, Probability Distribution Functions, Random Numbers, Scientific Functions
18930@section Combinatorial Functions
18931
18932@noindent
18933Commands relating to combinatorics and number theory begin with the
18934@kbd{k} key prefix.
18935
18936@kindex k g
18937@pindex calc-gcd
18938@tindex gcd
18939The @kbd{k g} (@code{calc-gcd}) [@code{gcd}] command computes the
18940Greatest Common Divisor of two integers. It also accepts fractions;
18941the GCD of two fractions is defined by taking the GCD of the
18942numerators, and the LCM of the denominators. This definition is
18943consistent with the idea that @samp{a / gcd(a,x)} should yield an
18944integer for any @samp{a} and @samp{x}. For other types of arguments,
18945the operation is left in symbolic form.
18946
18947@kindex k l
18948@pindex calc-lcm
18949@tindex lcm
18950The @kbd{k l} (@code{calc-lcm}) [@code{lcm}] command computes the
18951Least Common Multiple of two integers or fractions. The product of
18952the LCM and GCD of two numbers is equal to the product of the
18953numbers.
18954
18955@kindex k E
18956@pindex calc-extended-gcd
18957@tindex egcd
18958The @kbd{k E} (@code{calc-extended-gcd}) [@code{egcd}] command computes
18959the GCD of two integers @expr{x} and @expr{y} and returns a vector
18960@expr{[g, a, b]} where
18961@texline @math{g = \gcd(x,y) = a x + b y}.
18962@infoline @expr{g = gcd(x,y) = a x + b y}.
18963
18964@kindex !
18965@pindex calc-factorial
18966@tindex fact
18967@ignore
18968@mindex @null
18969@end ignore
18970@tindex !
18971The @kbd{!} (@code{calc-factorial}) [@code{fact}] command computes the
18972factorial of the number at the top of the stack. If the number is an
18973integer, the result is an exact integer. If the number is an
18974integer-valued float, the result is a floating-point approximation. If
18975the number is a non-integral real number, the generalized factorial is used,
18976as defined by the Euler Gamma function. Please note that computation of
18977large factorials can be slow; using floating-point format will help
18978since fewer digits must be maintained. The same is true of many of
18979the commands in this section.
18980
18981@kindex k d
18982@pindex calc-double-factorial
18983@tindex dfact
18984@ignore
18985@mindex @null
18986@end ignore
18987@tindex !!
18988The @kbd{k d} (@code{calc-double-factorial}) [@code{dfact}] command
18989computes the ``double factorial'' of an integer. For an even integer,
18990this is the product of even integers from 2 to @expr{N}. For an odd
18991integer, this is the product of odd integers from 3 to @expr{N}. If
18992the argument is an integer-valued float, the result is a floating-point
18993approximation. This function is undefined for negative even integers.
18994The notation @expr{N!!} is also recognized for double factorials.
18995
18996@kindex k c
18997@pindex calc-choose
18998@tindex choose
18999The @kbd{k c} (@code{calc-choose}) [@code{choose}] command computes the
19000binomial coefficient @expr{N}-choose-@expr{M}, where @expr{M} is the number
19001on the top of the stack and @expr{N} is second-to-top. If both arguments
19002are integers, the result is an exact integer. Otherwise, the result is a
19003floating-point approximation. The binomial coefficient is defined for all
19004real numbers by
19005@texline @math{N! \over M! (N-M)!\,}.
19006@infoline @expr{N! / M! (N-M)!}.
19007
19008@kindex H k c
19009@pindex calc-perm
19010@tindex perm
19011@ifnottex
19012The @kbd{H k c} (@code{calc-perm}) [@code{perm}] command computes the
19013number-of-permutations function @expr{N! / (N-M)!}.
19014@end ifnottex
19015@tex
19016The \kbd{H k c} (\code{calc-perm}) [\code{perm}] command computes the
19017number-of-perm\-utations function $N! \over (N-M)!\,$.
19018@end tex
19019
19020@kindex k b
19021@kindex H k b
19022@pindex calc-bernoulli-number
19023@tindex bern
19024The @kbd{k b} (@code{calc-bernoulli-number}) [@code{bern}] command
19025computes a given Bernoulli number. The value at the top of the stack
19026is a nonnegative integer @expr{n} that specifies which Bernoulli number
19027is desired. The @kbd{H k b} command computes a Bernoulli polynomial,
19028taking @expr{n} from the second-to-top position and @expr{x} from the
19029top of the stack. If @expr{x} is a variable or formula the result is
19030a polynomial in @expr{x}; if @expr{x} is a number the result is a number.
19031
19032@kindex k e
19033@kindex H k e
19034@pindex calc-euler-number
19035@tindex euler
19036The @kbd{k e} (@code{calc-euler-number}) [@code{euler}] command similarly
19037computes an Euler number, and @w{@kbd{H k e}} computes an Euler polynomial.
19038Bernoulli and Euler numbers occur in the Taylor expansions of several
19039functions.
19040
19041@kindex k s
19042@kindex H k s
19043@pindex calc-stirling-number
19044@tindex stir1
19045@tindex stir2
19046The @kbd{k s} (@code{calc-stirling-number}) [@code{stir1}] command
19047computes a Stirling number of the first
19048@texline kind@tie{}@math{n \brack m},
19049@infoline kind,
19050given two integers @expr{n} and @expr{m} on the stack. The @kbd{H k s}
19051[@code{stir2}] command computes a Stirling number of the second
19052@texline kind@tie{}@math{n \brace m}.
19053@infoline kind.
19054These are the number of @expr{m}-cycle permutations of @expr{n} objects,
19055and the number of ways to partition @expr{n} objects into @expr{m}
19056non-empty sets, respectively.
19057
19058@kindex k p
19059@pindex calc-prime-test
19060@cindex Primes
19061The @kbd{k p} (@code{calc-prime-test}) command checks if the integer on
19062the top of the stack is prime. For integers less than eight million, the
19063answer is always exact and reasonably fast. For larger integers, a
19064probabilistic method is used (see Knuth vol. II, section 4.5.4, algorithm P).
19065The number is first checked against small prime factors (up to 13). Then,
19066any number of iterations of the algorithm are performed. Each step either
19067discovers that the number is non-prime, or substantially increases the
19068certainty that the number is prime. After a few steps, the chance that
19069a number was mistakenly described as prime will be less than one percent.
19070(Indeed, this is a worst-case estimate of the probability; in practice
19071even a single iteration is quite reliable.) After the @kbd{k p} command,
19072the number will be reported as definitely prime or non-prime if possible,
19073or otherwise ``probably'' prime with a certain probability of error.
19074
19075@ignore
19076@starindex
19077@end ignore
19078@tindex prime
19079The normal @kbd{k p} command performs one iteration of the primality
19080test. Pressing @kbd{k p} repeatedly for the same integer will perform
19081additional iterations. Also, @kbd{k p} with a numeric prefix performs
19082the specified number of iterations. There is also an algebraic function
19083@samp{prime(n)} or @samp{prime(n,iters)} which returns 1 if @expr{n}
19084is (probably) prime and 0 if not.
19085
19086@kindex k f
19087@pindex calc-prime-factors
19088@tindex prfac
19089The @kbd{k f} (@code{calc-prime-factors}) [@code{prfac}] command
19090attempts to decompose an integer into its prime factors. For numbers up
19091to 25 million, the answer is exact although it may take some time. The
19092result is a vector of the prime factors in increasing order. For larger
19093inputs, prime factors above 5000 may not be found, in which case the
19094last number in the vector will be an unfactored integer greater than 25
19095million (with a warning message). For negative integers, the first
19096element of the list will be @mathit{-1}. For inputs @mathit{-1}, @mathit{0}, and
19097@mathit{1}, the result is a list of the same number.
19098
19099@kindex k n
19100@pindex calc-next-prime
19101@ignore
19102@mindex nextpr@idots
19103@end ignore
19104@tindex nextprime
19105The @kbd{k n} (@code{calc-next-prime}) [@code{nextprime}] command finds
19106the next prime above a given number. Essentially, it searches by calling
19107@code{calc-prime-test} on successive integers until it finds one that
19108passes the test. This is quite fast for integers less than eight million,
19109but once the probabilistic test comes into play the search may be rather
19110slow. Ordinarily this command stops for any prime that passes one iteration
19111of the primality test. With a numeric prefix argument, a number must pass
19112the specified number of iterations before the search stops. (This only
19113matters when searching above eight million.) You can always use additional
19114@kbd{k p} commands to increase your certainty that the number is indeed
19115prime.
19116
19117@kindex I k n
19118@pindex calc-prev-prime
19119@ignore
19120@mindex prevpr@idots
19121@end ignore
19122@tindex prevprime
19123The @kbd{I k n} (@code{calc-prev-prime}) [@code{prevprime}] command
19124analogously finds the next prime less than a given number.
19125
19126@kindex k t
19127@pindex calc-totient
19128@tindex totient
19129The @kbd{k t} (@code{calc-totient}) [@code{totient}] command computes the
19130Euler ``totient''
19131@texline function@tie{}@math{\phi(n)},
19132@infoline function,
19133the number of integers less than @expr{n} which
19134are relatively prime to @expr{n}.
19135
19136@kindex k m
19137@pindex calc-moebius
19138@tindex moebius
19139The @kbd{k m} (@code{calc-moebius}) [@code{moebius}] command computes the
19140@texline M@"obius @math{\mu}
19141@infoline Moebius ``mu''
19142function. If the input number is a product of @expr{k}
19143distinct factors, this is @expr{(-1)^k}. If the input number has any
19144duplicate factors (i.e., can be divided by the same prime more than once),
19145the result is zero.
19146
19147@node Probability Distribution Functions, , Combinatorial Functions, Scientific Functions
19148@section Probability Distribution Functions
19149
19150@noindent
19151The functions in this section compute various probability distributions.
19152For continuous distributions, this is the integral of the probability
19153density function from @expr{x} to infinity. (These are the ``upper
19154tail'' distribution functions; there are also corresponding ``lower
19155tail'' functions which integrate from minus infinity to @expr{x}.)
19156For discrete distributions, the upper tail function gives the sum
19157from @expr{x} to infinity; the lower tail function gives the sum
19158from minus infinity up to, but not including,@w{ }@expr{x}.
19159
19160To integrate from @expr{x} to @expr{y}, just use the distribution
19161function twice and subtract. For example, the probability that a
19162Gaussian random variable with mean 2 and standard deviation 1 will
19163lie in the range from 2.5 to 2.8 is @samp{utpn(2.5,2,1) - utpn(2.8,2,1)}
19164(``the probability that it is greater than 2.5, but not greater than 2.8''),
19165or equivalently @samp{ltpn(2.8,2,1) - ltpn(2.5,2,1)}.
19166
19167@kindex k B
19168@kindex I k B
19169@pindex calc-utpb
19170@tindex utpb
19171@tindex ltpb
19172The @kbd{k B} (@code{calc-utpb}) [@code{utpb}] function uses the
19173binomial distribution. Push the parameters @var{n}, @var{p}, and
19174then @var{x} onto the stack; the result (@samp{utpb(x,n,p)}) is the
19175probability that an event will occur @var{x} or more times out
19176of @var{n} trials, if its probability of occurring in any given
19177trial is @var{p}. The @kbd{I k B} [@code{ltpb}] function is
19178the probability that the event will occur fewer than @var{x} times.
19179
19180The other probability distribution functions similarly take the
19181form @kbd{k @var{X}} (@code{calc-utp@var{x}}) [@code{utp@var{x}}]
19182and @kbd{I k @var{X}} [@code{ltp@var{x}}], for various letters
19183@var{x}. The arguments to the algebraic functions are the value of
19184the random variable first, then whatever other parameters define the
19185distribution. Note these are among the few Calc functions where the
19186order of the arguments in algebraic form differs from the order of
19187arguments as found on the stack. (The random variable comes last on
19188the stack, so that you can type, e.g., @kbd{2 @key{RET} 1 @key{RET} 2.5
19189k N M-@key{RET} @key{DEL} 2.8 k N -}, using @kbd{M-@key{RET} @key{DEL}} to
19190recover the original arguments but substitute a new value for @expr{x}.)
19191
19192@kindex k C
19193@pindex calc-utpc
19194@tindex utpc
19195@ignore
19196@mindex @idots
19197@end ignore
19198@kindex I k C
19199@ignore
19200@mindex @null
19201@end ignore
19202@tindex ltpc
19203The @samp{utpc(x,v)} function uses the chi-square distribution with
19204@texline @math{\nu}
19205@infoline @expr{v}
19206degrees of freedom. It is the probability that a model is
19207correct if its chi-square statistic is @expr{x}.
19208
19209@kindex k F
19210@pindex calc-utpf
19211@tindex utpf
19212@ignore
19213@mindex @idots
19214@end ignore
19215@kindex I k F
19216@ignore
19217@mindex @null
19218@end ignore
19219@tindex ltpf
19220The @samp{utpf(F,v1,v2)} function uses the F distribution, used in
19221various statistical tests. The parameters
19222@texline @math{\nu_1}
19223@infoline @expr{v1}
19224and
19225@texline @math{\nu_2}
19226@infoline @expr{v2}
19227are the degrees of freedom in the numerator and denominator,
19228respectively, used in computing the statistic @expr{F}.
19229
19230@kindex k N
19231@pindex calc-utpn
19232@tindex utpn
19233@ignore
19234@mindex @idots
19235@end ignore
19236@kindex I k N
19237@ignore
19238@mindex @null
19239@end ignore
19240@tindex ltpn
19241The @samp{utpn(x,m,s)} function uses a normal (Gaussian) distribution
19242with mean @expr{m} and standard deviation
19243@texline @math{\sigma}.
19244@infoline @expr{s}.
19245It is the probability that such a normal-distributed random variable
19246would exceed @expr{x}.
19247
19248@kindex k P
19249@pindex calc-utpp
19250@tindex utpp
19251@ignore
19252@mindex @idots
19253@end ignore
19254@kindex I k P
19255@ignore
19256@mindex @null
19257@end ignore
19258@tindex ltpp
19259The @samp{utpp(n,x)} function uses a Poisson distribution with
19260mean @expr{x}. It is the probability that @expr{n} or more such
19261Poisson random events will occur.
19262
19263@kindex k T
19264@pindex calc-ltpt
19265@tindex utpt
19266@ignore
19267@mindex @idots
19268@end ignore
19269@kindex I k T
19270@ignore
19271@mindex @null
19272@end ignore
19273@tindex ltpt
19274The @samp{utpt(t,v)} function uses the Student's ``t'' distribution
19275with
19276@texline @math{\nu}
19277@infoline @expr{v}
19278degrees of freedom. It is the probability that a
19279t-distributed random variable will be greater than @expr{t}.
19280(Note: This computes the distribution function
19281@texline @math{A(t|\nu)}
19282@infoline @expr{A(t|v)}
19283where
19284@texline @math{A(0|\nu) = 1}
19285@infoline @expr{A(0|v) = 1}
19286and
19287@texline @math{A(\infty|\nu) \to 0}.
19288@infoline @expr{A(inf|v) -> 0}.
19289The @code{UTPT} operation on the HP-48 uses a different definition which
19290returns half of Calc's value: @samp{UTPT(t,v) = .5*utpt(t,v)}.)
19291
19292While Calc does not provide inverses of the probability distribution
19293functions, the @kbd{a R} command can be used to solve for the inverse.
19294Since the distribution functions are monotonic, @kbd{a R} is guaranteed
19295to be able to find a solution given any initial guess.
19296@xref{Numerical Solutions}.
19297
19298@node Matrix Functions, Algebra, Scientific Functions, Top
19299@chapter Vector/Matrix Functions
19300
19301@noindent
19302Many of the commands described here begin with the @kbd{v} prefix.
19303(For convenience, the shift-@kbd{V} prefix is equivalent to @kbd{v}.)
19304The commands usually apply to both plain vectors and matrices; some
19305apply only to matrices or only to square matrices. If the argument
19306has the wrong dimensions the operation is left in symbolic form.
19307
19308Vectors are entered and displayed using @samp{[a,b,c]} notation.
19309Matrices are vectors of which all elements are vectors of equal length.
19310(Though none of the standard Calc commands use this concept, a
19311three-dimensional matrix or rank-3 tensor could be defined as a
19312vector of matrices, and so on.)
19313
19314@menu
19315* Packing and Unpacking::
19316* Building Vectors::
19317* Extracting Elements::
19318* Manipulating Vectors::
19319* Vector and Matrix Arithmetic::
19320* Set Operations::
19321* Statistical Operations::
19322* Reducing and Mapping::
19323* Vector and Matrix Formats::
19324@end menu
19325
19326@node Packing and Unpacking, Building Vectors, Matrix Functions, Matrix Functions
19327@section Packing and Unpacking
19328
19329@noindent
19330Calc's ``pack'' and ``unpack'' commands collect stack entries to build
19331composite objects such as vectors and complex numbers. They are
19332described in this chapter because they are most often used to build
19333vectors.
19334
19335@kindex v p
19336@pindex calc-pack
19337The @kbd{v p} (@code{calc-pack}) [@code{pack}] command collects several
19338elements from the stack into a matrix, complex number, HMS form, error
19339form, etc. It uses a numeric prefix argument to specify the kind of
19340object to be built; this argument is referred to as the ``packing mode.''
19341If the packing mode is a nonnegative integer, a vector of that
19342length is created. For example, @kbd{C-u 5 v p} will pop the top
19343five stack elements and push back a single vector of those five
19344elements. (@kbd{C-u 0 v p} simply creates an empty vector.)
19345
19346The same effect can be had by pressing @kbd{[} to push an incomplete
19347vector on the stack, using @key{TAB} (@code{calc-roll-down}) to sneak
19348the incomplete object up past a certain number of elements, and
19349then pressing @kbd{]} to complete the vector.
19350
19351Negative packing modes create other kinds of composite objects:
19352
19353@table @cite
19354@item -1
19355Two values are collected to build a complex number. For example,
19356@kbd{5 @key{RET} 7 C-u -1 v p} creates the complex number
19357@expr{(5, 7)}. The result is always a rectangular complex
19358number. The two input values must both be real numbers,
19359i.e., integers, fractions, or floats. If they are not, Calc
19360will instead build a formula like @samp{a + (0, 1) b}. (The
19361other packing modes also create a symbolic answer if the
19362components are not suitable.)
19363
19364@item -2
19365Two values are collected to build a polar complex number.
19366The first is the magnitude; the second is the phase expressed
19367in either degrees or radians according to the current angular
19368mode.
19369
19370@item -3
19371Three values are collected into an HMS form. The first
19372two values (hours and minutes) must be integers or
19373integer-valued floats. The third value may be any real
19374number.
19375
19376@item -4
19377Two values are collected into an error form. The inputs
19378may be real numbers or formulas.
19379
19380@item -5
19381Two values are collected into a modulo form. The inputs
19382must be real numbers.
19383
19384@item -6
19385Two values are collected into the interval @samp{[a .. b]}.
19386The inputs may be real numbers, HMS or date forms, or formulas.
19387
19388@item -7
19389Two values are collected into the interval @samp{[a .. b)}.
19390
19391@item -8
19392Two values are collected into the interval @samp{(a .. b]}.
19393
19394@item -9
19395Two values are collected into the interval @samp{(a .. b)}.
19396
19397@item -10
19398Two integer values are collected into a fraction.
19399
19400@item -11
19401Two values are collected into a floating-point number.
19402The first is the mantissa; the second, which must be an
19403integer, is the exponent. The result is the mantissa
19404times ten to the power of the exponent.
19405
19406@item -12
19407This is treated the same as @mathit{-11} by the @kbd{v p} command.
19408When unpacking, @mathit{-12} specifies that a floating-point mantissa
19409is desired.
19410
19411@item -13
19412A real number is converted into a date form.
19413
19414@item -14
19415Three numbers (year, month, day) are packed into a pure date form.
19416
19417@item -15
19418Six numbers are packed into a date/time form.
19419@end table
19420
19421With any of the two-input negative packing modes, either or both
19422of the inputs may be vectors. If both are vectors of the same
19423length, the result is another vector made by packing corresponding
19424elements of the input vectors. If one input is a vector and the
19425other is a plain number, the number is packed along with each vector
19426element to produce a new vector. For example, @kbd{C-u -4 v p}
19427could be used to convert a vector of numbers and a vector of errors
19428into a single vector of error forms; @kbd{C-u -5 v p} could convert
19429a vector of numbers and a single number @var{M} into a vector of
19430numbers modulo @var{M}.
19431
19432If you don't give a prefix argument to @kbd{v p}, it takes
19433the packing mode from the top of the stack. The elements to
19434be packed then begin at stack level 2. Thus
19435@kbd{1 @key{RET} 2 @key{RET} 4 n v p} is another way to
19436enter the error form @samp{1 +/- 2}.
19437
19438If the packing mode taken from the stack is a vector, the result is a
19439matrix with the dimensions specified by the elements of the vector,
19440which must each be integers. For example, if the packing mode is
19441@samp{[2, 3]}, then six numbers will be taken from the stack and
19442returned in the form @samp{[@w{[a, b, c]}, [d, e, f]]}.
19443
19444If any elements of the vector are negative, other kinds of
19445packing are done at that level as described above. For
19446example, @samp{[2, 3, -4]} takes 12 objects and creates a
19447@texline @math{2\times3}
19448@infoline 2x3
19449matrix of error forms: @samp{[[a +/- b, c +/- d ... ]]}.
19450Also, @samp{[-4, -10]} will convert four integers into an
19451error form consisting of two fractions: @samp{a:b +/- c:d}.
19452
19453@ignore
19454@starindex
19455@end ignore
19456@tindex pack
19457There is an equivalent algebraic function,
19458@samp{pack(@var{mode}, @var{items})} where @var{mode} is a
19459packing mode (an integer or a vector of integers) and @var{items}
19460is a vector of objects to be packed (re-packed, really) according
19461to that mode. For example, @samp{pack([3, -4], [a,b,c,d,e,f])}
19462yields @samp{[a +/- b, @w{c +/- d}, e +/- f]}. The function is
19463left in symbolic form if the packing mode is invalid, or if the
19464number of data items does not match the number of items required
19465by the mode.
19466
19467@kindex v u
19468@pindex calc-unpack
19469The @kbd{v u} (@code{calc-unpack}) command takes the vector, complex
19470number, HMS form, or other composite object on the top of the stack and
19471``unpacks'' it, pushing each of its elements onto the stack as separate
19472objects. Thus, it is the ``inverse'' of @kbd{v p}. If the value
19473at the top of the stack is a formula, @kbd{v u} unpacks it by pushing
19474each of the arguments of the top-level operator onto the stack.
19475
19476You can optionally give a numeric prefix argument to @kbd{v u}
19477to specify an explicit (un)packing mode. If the packing mode is
19478negative and the input is actually a vector or matrix, the result
19479will be two or more similar vectors or matrices of the elements.
19480For example, given the vector @samp{[@w{a +/- b}, c^2, d +/- 7]},
19481the result of @kbd{C-u -4 v u} will be the two vectors
19482@samp{[a, c^2, d]} and @w{@samp{[b, 0, 7]}}.
19483
19484Note that the prefix argument can have an effect even when the input is
19485not a vector. For example, if the input is the number @mathit{-5}, then
19486@kbd{c-u -1 v u} yields @mathit{-5} and 0 (the components of @mathit{-5}
19487when viewed as a rectangular complex number); @kbd{C-u -2 v u} yields 5
19488and 180 (assuming Degrees mode); and @kbd{C-u -10 v u} yields @mathit{-5}
19489and 1 (the numerator and denominator of @mathit{-5}, viewed as a rational
19490number). Plain @kbd{v u} with this input would complain that the input
19491is not a composite object.
19492
19493Unpacking mode @mathit{-11} converts a float into an integer mantissa and
19494an integer exponent, where the mantissa is not divisible by 10
19495(except that 0.0 is represented by a mantissa and exponent of 0).
19496Unpacking mode @mathit{-12} converts a float into a floating-point mantissa
19497and integer exponent, where the mantissa (for non-zero numbers)
19498is guaranteed to lie in the range [1 .. 10). In both cases,
19499the mantissa is shifted left or right (and the exponent adjusted
19500to compensate) in order to satisfy these constraints.
19501
19502Positive unpacking modes are treated differently than for @kbd{v p}.
19503A mode of 1 is much like plain @kbd{v u} with no prefix argument,
19504except that in addition to the components of the input object,
19505a suitable packing mode to re-pack the object is also pushed.
19506Thus, @kbd{C-u 1 v u} followed by @kbd{v p} will re-build the
19507original object.
19508
19509A mode of 2 unpacks two levels of the object; the resulting
19510re-packing mode will be a vector of length 2. This might be used
19511to unpack a matrix, say, or a vector of error forms. Higher
19512unpacking modes unpack the input even more deeply.
19513
19514@ignore
19515@starindex
19516@end ignore
19517@tindex unpack
19518There are two algebraic functions analogous to @kbd{v u}.
19519The @samp{unpack(@var{mode}, @var{item})} function unpacks the
19520@var{item} using the given @var{mode}, returning the result as
19521a vector of components. Here the @var{mode} must be an
19522integer, not a vector. For example, @samp{unpack(-4, a +/- b)}
19523returns @samp{[a, b]}, as does @samp{unpack(1, a +/- b)}.
19524
19525@ignore
19526@starindex
19527@end ignore
19528@tindex unpackt
19529The @code{unpackt} function is like @code{unpack} but instead
19530of returning a simple vector of items, it returns a vector of
19531two things: The mode, and the vector of items. For example,
19532@samp{unpackt(1, 2:3 +/- 1:4)} returns @samp{[-4, [2:3, 1:4]]},
19533and @samp{unpackt(2, 2:3 +/- 1:4)} returns @samp{[[-4, -10], [2, 3, 1, 4]]}.
19534The identity for re-building the original object is
19535@samp{apply(pack, unpackt(@var{n}, @var{x})) = @var{x}}. (The
19536@code{apply} function builds a function call given the function
19537name and a vector of arguments.)
19538
19539@cindex Numerator of a fraction, extracting
19540Subscript notation is a useful way to extract a particular part
19541of an object. For example, to get the numerator of a rational
19542number, you can use @samp{unpack(-10, @var{x})_1}.
19543
19544@node Building Vectors, Extracting Elements, Packing and Unpacking, Matrix Functions
19545@section Building Vectors
19546
19547@noindent
19548Vectors and matrices can be added,
19549subtracted, multiplied, and divided; @pxref{Basic Arithmetic}.
19550
19551@kindex |
19552@pindex calc-concat
19553@ignore
19554@mindex @null
19555@end ignore
19556@tindex |
19557The @kbd{|} (@code{calc-concat}) [@code{vconcat}] command ``concatenates'' two vectors
19558into one. For example, after @kbd{@w{[ 1 , 2 ]} [ 3 , 4 ] |}, the stack
19559will contain the single vector @samp{[1, 2, 3, 4]}. If the arguments
19560are matrices, the rows of the first matrix are concatenated with the
19561rows of the second. (In other words, two matrices are just two vectors
19562of row-vectors as far as @kbd{|} is concerned.)
19563
19564If either argument to @kbd{|} is a scalar (a non-vector), it is treated
19565like a one-element vector for purposes of concatenation: @kbd{1 [ 2 , 3 ] |}
19566produces the vector @samp{[1, 2, 3]}. Likewise, if one argument is a
19567matrix and the other is a plain vector, the vector is treated as a
19568one-row matrix.
19569
19570@kindex H |
19571@tindex append
19572The @kbd{H |} (@code{calc-append}) [@code{append}] command concatenates
19573two vectors without any special cases. Both inputs must be vectors.
19574Whether or not they are matrices is not taken into account. If either
19575argument is a scalar, the @code{append} function is left in symbolic form.
19576See also @code{cons} and @code{rcons} below.
19577
19578@kindex I |
19579@kindex H I |
19580The @kbd{I |} and @kbd{H I |} commands are similar, but they use their
19581two stack arguments in the opposite order. Thus @kbd{I |} is equivalent
19582to @kbd{@key{TAB} |}, but possibly more convenient and also a bit faster.
19583
19584@kindex v d
19585@pindex calc-diag
19586@tindex diag
19587The @kbd{v d} (@code{calc-diag}) [@code{diag}] function builds a diagonal
19588square matrix. The optional numeric prefix gives the number of rows
19589and columns in the matrix. If the value at the top of the stack is a
19590vector, the elements of the vector are used as the diagonal elements; the
19591prefix, if specified, must match the size of the vector. If the value on
19592the stack is a scalar, it is used for each element on the diagonal, and
19593the prefix argument is required.
19594
19595To build a constant square matrix, e.g., a
19596@texline @math{3\times3}
19597@infoline 3x3
19598matrix filled with ones, use @kbd{0 M-3 v d 1 +}, i.e., build a zero
19599matrix first and then add a constant value to that matrix. (Another
19600alternative would be to use @kbd{v b} and @kbd{v a}; see below.)
19601
19602@kindex v i
19603@pindex calc-ident
19604@tindex idn
19605The @kbd{v i} (@code{calc-ident}) [@code{idn}] function builds an identity
19606matrix of the specified size. It is a convenient form of @kbd{v d}
19607where the diagonal element is always one. If no prefix argument is given,
19608this command prompts for one.
19609
19610In algebraic notation, @samp{idn(a,n)} acts much like @samp{diag(a,n)},
19611except that @expr{a} is required to be a scalar (non-vector) quantity.
19612If @expr{n} is omitted, @samp{idn(a)} represents @expr{a} times an
19613identity matrix of unknown size. Calc can operate algebraically on
19614such generic identity matrices, and if one is combined with a matrix
19615whose size is known, it is converted automatically to an identity
19616matrix of a suitable matching size. The @kbd{v i} command with an
19617argument of zero creates a generic identity matrix, @samp{idn(1)}.
19618Note that in dimensioned Matrix mode (@pxref{Matrix Mode}), generic
19619identity matrices are immediately expanded to the current default
19620dimensions.
19621
19622@kindex v x
19623@pindex calc-index
19624@tindex index
19625The @kbd{v x} (@code{calc-index}) [@code{index}] function builds a vector
19626of consecutive integers from 1 to @var{n}, where @var{n} is the numeric
19627prefix argument. If you do not provide a prefix argument, you will be
19628prompted to enter a suitable number. If @var{n} is negative, the result
19629is a vector of negative integers from @var{n} to @mathit{-1}.
19630
19631With a prefix argument of just @kbd{C-u}, the @kbd{v x} command takes
19632three values from the stack: @var{n}, @var{start}, and @var{incr} (with
19633@var{incr} at top-of-stack). Counting starts at @var{start} and increases
19634by @var{incr} for successive vector elements. If @var{start} or @var{n}
19635is in floating-point format, the resulting vector elements will also be
19636floats. Note that @var{start} and @var{incr} may in fact be any kind
19637of numbers or formulas.
19638
19639When @var{start} and @var{incr} are specified, a negative @var{n} has a
19640different interpretation: It causes a geometric instead of arithmetic
19641sequence to be generated. For example, @samp{index(-3, a, b)} produces
19642@samp{[a, a b, a b^2]}. If you omit @var{incr} in the algebraic form,
19643@samp{index(@var{n}, @var{start})}, the default value for @var{incr}
19644is one for positive @var{n} or two for negative @var{n}.
19645
19646@kindex v b
19647@pindex calc-build-vector
19648@tindex cvec
19649The @kbd{v b} (@code{calc-build-vector}) [@code{cvec}] function builds a
19650vector of @var{n} copies of the value on the top of the stack, where @var{n}
19651is the numeric prefix argument. In algebraic formulas, @samp{cvec(x,n,m)}
19652can also be used to build an @var{n}-by-@var{m} matrix of copies of @var{x}.
19653(Interactively, just use @kbd{v b} twice: once to build a row, then again
19654to build a matrix of copies of that row.)
19655
19656@kindex v h
19657@kindex I v h
19658@pindex calc-head
19659@pindex calc-tail
19660@tindex head
19661@tindex tail
19662The @kbd{v h} (@code{calc-head}) [@code{head}] function returns the first
19663element of a vector. The @kbd{I v h} (@code{calc-tail}) [@code{tail}]
19664function returns the vector with its first element removed. In both
19665cases, the argument must be a non-empty vector.
19666
19667@kindex v k
19668@pindex calc-cons
19669@tindex cons
19670The @kbd{v k} (@code{calc-cons}) [@code{cons}] function takes a value @var{h}
19671and a vector @var{t} from the stack, and produces the vector whose head is
19672@var{h} and whose tail is @var{t}. This is similar to @kbd{|}, except
19673if @var{h} is itself a vector, @kbd{|} will concatenate the two vectors
19674whereas @code{cons} will insert @var{h} at the front of the vector @var{t}.
19675
19676@kindex H v h
19677@tindex rhead
19678@ignore
19679@mindex @idots
19680@end ignore
19681@kindex H I v h
19682@ignore
19683@mindex @null
19684@end ignore
19685@kindex H v k
19686@ignore
19687@mindex @null
19688@end ignore
19689@tindex rtail
19690@ignore
19691@mindex @null
19692@end ignore
19693@tindex rcons
19694Each of these three functions also accepts the Hyperbolic flag [@code{rhead},
19695@code{rtail}, @code{rcons}] in which case @var{t} instead represents
19696the @emph{last} single element of the vector, with @var{h}
19697representing the remainder of the vector. Thus the vector
19698@samp{[a, b, c, d] = cons(a, [b, c, d]) = rcons([a, b, c], d)}.
19699Also, @samp{head([a, b, c, d]) = a}, @samp{tail([a, b, c, d]) = [b, c, d]},
19700@samp{rhead([a, b, c, d]) = [a, b, c]}, and @samp{rtail([a, b, c, d]) = d}.
19701
19702@node Extracting Elements, Manipulating Vectors, Building Vectors, Matrix Functions
19703@section Extracting Vector Elements
19704
19705@noindent
19706@kindex v r
19707@pindex calc-mrow
19708@tindex mrow
19709The @kbd{v r} (@code{calc-mrow}) [@code{mrow}] command extracts one row of
19710the matrix on the top of the stack, or one element of the plain vector on
19711the top of the stack. The row or element is specified by the numeric
19712prefix argument; the default is to prompt for the row or element number.
19713The matrix or vector is replaced by the specified row or element in the
19714form of a vector or scalar, respectively.
19715
19716@cindex Permutations, applying
19717With a prefix argument of @kbd{C-u} only, @kbd{v r} takes the index of
19718the element or row from the top of the stack, and the vector or matrix
19719from the second-to-top position. If the index is itself a vector of
19720integers, the result is a vector of the corresponding elements of the
19721input vector, or a matrix of the corresponding rows of the input matrix.
19722This command can be used to obtain any permutation of a vector.
19723
19724With @kbd{C-u}, if the index is an interval form with integer components,
19725it is interpreted as a range of indices and the corresponding subvector or
19726submatrix is returned.
19727
19728@cindex Subscript notation
19729@kindex a _
19730@pindex calc-subscript
19731@tindex subscr
19732@tindex _
19733Subscript notation in algebraic formulas (@samp{a_b}) stands for the
19734Calc function @code{subscr}, which is synonymous with @code{mrow}.
19735Thus, @samp{[x, y, z]_k} produces @expr{x}, @expr{y}, or @expr{z} if
19736@expr{k} is one, two, or three, respectively. A double subscript
19737(@samp{M_i_j}, equivalent to @samp{subscr(subscr(M, i), j)}) will
19738access the element at row @expr{i}, column @expr{j} of a matrix.
19739The @kbd{a _} (@code{calc-subscript}) command creates a subscript
19740formula @samp{a_b} out of two stack entries. (It is on the @kbd{a}
19741``algebra'' prefix because subscripted variables are often used
19742purely as an algebraic notation.)
19743
19744@tindex mrrow
19745Given a negative prefix argument, @kbd{v r} instead deletes one row or
19746element from the matrix or vector on the top of the stack. Thus
19747@kbd{C-u 2 v r} replaces a matrix with its second row, but @kbd{C-u -2 v r}
19748replaces the matrix with the same matrix with its second row removed.
19749In algebraic form this function is called @code{mrrow}.
19750
19751@tindex getdiag
19752Given a prefix argument of zero, @kbd{v r} extracts the diagonal elements
19753of a square matrix in the form of a vector. In algebraic form this
19754function is called @code{getdiag}.
19755
19756@kindex v c
19757@pindex calc-mcol
19758@tindex mcol
19759@tindex mrcol
19760The @kbd{v c} (@code{calc-mcol}) [@code{mcol} or @code{mrcol}] command is
19761the analogous operation on columns of a matrix. Given a plain vector
19762it extracts (or removes) one element, just like @kbd{v r}. If the
19763index in @kbd{C-u v c} is an interval or vector and the argument is a
19764matrix, the result is a submatrix with only the specified columns
19765retained (and possibly permuted in the case of a vector index).
19766
19767To extract a matrix element at a given row and column, use @kbd{v r} to
19768extract the row as a vector, then @kbd{v c} to extract the column element
19769from that vector. In algebraic formulas, it is often more convenient to
19770use subscript notation: @samp{m_i_j} gives row @expr{i}, column @expr{j}
19771of matrix @expr{m}.
19772
19773@kindex v s
19774@pindex calc-subvector
19775@tindex subvec
19776The @kbd{v s} (@code{calc-subvector}) [@code{subvec}] command extracts
19777a subvector of a vector. The arguments are the vector, the starting
19778index, and the ending index, with the ending index in the top-of-stack
19779position. The starting index indicates the first element of the vector
19780to take. The ending index indicates the first element @emph{past} the
19781range to be taken. Thus, @samp{subvec([a, b, c, d, e], 2, 4)} produces
19782the subvector @samp{[b, c]}. You could get the same result using
19783@samp{mrow([a, b, c, d, e], @w{[2 .. 4)})}.
19784
19785If either the start or the end index is zero or negative, it is
19786interpreted as relative to the end of the vector. Thus
19787@samp{subvec([a, b, c, d, e], 2, -2)} also produces @samp{[b, c]}. In
19788the algebraic form, the end index can be omitted in which case it
19789is taken as zero, i.e., elements from the starting element to the
19790end of the vector are used. The infinity symbol, @code{inf}, also
19791has this effect when used as the ending index.
19792
19793@kindex I v s
19794@tindex rsubvec
19795With the Inverse flag, @kbd{I v s} [@code{rsubvec}] removes a subvector
19796from a vector. The arguments are interpreted the same as for the
19797normal @kbd{v s} command. Thus, @samp{rsubvec([a, b, c, d, e], 2, 4)}
19798produces @samp{[a, d, e]}. It is always true that @code{subvec} and
19799@code{rsubvec} return complementary parts of the input vector.
19800
19801@xref{Selecting Subformulas}, for an alternative way to operate on
19802vectors one element at a time.
19803
19804@node Manipulating Vectors, Vector and Matrix Arithmetic, Extracting Elements, Matrix Functions
19805@section Manipulating Vectors
19806
19807@noindent
19808@kindex v l
19809@pindex calc-vlength
19810@tindex vlen
19811The @kbd{v l} (@code{calc-vlength}) [@code{vlen}] command computes the
19812length of a vector. The length of a non-vector is considered to be zero.
19813Note that matrices are just vectors of vectors for the purposes of this
19814command.
19815
19816@kindex H v l
19817@tindex mdims
19818With the Hyperbolic flag, @kbd{H v l} [@code{mdims}] computes a vector
19819of the dimensions of a vector, matrix, or higher-order object. For
19820example, @samp{mdims([[a,b,c],[d,e,f]])} returns @samp{[2, 3]} since
19821its argument is a
19822@texline @math{2\times3}
19823@infoline 2x3
19824matrix.
19825
19826@kindex v f
19827@pindex calc-vector-find
19828@tindex find
19829The @kbd{v f} (@code{calc-vector-find}) [@code{find}] command searches
19830along a vector for the first element equal to a given target. The target
19831is on the top of the stack; the vector is in the second-to-top position.
19832If a match is found, the result is the index of the matching element.
19833Otherwise, the result is zero. The numeric prefix argument, if given,
19834allows you to select any starting index for the search.
19835
19836@kindex v a
19837@pindex calc-arrange-vector
19838@tindex arrange
19839@cindex Arranging a matrix
19840@cindex Reshaping a matrix
19841@cindex Flattening a matrix
19842The @kbd{v a} (@code{calc-arrange-vector}) [@code{arrange}] command
19843rearranges a vector to have a certain number of columns and rows. The
19844numeric prefix argument specifies the number of columns; if you do not
19845provide an argument, you will be prompted for the number of columns.
19846The vector or matrix on the top of the stack is @dfn{flattened} into a
19847plain vector. If the number of columns is nonzero, this vector is
19848then formed into a matrix by taking successive groups of @var{n} elements.
19849If the number of columns does not evenly divide the number of elements
19850in the vector, the last row will be short and the result will not be
19851suitable for use as a matrix. For example, with the matrix
19852@samp{[[1, 2], @w{[3, 4]}]} on the stack, @kbd{v a 4} produces
19853@samp{[[1, 2, 3, 4]]} (a
19854@texline @math{1\times4}
19855@infoline 1x4
19856matrix), @kbd{v a 1} produces @samp{[[1], [2], [3], [4]]} (a
19857@texline @math{4\times1}
19858@infoline 4x1
19859matrix), @kbd{v a 2} produces @samp{[[1, 2], [3, 4]]} (the original
19860@texline @math{2\times2}
19861@infoline 2x2
19862matrix), @w{@kbd{v a 3}} produces @samp{[[1, 2, 3], [4]]} (not a
19863matrix), and @kbd{v a 0} produces the flattened list
19864@samp{[1, 2, @w{3, 4}]}.
19865
19866@cindex Sorting data
19867@kindex V S
19868@kindex I V S
19869@pindex calc-sort
19870@tindex sort
19871@tindex rsort
19872The @kbd{V S} (@code{calc-sort}) [@code{sort}] command sorts the elements of
19873a vector into increasing order. Real numbers, real infinities, and
19874constant interval forms come first in this ordering; next come other
19875kinds of numbers, then variables (in alphabetical order), then finally
19876come formulas and other kinds of objects; these are sorted according
19877to a kind of lexicographic ordering with the useful property that
19878one vector is less or greater than another if the first corresponding
19879unequal elements are less or greater, respectively. Since quoted strings
19880are stored by Calc internally as vectors of ASCII character codes
19881(@pxref{Strings}), this means vectors of strings are also sorted into
19882alphabetical order by this command.
19883
19884The @kbd{I V S} [@code{rsort}] command sorts a vector into decreasing order.
19885
19886@cindex Permutation, inverse of
19887@cindex Inverse of permutation
19888@cindex Index tables
19889@cindex Rank tables
19890@kindex V G
19891@kindex I V G
19892@pindex calc-grade
19893@tindex grade
19894@tindex rgrade
19895The @kbd{V G} (@code{calc-grade}) [@code{grade}, @code{rgrade}] command
19896produces an index table or permutation vector which, if applied to the
19897input vector (as the index of @kbd{C-u v r}, say), would sort the vector.
19898A permutation vector is just a vector of integers from 1 to @var{n}, where
19899each integer occurs exactly once. One application of this is to sort a
19900matrix of data rows using one column as the sort key; extract that column,
19901grade it with @kbd{V G}, then use the result to reorder the original matrix
19902with @kbd{C-u v r}. Another interesting property of the @code{V G} command
19903is that, if the input is itself a permutation vector, the result will
19904be the inverse of the permutation. The inverse of an index table is
19905a rank table, whose @var{k}th element says where the @var{k}th original
19906vector element will rest when the vector is sorted. To get a rank
19907table, just use @kbd{V G V G}.
19908
19909With the Inverse flag, @kbd{I V G} produces an index table that would
19910sort the input into decreasing order. Note that @kbd{V S} and @kbd{V G}
19911use a ``stable'' sorting algorithm, i.e., any two elements which are equal
19912will not be moved out of their original order. Generally there is no way
19913to tell with @kbd{V S}, since two elements which are equal look the same,
19914but with @kbd{V G} this can be an important issue. In the matrix-of-rows
19915example, suppose you have names and telephone numbers as two columns and
19916you wish to sort by phone number primarily, and by name when the numbers
19917are equal. You can sort the data matrix by names first, and then again
19918by phone numbers. Because the sort is stable, any two rows with equal
19919phone numbers will remain sorted by name even after the second sort.
19920
19921@cindex Histograms
19922@kindex V H
19923@pindex calc-histogram
19924@ignore
19925@mindex histo@idots
19926@end ignore
19927@tindex histogram
19928The @kbd{V H} (@code{calc-histogram}) [@code{histogram}] command builds a
19929histogram of a vector of numbers. Vector elements are assumed to be
19930integers or real numbers in the range [0..@var{n}) for some ``number of
19931bins'' @var{n}, which is the numeric prefix argument given to the
19932command. The result is a vector of @var{n} counts of how many times
19933each value appeared in the original vector. Non-integers in the input
19934are rounded down to integers. Any vector elements outside the specified
19935range are ignored. (You can tell if elements have been ignored by noting
19936that the counts in the result vector don't add up to the length of the
19937input vector.)
19938
19939@kindex H V H
19940With the Hyperbolic flag, @kbd{H V H} pulls two vectors from the stack.
19941The second-to-top vector is the list of numbers as before. The top
19942vector is an equal-sized list of ``weights'' to attach to the elements
19943of the data vector. For example, if the first data element is 4.2 and
19944the first weight is 10, then 10 will be added to bin 4 of the result
19945vector. Without the hyperbolic flag, every element has a weight of one.
19946
19947@kindex v t
19948@pindex calc-transpose
19949@tindex trn
19950The @kbd{v t} (@code{calc-transpose}) [@code{trn}] command computes
19951the transpose of the matrix at the top of the stack. If the argument
19952is a plain vector, it is treated as a row vector and transposed into
19953a one-column matrix.
19954
19955@kindex v v
19956@pindex calc-reverse-vector
19957@tindex rev
19958The @kbd{v v} (@code{calc-reverse-vector}) [@code{rev}] command reverses
19959a vector end-for-end. Given a matrix, it reverses the order of the rows.
19960(To reverse the columns instead, just use @kbd{v t v v v t}. The same
19961principle can be used to apply other vector commands to the columns of
19962a matrix.)
19963
19964@kindex v m
19965@pindex calc-mask-vector
19966@tindex vmask
19967The @kbd{v m} (@code{calc-mask-vector}) [@code{vmask}] command uses
19968one vector as a mask to extract elements of another vector. The mask
19969is in the second-to-top position; the target vector is on the top of
19970the stack. These vectors must have the same length. The result is
19971the same as the target vector, but with all elements which correspond
19972to zeros in the mask vector deleted. Thus, for example,
19973@samp{vmask([1, 0, 1, 0, 1], [a, b, c, d, e])} produces @samp{[a, c, e]}.
19974@xref{Logical Operations}.
19975
19976@kindex v e
19977@pindex calc-expand-vector
19978@tindex vexp
19979The @kbd{v e} (@code{calc-expand-vector}) [@code{vexp}] command
19980expands a vector according to another mask vector. The result is a
19981vector the same length as the mask, but with nonzero elements replaced
19982by successive elements from the target vector. The length of the target
19983vector is normally the number of nonzero elements in the mask. If the
19984target vector is longer, its last few elements are lost. If the target
19985vector is shorter, the last few nonzero mask elements are left
19986unreplaced in the result. Thus @samp{vexp([2, 0, 3, 0, 7], [a, b])}
19987produces @samp{[a, 0, b, 0, 7]}.
19988
19989@kindex H v e
19990With the Hyperbolic flag, @kbd{H v e} takes a filler value from the
19991top of the stack; the mask and target vectors come from the third and
19992second elements of the stack. This filler is used where the mask is
19993zero: @samp{vexp([2, 0, 3, 0, 7], [a, b], z)} produces
19994@samp{[a, z, c, z, 7]}. If the filler value is itself a vector,
19995then successive values are taken from it, so that the effect is to
19996interleave two vectors according to the mask:
19997@samp{vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])} produces
19998@samp{[a, x, b, 7, y, 0]}.
19999
20000Another variation on the masking idea is to combine @samp{[a, b, c, d, e]}
20001with the mask @samp{[1, 0, 1, 0, 1]} to produce @samp{[a, 0, c, 0, e]}.
20002You can accomplish this with @kbd{V M a &}, mapping the logical ``and''
20003operation across the two vectors. @xref{Logical Operations}. Note that
20004the @code{? :} operation also discussed there allows other types of
20005masking using vectors.
20006
20007@node Vector and Matrix Arithmetic, Set Operations, Manipulating Vectors, Matrix Functions
20008@section Vector and Matrix Arithmetic
20009
20010@noindent
20011Basic arithmetic operations like addition and multiplication are defined
20012for vectors and matrices as well as for numbers. Division of matrices, in
20013the sense of multiplying by the inverse, is supported. (Division by a
20014matrix actually uses LU-decomposition for greater accuracy and speed.)
20015@xref{Basic Arithmetic}.
20016
20017The following functions are applied element-wise if their arguments are
20018vectors or matrices: @code{change-sign}, @code{conj}, @code{arg},
20019@code{re}, @code{im}, @code{polar}, @code{rect}, @code{clean},
20020@code{float}, @code{frac}. @xref{Function Index}.
20021
20022@kindex V J
20023@pindex calc-conj-transpose
20024@tindex ctrn
20025The @kbd{V J} (@code{calc-conj-transpose}) [@code{ctrn}] command computes
20026the conjugate transpose of its argument, i.e., @samp{conj(trn(x))}.
20027
20028@ignore
20029@mindex A
20030@end ignore
20031@kindex A (vectors)
20032@pindex calc-abs (vectors)
20033@ignore
20034@mindex abs
20035@end ignore
20036@tindex abs (vectors)
20037The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the
20038Frobenius norm of a vector or matrix argument. This is the square
20039root of the sum of the squares of the absolute values of the
20040elements of the vector or matrix. If the vector is interpreted as
20041a point in two- or three-dimensional space, this is the distance
20042from that point to the origin.
20043
20044@kindex v n
20045@pindex calc-rnorm
20046@tindex rnorm
a8b14149
JB
20047The @kbd{v n} (@code{calc-rnorm}) [@code{rnorm}] command computes the
20048infinity-norm of a vector, or the row norm of a matrix. For a plain
20049vector, this is the maximum of the absolute values of the elements. For
20050a matrix, this is the maximum of the row-absolute-value-sums, i.e., of
20051the sums of the absolute values of the elements along the various rows.
4009494e
GM
20052
20053@kindex V N
20054@pindex calc-cnorm
20055@tindex cnorm
20056The @kbd{V N} (@code{calc-cnorm}) [@code{cnorm}] command computes
a8b14149 20057the one-norm of a vector, or column norm of a matrix. For a plain
4009494e
GM
20058vector, this is the sum of the absolute values of the elements.
20059For a matrix, this is the maximum of the column-absolute-value-sums.
20060General @expr{k}-norms for @expr{k} other than one or infinity are
a8b14149
JB
20061not provided. However, the 2-norm (or Frobenius norm) is provided for
20062vectors by the @kbd{A} (@code{calc-abs}) command.
4009494e
GM
20063
20064@kindex V C
20065@pindex calc-cross
20066@tindex cross
20067The @kbd{V C} (@code{calc-cross}) [@code{cross}] command computes the
20068right-handed cross product of two vectors, each of which must have
20069exactly three elements.
20070
20071@ignore
20072@mindex &
20073@end ignore
20074@kindex & (matrices)
20075@pindex calc-inv (matrices)
20076@ignore
20077@mindex inv
20078@end ignore
20079@tindex inv (matrices)
20080The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
20081inverse of a square matrix. If the matrix is singular, the inverse
20082operation is left in symbolic form. Matrix inverses are recorded so
20083that once an inverse (or determinant) of a particular matrix has been
20084computed, the inverse and determinant of the matrix can be recomputed
20085quickly in the future.
20086
20087If the argument to @kbd{&} is a plain number @expr{x}, this
20088command simply computes @expr{1/x}. This is okay, because the
20089@samp{/} operator also does a matrix inversion when dividing one
20090by a matrix.
20091
20092@kindex V D
20093@pindex calc-mdet
20094@tindex det
20095The @kbd{V D} (@code{calc-mdet}) [@code{det}] command computes the
20096determinant of a square matrix.
20097
20098@kindex V L
20099@pindex calc-mlud
20100@tindex lud
20101The @kbd{V L} (@code{calc-mlud}) [@code{lud}] command computes the
20102LU decomposition of a matrix. The result is a list of three matrices
20103which, when multiplied together left-to-right, form the original matrix.
20104The first is a permutation matrix that arises from pivoting in the
20105algorithm, the second is lower-triangular with ones on the diagonal,
20106and the third is upper-triangular.
20107
20108@kindex V T
20109@pindex calc-mtrace
20110@tindex tr
20111The @kbd{V T} (@code{calc-mtrace}) [@code{tr}] command computes the
20112trace of a square matrix. This is defined as the sum of the diagonal
20113elements of the matrix.
20114
629f618d
JB
20115@kindex V K
20116@pindex calc-kron
20117@tindex kron
20118The @kbd{V K} (@code{calc-kron}) [@code{kron}] command computes
20119the Kronecker product of two matrices.
20120
4009494e
GM
20121@node Set Operations, Statistical Operations, Vector and Matrix Arithmetic, Matrix Functions
20122@section Set Operations using Vectors
20123
20124@noindent
20125@cindex Sets, as vectors
20126Calc includes several commands which interpret vectors as @dfn{sets} of
20127objects. A set is a collection of objects; any given object can appear
20128only once in the set. Calc stores sets as vectors of objects in
20129sorted order. Objects in a Calc set can be any of the usual things,
20130such as numbers, variables, or formulas. Two set elements are considered
20131equal if they are identical, except that numerically equal numbers like
20132the integer 4 and the float 4.0 are considered equal even though they
20133are not ``identical.'' Variables are treated like plain symbols without
20134attached values by the set operations; subtracting the set @samp{[b]}
20135from @samp{[a, b]} always yields the set @samp{[a]} even though if
20136the variables @samp{a} and @samp{b} both equaled 17, you might
20137expect the answer @samp{[]}.
20138
20139If a set contains interval forms, then it is assumed to be a set of
20140real numbers. In this case, all set operations require the elements
20141of the set to be only things that are allowed in intervals: Real
20142numbers, plus and minus infinity, HMS forms, and date forms. If
20143there are variables or other non-real objects present in a real set,
20144all set operations on it will be left in unevaluated form.
20145
20146If the input to a set operation is a plain number or interval form
20147@var{a}, it is treated like the one-element vector @samp{[@var{a}]}.
20148The result is always a vector, except that if the set consists of a
20149single interval, the interval itself is returned instead.
20150
20151@xref{Logical Operations}, for the @code{in} function which tests if
20152a certain value is a member of a given set. To test if the set @expr{A}
20153is a subset of the set @expr{B}, use @samp{vdiff(A, B) = []}.
20154
20155@kindex V +
20156@pindex calc-remove-duplicates
20157@tindex rdup
20158The @kbd{V +} (@code{calc-remove-duplicates}) [@code{rdup}] command
20159converts an arbitrary vector into set notation. It works by sorting
20160the vector as if by @kbd{V S}, then removing duplicates. (For example,
20161@kbd{[a, 5, 4, a, 4.0]} is sorted to @samp{[4, 4.0, 5, a, a]} and then
20162reduced to @samp{[4, 5, a]}). Overlapping intervals are merged as
20163necessary. You rarely need to use @kbd{V +} explicitly, since all the
20164other set-based commands apply @kbd{V +} to their inputs before using
20165them.
20166
20167@kindex V V
20168@pindex calc-set-union
20169@tindex vunion
20170The @kbd{V V} (@code{calc-set-union}) [@code{vunion}] command computes
20171the union of two sets. An object is in the union of two sets if and
20172only if it is in either (or both) of the input sets. (You could
20173accomplish the same thing by concatenating the sets with @kbd{|},
20174then using @kbd{V +}.)
20175
20176@kindex V ^
20177@pindex calc-set-intersect
20178@tindex vint
20179The @kbd{V ^} (@code{calc-set-intersect}) [@code{vint}] command computes
20180the intersection of two sets. An object is in the intersection if
20181and only if it is in both of the input sets. Thus if the input
20182sets are disjoint, i.e., if they share no common elements, the result
20183will be the empty vector @samp{[]}. Note that the characters @kbd{V}
20184and @kbd{^} were chosen to be close to the conventional mathematical
20185notation for set
20186@texline union@tie{}(@math{A \cup B})
20187@infoline union
20188and
20189@texline intersection@tie{}(@math{A \cap B}).
20190@infoline intersection.
20191
20192@kindex V -
20193@pindex calc-set-difference
20194@tindex vdiff
20195The @kbd{V -} (@code{calc-set-difference}) [@code{vdiff}] command computes
20196the difference between two sets. An object is in the difference
20197@expr{A - B} if and only if it is in @expr{A} but not in @expr{B}.
20198Thus subtracting @samp{[y,z]} from a set will remove the elements
20199@samp{y} and @samp{z} if they are present. You can also think of this
20200as a general @dfn{set complement} operator; if @expr{A} is the set of
20201all possible values, then @expr{A - B} is the ``complement'' of @expr{B}.
20202Obviously this is only practical if the set of all possible values in
20203your problem is small enough to list in a Calc vector (or simple
20204enough to express in a few intervals).
20205
20206@kindex V X
20207@pindex calc-set-xor
20208@tindex vxor
20209The @kbd{V X} (@code{calc-set-xor}) [@code{vxor}] command computes
20210the ``exclusive-or,'' or ``symmetric difference'' of two sets.
20211An object is in the symmetric difference of two sets if and only
20212if it is in one, but @emph{not} both, of the sets. Objects that
20213occur in both sets ``cancel out.''
20214
20215@kindex V ~
20216@pindex calc-set-complement
20217@tindex vcompl
20218The @kbd{V ~} (@code{calc-set-complement}) [@code{vcompl}] command
20219computes the complement of a set with respect to the real numbers.
20220Thus @samp{vcompl(x)} is equivalent to @samp{vdiff([-inf .. inf], x)}.
20221For example, @samp{vcompl([2, (3 .. 4]])} evaluates to
20222@samp{[[-inf .. 2), (2 .. 3], (4 .. inf]]}.
20223
20224@kindex V F
20225@pindex calc-set-floor
20226@tindex vfloor
20227The @kbd{V F} (@code{calc-set-floor}) [@code{vfloor}] command
20228reinterprets a set as a set of integers. Any non-integer values,
20229and intervals that do not enclose any integers, are removed. Open
20230intervals are converted to equivalent closed intervals. Successive
20231integers are converted into intervals of integers. For example, the
20232complement of the set @samp{[2, 6, 7, 8]} is messy, but if you wanted
20233the complement with respect to the set of integers you could type
20234@kbd{V ~ V F} to get @samp{[[-inf .. 1], [3 .. 5], [9 .. inf]]}.
20235
20236@kindex V E
20237@pindex calc-set-enumerate
20238@tindex venum
20239The @kbd{V E} (@code{calc-set-enumerate}) [@code{venum}] command
20240converts a set of integers into an explicit vector. Intervals in
20241the set are expanded out to lists of all integers encompassed by
20242the intervals. This only works for finite sets (i.e., sets which
20243do not involve @samp{-inf} or @samp{inf}).
20244
20245@kindex V :
20246@pindex calc-set-span
20247@tindex vspan
20248The @kbd{V :} (@code{calc-set-span}) [@code{vspan}] command converts any
20249set of reals into an interval form that encompasses all its elements.
20250The lower limit will be the smallest element in the set; the upper
20251limit will be the largest element. For an empty set, @samp{vspan([])}
20252returns the empty interval @w{@samp{[0 .. 0)}}.
20253
20254@kindex V #
20255@pindex calc-set-cardinality
20256@tindex vcard
20257The @kbd{V #} (@code{calc-set-cardinality}) [@code{vcard}] command counts
20258the number of integers in a set. The result is the length of the vector
20259that would be produced by @kbd{V E}, although the computation is much
20260more efficient than actually producing that vector.
20261
20262@cindex Sets, as binary numbers
20263Another representation for sets that may be more appropriate in some
20264cases is binary numbers. If you are dealing with sets of integers
20265in the range 0 to 49, you can use a 50-bit binary number where a
20266particular bit is 1 if the corresponding element is in the set.
20267@xref{Binary Functions}, for a list of commands that operate on
20268binary numbers. Note that many of the above set operations have
20269direct equivalents in binary arithmetic: @kbd{b o} (@code{calc-or}),
20270@kbd{b a} (@code{calc-and}), @kbd{b d} (@code{calc-diff}),
20271@kbd{b x} (@code{calc-xor}), and @kbd{b n} (@code{calc-not}),
20272respectively. You can use whatever representation for sets is most
20273convenient to you.
20274
20275@kindex b p
20276@kindex b u
20277@pindex calc-pack-bits
20278@pindex calc-unpack-bits
20279@tindex vpack
20280@tindex vunpack
20281The @kbd{b u} (@code{calc-unpack-bits}) [@code{vunpack}] command
20282converts an integer that represents a set in binary into a set
20283in vector/interval notation. For example, @samp{vunpack(67)}
20284returns @samp{[[0 .. 1], 6]}. If the input is negative, the set
20285it represents is semi-infinite: @samp{vunpack(-4) = [2 .. inf)}.
20286Use @kbd{V E} afterwards to expand intervals to individual
20287values if you wish. Note that this command uses the @kbd{b}
20288(binary) prefix key.
20289
20290The @kbd{b p} (@code{calc-pack-bits}) [@code{vpack}] command
20291converts the other way, from a vector or interval representing
20292a set of nonnegative integers into a binary integer describing
20293the same set. The set may include positive infinity, but must
20294not include any negative numbers. The input is interpreted as a
20295set of integers in the sense of @kbd{V F} (@code{vfloor}). Beware
20296that a simple input like @samp{[100]} can result in a huge integer
20297representation
20298@texline (@math{2^{100}}, a 31-digit integer, in this case).
20299@infoline (@expr{2^100}, a 31-digit integer, in this case).
20300
20301@node Statistical Operations, Reducing and Mapping, Set Operations, Matrix Functions
20302@section Statistical Operations on Vectors
20303
20304@noindent
20305@cindex Statistical functions
20306The commands in this section take vectors as arguments and compute
20307various statistical measures on the data stored in the vectors. The
20308references used in the definitions of these functions are Bevington's
20309@emph{Data Reduction and Error Analysis for the Physical Sciences},
20310and @emph{Numerical Recipes} by Press, Flannery, Teukolsky and
20311Vetterling.
20312
20313The statistical commands use the @kbd{u} prefix key followed by
20314a shifted letter or other character.
20315
20316@xref{Manipulating Vectors}, for a description of @kbd{V H}
20317(@code{calc-histogram}).
20318
20319@xref{Curve Fitting}, for the @kbd{a F} command for doing
20320least-squares fits to statistical data.
20321
20322@xref{Probability Distribution Functions}, for several common
20323probability distribution functions.
20324
20325@menu
20326* Single-Variable Statistics::
20327* Paired-Sample Statistics::
20328@end menu
20329
20330@node Single-Variable Statistics, Paired-Sample Statistics, Statistical Operations, Statistical Operations
20331@subsection Single-Variable Statistics
20332
20333@noindent
20334These functions do various statistical computations on single
20335vectors. Given a numeric prefix argument, they actually pop
20336@var{n} objects from the stack and combine them into a data
20337vector. Each object may be either a number or a vector; if a
20338vector, any sub-vectors inside it are ``flattened'' as if by
20339@kbd{v a 0}; @pxref{Manipulating Vectors}. By default one object
20340is popped, which (in order to be useful) is usually a vector.
20341
20342If an argument is a variable name, and the value stored in that
20343variable is a vector, then the stored vector is used. This method
20344has the advantage that if your data vector is large, you can avoid
20345the slow process of manipulating it directly on the stack.
20346
20347These functions are left in symbolic form if any of their arguments
20348are not numbers or vectors, e.g., if an argument is a formula, or
20349a non-vector variable. However, formulas embedded within vector
20350arguments are accepted; the result is a symbolic representation
20351of the computation, based on the assumption that the formula does
20352not itself represent a vector. All varieties of numbers such as
20353error forms and interval forms are acceptable.
20354
20355Some of the functions in this section also accept a single error form
20356or interval as an argument. They then describe a property of the
20357normal or uniform (respectively) statistical distribution described
20358by the argument. The arguments are interpreted in the same way as
20359the @var{M} argument of the random number function @kbd{k r}. In
20360particular, an interval with integer limits is considered an integer
20361distribution, so that @samp{[2 .. 6)} is the same as @samp{[2 .. 5]}.
20362An interval with at least one floating-point limit is a continuous
20363distribution: @samp{[2.0 .. 6.0)} is @emph{not} the same as
20364@samp{[2.0 .. 5.0]}!
20365
20366@kindex u #
20367@pindex calc-vector-count
20368@tindex vcount
20369The @kbd{u #} (@code{calc-vector-count}) [@code{vcount}] command
20370computes the number of data values represented by the inputs.
20371For example, @samp{vcount(1, [2, 3], [[4, 5], [], x, y])} returns 7.
20372If the argument is a single vector with no sub-vectors, this
20373simply computes the length of the vector.
20374
20375@kindex u +
20376@kindex u *
20377@pindex calc-vector-sum
20378@pindex calc-vector-prod
20379@tindex vsum
20380@tindex vprod
20381@cindex Summations (statistical)
20382The @kbd{u +} (@code{calc-vector-sum}) [@code{vsum}] command
20383computes the sum of the data values. The @kbd{u *}
20384(@code{calc-vector-prod}) [@code{vprod}] command computes the
20385product of the data values. If the input is a single flat vector,
20386these are the same as @kbd{V R +} and @kbd{V R *}
20387(@pxref{Reducing and Mapping}).
20388
20389@kindex u X
20390@kindex u N
20391@pindex calc-vector-max
20392@pindex calc-vector-min
20393@tindex vmax
20394@tindex vmin
20395The @kbd{u X} (@code{calc-vector-max}) [@code{vmax}] command
20396computes the maximum of the data values, and the @kbd{u N}
20397(@code{calc-vector-min}) [@code{vmin}] command computes the minimum.
20398If the argument is an interval, this finds the minimum or maximum
20399value in the interval. (Note that @samp{vmax([2..6)) = 5} as
20400described above.) If the argument is an error form, this returns
20401plus or minus infinity.
20402
20403@kindex u M
20404@pindex calc-vector-mean
20405@tindex vmean
20406@cindex Mean of data values
20407The @kbd{u M} (@code{calc-vector-mean}) [@code{vmean}] command
20408computes the average (arithmetic mean) of the data values.
20409If the inputs are error forms
20410@texline @math{x \pm \sigma},
20411@infoline @samp{x +/- s},
20412this is the weighted mean of the @expr{x} values with weights
20413@texline @math{1 /\sigma^2}.
20414@infoline @expr{1 / s^2}.
20415@tex
20416\turnoffactive
20417$$ \mu = { \displaystyle \sum { x_i \over \sigma_i^2 } \over
20418 \displaystyle \sum { 1 \over \sigma_i^2 } } $$
20419@end tex
20420If the inputs are not error forms, this is simply the sum of the
20421values divided by the count of the values.
20422
20423Note that a plain number can be considered an error form with
20424error
20425@texline @math{\sigma = 0}.
20426@infoline @expr{s = 0}.
20427If the input to @kbd{u M} is a mixture of
20428plain numbers and error forms, the result is the mean of the
20429plain numbers, ignoring all values with non-zero errors. (By the
20430above definitions it's clear that a plain number effectively
20431has an infinite weight, next to which an error form with a finite
20432weight is completely negligible.)
20433
20434This function also works for distributions (error forms or
20435intervals). The mean of an error form `@var{a} @tfn{+/-} @var{b}' is simply
20436@expr{a}. The mean of an interval is the mean of the minimum
20437and maximum values of the interval.
20438
20439@kindex I u M
20440@pindex calc-vector-mean-error
20441@tindex vmeane
20442The @kbd{I u M} (@code{calc-vector-mean-error}) [@code{vmeane}]
20443command computes the mean of the data points expressed as an
20444error form. This includes the estimated error associated with
20445the mean. If the inputs are error forms, the error is the square
20446root of the reciprocal of the sum of the reciprocals of the squares
20447of the input errors. (I.e., the variance is the reciprocal of the
20448sum of the reciprocals of the variances.)
20449@tex
20450\turnoffactive
20451$$ \sigma_\mu^2 = {1 \over \displaystyle \sum {1 \over \sigma_i^2}} $$
20452@end tex
20453If the inputs are plain
20454numbers, the error is equal to the standard deviation of the values
20455divided by the square root of the number of values. (This works
20456out to be equivalent to calculating the standard deviation and
20457then assuming each value's error is equal to this standard
20458deviation.)
20459@tex
20460\turnoffactive
20461$$ \sigma_\mu^2 = {\sigma^2 \over N} $$
20462@end tex
20463
20464@kindex H u M
20465@pindex calc-vector-median
20466@tindex vmedian
20467@cindex Median of data values
20468The @kbd{H u M} (@code{calc-vector-median}) [@code{vmedian}]
20469command computes the median of the data values. The values are
20470first sorted into numerical order; the median is the middle
20471value after sorting. (If the number of data values is even,
20472the median is taken to be the average of the two middle values.)
20473The median function is different from the other functions in
20474this section in that the arguments must all be real numbers;
20475variables are not accepted even when nested inside vectors.
20476(Otherwise it is not possible to sort the data values.) If
20477any of the input values are error forms, their error parts are
20478ignored.
20479
20480The median function also accepts distributions. For both normal
20481(error form) and uniform (interval) distributions, the median is
20482the same as the mean.
20483
20484@kindex H I u M
20485@pindex calc-vector-harmonic-mean
20486@tindex vhmean
20487@cindex Harmonic mean
20488The @kbd{H I u M} (@code{calc-vector-harmonic-mean}) [@code{vhmean}]
20489command computes the harmonic mean of the data values. This is
20490defined as the reciprocal of the arithmetic mean of the reciprocals
20491of the values.
20492@tex
20493\turnoffactive
20494$$ { N \over \displaystyle \sum {1 \over x_i} } $$
20495@end tex
20496
20497@kindex u G
20498@pindex calc-vector-geometric-mean
20499@tindex vgmean
20500@cindex Geometric mean
20501The @kbd{u G} (@code{calc-vector-geometric-mean}) [@code{vgmean}]
20502command computes the geometric mean of the data values. This
20503is the @var{n}th root of the product of the values. This is also
20504equal to the @code{exp} of the arithmetic mean of the logarithms
20505of the data values.
20506@tex
20507\turnoffactive
20508$$ \exp \left ( \sum { \ln x_i } \right ) =
20509 \left ( \prod { x_i } \right)^{1 / N} $$
20510@end tex
20511
20512@kindex H u G
20513@tindex agmean
20514The @kbd{H u G} [@code{agmean}] command computes the ``arithmetic-geometric
20515mean'' of two numbers taken from the stack. This is computed by
20516replacing the two numbers with their arithmetic mean and geometric
20517mean, then repeating until the two values converge.
20518@tex
20519\turnoffactive
20520$$ a_{i+1} = { a_i + b_i \over 2 } , \qquad b_{i+1} = \sqrt{a_i b_i} $$
20521@end tex
20522
20523@cindex Root-mean-square
20524Another commonly used mean, the RMS (root-mean-square), can be computed
20525for a vector of numbers simply by using the @kbd{A} command.
20526
20527@kindex u S
20528@pindex calc-vector-sdev
20529@tindex vsdev
20530@cindex Standard deviation
20531@cindex Sample statistics
20532The @kbd{u S} (@code{calc-vector-sdev}) [@code{vsdev}] command
20533computes the standard
20534@texline deviation@tie{}@math{\sigma}
20535@infoline deviation
20536of the data values. If the values are error forms, the errors are used
20537as weights just as for @kbd{u M}. This is the @emph{sample} standard
20538deviation, whose value is the square root of the sum of the squares of
20539the differences between the values and the mean of the @expr{N} values,
20540divided by @expr{N-1}.
20541@tex
20542\turnoffactive
20543$$ \sigma^2 = {1 \over N - 1} \sum (x_i - \mu)^2 $$
20544@end tex
20545
20546This function also applies to distributions. The standard deviation
20547of a single error form is simply the error part. The standard deviation
20548of a continuous interval happens to equal the difference between the
20549limits, divided by
20550@texline @math{\sqrt{12}}.
20551@infoline @expr{sqrt(12)}.
20552The standard deviation of an integer interval is the same as the
20553standard deviation of a vector of those integers.
20554
20555@kindex I u S
20556@pindex calc-vector-pop-sdev
20557@tindex vpsdev
20558@cindex Population statistics
20559The @kbd{I u S} (@code{calc-vector-pop-sdev}) [@code{vpsdev}]
20560command computes the @emph{population} standard deviation.
20561It is defined by the same formula as above but dividing
20562by @expr{N} instead of by @expr{N-1}. The population standard
20563deviation is used when the input represents the entire set of
20564data values in the distribution; the sample standard deviation
20565is used when the input represents a sample of the set of all
20566data values, so that the mean computed from the input is itself
20567only an estimate of the true mean.
20568@tex
20569\turnoffactive
20570$$ \sigma^2 = {1 \over N} \sum (x_i - \mu)^2 $$
20571@end tex
20572
20573For error forms and continuous intervals, @code{vpsdev} works
20574exactly like @code{vsdev}. For integer intervals, it computes the
20575population standard deviation of the equivalent vector of integers.
20576
20577@kindex H u S
20578@kindex H I u S
20579@pindex calc-vector-variance
20580@pindex calc-vector-pop-variance
20581@tindex vvar
20582@tindex vpvar
20583@cindex Variance of data values
20584The @kbd{H u S} (@code{calc-vector-variance}) [@code{vvar}] and
20585@kbd{H I u S} (@code{calc-vector-pop-variance}) [@code{vpvar}]
20586commands compute the variance of the data values. The variance
20587is the
20588@texline square@tie{}@math{\sigma^2}
20589@infoline square
20590of the standard deviation, i.e., the sum of the
20591squares of the deviations of the data values from the mean.
20592(This definition also applies when the argument is a distribution.)
20593
20594@ignore
20595@starindex
20596@end ignore
20597@tindex vflat
20598The @code{vflat} algebraic function returns a vector of its
20599arguments, interpreted in the same way as the other functions
20600in this section. For example, @samp{vflat(1, [2, [3, 4]], 5)}
20601returns @samp{[1, 2, 3, 4, 5]}.
20602
20603@node Paired-Sample Statistics, , Single-Variable Statistics, Statistical Operations
20604@subsection Paired-Sample Statistics
20605
20606@noindent
20607The functions in this section take two arguments, which must be
20608vectors of equal size. The vectors are each flattened in the same
20609way as by the single-variable statistical functions. Given a numeric
20610prefix argument of 1, these functions instead take one object from
20611the stack, which must be an
20612@texline @math{N\times2}
20613@infoline Nx2
20614matrix of data values. Once again, variable names can be used in place
20615of actual vectors and matrices.
20616
20617@kindex u C
20618@pindex calc-vector-covariance
20619@tindex vcov
20620@cindex Covariance
20621The @kbd{u C} (@code{calc-vector-covariance}) [@code{vcov}] command
20622computes the sample covariance of two vectors. The covariance
20623of vectors @var{x} and @var{y} is the sum of the products of the
20624differences between the elements of @var{x} and the mean of @var{x}
20625times the differences between the corresponding elements of @var{y}
20626and the mean of @var{y}, all divided by @expr{N-1}. Note that
20627the variance of a vector is just the covariance of the vector
20628with itself. Once again, if the inputs are error forms the
20629errors are used as weight factors. If both @var{x} and @var{y}
20630are composed of error forms, the error for a given data point
20631is taken as the square root of the sum of the squares of the two
20632input errors.
20633@tex
20634\turnoffactive
20635$$ \sigma_{x\!y}^2 = {1 \over N-1} \sum (x_i - \mu_x) (y_i - \mu_y) $$
20636$$ \sigma_{x\!y}^2 =
20637 {\displaystyle {1 \over N-1}
20638 \sum {(x_i - \mu_x) (y_i - \mu_y) \over \sigma_i^2}
20639 \over \displaystyle {1 \over N} \sum {1 \over \sigma_i^2}}
20640$$
20641@end tex
20642
20643@kindex I u C
20644@pindex calc-vector-pop-covariance
20645@tindex vpcov
20646The @kbd{I u C} (@code{calc-vector-pop-covariance}) [@code{vpcov}]
20647command computes the population covariance, which is the same as the
20648sample covariance computed by @kbd{u C} except dividing by @expr{N}
20649instead of @expr{N-1}.
20650
20651@kindex H u C
20652@pindex calc-vector-correlation
20653@tindex vcorr
20654@cindex Correlation coefficient
20655@cindex Linear correlation
20656The @kbd{H u C} (@code{calc-vector-correlation}) [@code{vcorr}]
20657command computes the linear correlation coefficient of two vectors.
20658This is defined by the covariance of the vectors divided by the
20659product of their standard deviations. (There is no difference
20660between sample or population statistics here.)
20661@tex
20662\turnoffactive
20663$$ r_{x\!y} = { \sigma_{x\!y}^2 \over \sigma_x^2 \sigma_y^2 } $$
20664@end tex
20665
20666@node Reducing and Mapping, Vector and Matrix Formats, Statistical Operations, Matrix Functions
20667@section Reducing and Mapping Vectors
20668
20669@noindent
20670The commands in this section allow for more general operations on the
20671elements of vectors.
20672
20673@kindex V A
20674@pindex calc-apply
20675@tindex apply
20676The simplest of these operations is @kbd{V A} (@code{calc-apply})
20677[@code{apply}], which applies a given operator to the elements of a vector.
20678For example, applying the hypothetical function @code{f} to the vector
20679@w{@samp{[1, 2, 3]}} would produce the function call @samp{f(1, 2, 3)}.
20680Applying the @code{+} function to the vector @samp{[a, b]} gives
20681@samp{a + b}. Applying @code{+} to the vector @samp{[a, b, c]} is an
20682error, since the @code{+} function expects exactly two arguments.
20683
20684While @kbd{V A} is useful in some cases, you will usually find that either
20685@kbd{V R} or @kbd{V M}, described below, is closer to what you want.
20686
20687@menu
20688* Specifying Operators::
20689* Mapping::
20690* Reducing::
20691* Nesting and Fixed Points::
20692* Generalized Products::
20693@end menu
20694
20695@node Specifying Operators, Mapping, Reducing and Mapping, Reducing and Mapping
20696@subsection Specifying Operators
20697
20698@noindent
20699Commands in this section (like @kbd{V A}) prompt you to press the key
20700corresponding to the desired operator. Press @kbd{?} for a partial
20701list of the available operators. Generally, an operator is any key or
20702sequence of keys that would normally take one or more arguments from
20703the stack and replace them with a result. For example, @kbd{V A H C}
20704uses the hyperbolic cosine operator, @code{cosh}. (Since @code{cosh}
20705expects one argument, @kbd{V A H C} requires a vector with a single
20706element as its argument.)
20707
20708You can press @kbd{x} at the operator prompt to select any algebraic
20709function by name to use as the operator. This includes functions you
20710have defined yourself using the @kbd{Z F} command. (@xref{Algebraic
20711Definitions}.) If you give a name for which no function has been
20712defined, the result is left in symbolic form, as in @samp{f(1, 2, 3)}.
20713Calc will prompt for the number of arguments the function takes if it
20714can't figure it out on its own (say, because you named a function that
20715is currently undefined). It is also possible to type a digit key before
20716the function name to specify the number of arguments, e.g.,
20717@kbd{V M 3 x f @key{RET}} calls @code{f} with three arguments even if it
20718looks like it ought to have only two. This technique may be necessary
20719if the function allows a variable number of arguments. For example,
20720the @kbd{v e} [@code{vexp}] function accepts two or three arguments;
20721if you want to map with the three-argument version, you will have to
20722type @kbd{V M 3 v e}.
20723
20724It is also possible to apply any formula to a vector by treating that
20725formula as a function. When prompted for the operator to use, press
20726@kbd{'} (the apostrophe) and type your formula as an algebraic entry.
20727You will then be prompted for the argument list, which defaults to a
20728list of all variables that appear in the formula, sorted into alphabetic
20729order. For example, suppose you enter the formula @w{@samp{x + 2y^x}}.
20730The default argument list would be @samp{(x y)}, which means that if
20731this function is applied to the arguments @samp{[3, 10]} the result will
20732be @samp{3 + 2*10^3}. (If you plan to use a certain formula in this
20733way often, you might consider defining it as a function with @kbd{Z F}.)
20734
20735Another way to specify the arguments to the formula you enter is with
20736@kbd{$}, @kbd{$$}, and so on. For example, @kbd{V A ' $$ + 2$^$$}
20737has the same effect as the previous example. The argument list is
20738automatically taken to be @samp{($$ $)}. (The order of the arguments
20739may seem backwards, but it is analogous to the way normal algebraic
20740entry interacts with the stack.)
20741
20742If you press @kbd{$} at the operator prompt, the effect is similar to
20743the apostrophe except that the relevant formula is taken from top-of-stack
20744instead. The actual vector arguments of the @kbd{V A $} or related command
20745then start at the second-to-top stack position. You will still be
20746prompted for an argument list.
20747
20748@cindex Nameless functions
20749@cindex Generic functions
20750A function can be written without a name using the notation @samp{<#1 - #2>},
20751which means ``a function of two arguments that computes the first
20752argument minus the second argument.'' The symbols @samp{#1} and @samp{#2}
20753are placeholders for the arguments. You can use any names for these
20754placeholders if you wish, by including an argument list followed by a
20755colon: @samp{<x, y : x - y>}. When you type @kbd{V A ' $$ + 2$^$$ @key{RET}},
20756Calc builds the nameless function @samp{<#1 + 2 #2^#1>} as the function
20757to map across the vectors. When you type @kbd{V A ' x + 2y^x @key{RET} @key{RET}},
20758Calc builds the nameless function @w{@samp{<x, y : x + 2 y^x>}}. In both
20759cases, Calc also writes the nameless function to the Trail so that you
20760can get it back later if you wish.
20761
20762If there is only one argument, you can write @samp{#} in place of @samp{#1}.
20763(Note that @samp{< >} notation is also used for date forms. Calc tells
20764that @samp{<@var{stuff}>} is a nameless function by the presence of
20765@samp{#} signs inside @var{stuff}, or by the fact that @var{stuff}
20766begins with a list of variables followed by a colon.)
20767
20768You can type a nameless function directly to @kbd{V A '}, or put one on
20769the stack and use it with @w{@kbd{V A $}}. Calc will not prompt for an
20770argument list in this case, since the nameless function specifies the
20771argument list as well as the function itself. In @kbd{V A '}, you can
20772omit the @samp{< >} marks if you use @samp{#} notation for the arguments,
20773so that @kbd{V A ' #1+#2 @key{RET}} is the same as @kbd{V A ' <#1+#2> @key{RET}},
20774which in turn is the same as @kbd{V A ' $$+$ @key{RET}}.
20775
20776@cindex Lambda expressions
20777@ignore
20778@starindex
20779@end ignore
20780@tindex lambda
20781The internal format for @samp{<x, y : x + y>} is @samp{lambda(x, y, x + y)}.
20782(The word @code{lambda} derives from Lisp notation and the theory of
20783functions.) The internal format for @samp{<#1 + #2>} is @samp{lambda(ArgA,
20784ArgB, ArgA + ArgB)}. Note that there is no actual Calc function called
20785@code{lambda}; the whole point is that the @code{lambda} expression is
20786used in its symbolic form, not evaluated for an answer until it is applied
20787to specific arguments by a command like @kbd{V A} or @kbd{V M}.
20788
20789(Actually, @code{lambda} does have one special property: Its arguments
20790are never evaluated; for example, putting @samp{<(2/3) #>} on the stack
20791will not simplify the @samp{2/3} until the nameless function is actually
20792called.)
20793
20794@tindex add
20795@tindex sub
20796@ignore
20797@mindex @idots
20798@end ignore
20799@tindex mul
20800@ignore
20801@mindex @null
20802@end ignore
20803@tindex div
20804@ignore
20805@mindex @null
20806@end ignore
20807@tindex pow
20808@ignore
20809@mindex @null
20810@end ignore
20811@tindex neg
20812@ignore
20813@mindex @null
20814@end ignore
20815@tindex mod
20816@ignore
20817@mindex @null
20818@end ignore
20819@tindex vconcat
20820As usual, commands like @kbd{V A} have algebraic function name equivalents.
20821For example, @kbd{V A k g} with an argument of @samp{v} is equivalent to
20822@samp{apply(gcd, v)}. The first argument specifies the operator name,
20823and is either a variable whose name is the same as the function name,
20824or a nameless function like @samp{<#^3+1>}. Operators that are normally
20825written as algebraic symbols have the names @code{add}, @code{sub},
20826@code{mul}, @code{div}, @code{pow}, @code{neg}, @code{mod}, and
20827@code{vconcat}.
20828
20829@ignore
20830@starindex
20831@end ignore
20832@tindex call
20833The @code{call} function builds a function call out of several arguments:
20834@samp{call(gcd, x, y)} is the same as @samp{apply(gcd, [x, y])}, which
20835in turn is the same as @samp{gcd(x, y)}. The first argument of @code{call},
20836like the other functions described here, may be either a variable naming a
20837function, or a nameless function (@samp{call(<#1+2#2>, x, y)} is the same
20838as @samp{x + 2y}).
20839
20840(Experts will notice that it's not quite proper to use a variable to name
20841a function, since the name @code{gcd} corresponds to the Lisp variable
20842@code{var-gcd} but to the Lisp function @code{calcFunc-gcd}. Calc
20843automatically makes this translation, so you don't have to worry
20844about it.)
20845
20846@node Mapping, Reducing, Specifying Operators, Reducing and Mapping
20847@subsection Mapping
20848
20849@noindent
20850@kindex V M
20851@pindex calc-map
20852@tindex map
20853The @kbd{V M} (@code{calc-map}) [@code{map}] command applies a given
20854operator elementwise to one or more vectors. For example, mapping
20855@code{A} [@code{abs}] produces a vector of the absolute values of the
20856elements in the input vector. Mapping @code{+} pops two vectors from
20857the stack, which must be of equal length, and produces a vector of the
20858pairwise sums of the elements. If either argument is a non-vector, it
20859is duplicated for each element of the other vector. For example,
20860@kbd{[1,2,3] 2 V M ^} squares the elements of the specified vector.
20861With the 2 listed first, it would have computed a vector of powers of
20862two. Mapping a user-defined function pops as many arguments from the
20863stack as the function requires. If you give an undefined name, you will
20864be prompted for the number of arguments to use.
20865
20866If any argument to @kbd{V M} is a matrix, the operator is normally mapped
20867across all elements of the matrix. For example, given the matrix
20868@expr{[[1, -2, 3], [-4, 5, -6]]}, @kbd{V M A} takes six absolute values to
20869produce another
20870@texline @math{3\times2}
20871@infoline 3x2
20872matrix, @expr{[[1, 2, 3], [4, 5, 6]]}.
20873
20874@tindex mapr
20875The command @kbd{V M _} [@code{mapr}] (i.e., type an underscore at the
20876operator prompt) maps by rows instead. For example, @kbd{V M _ A} views
20877the above matrix as a vector of two 3-element row vectors. It produces
20878a new vector which contains the absolute values of those row vectors,
20879namely @expr{[3.74, 8.77]}. (Recall, the absolute value of a vector is
20880defined as the square root of the sum of the squares of the elements.)
20881Some operators accept vectors and return new vectors; for example,
20882@kbd{v v} reverses a vector, so @kbd{V M _ v v} would reverse each row
20883of the matrix to get a new matrix, @expr{[[3, -2, 1], [-6, 5, -4]]}.
20884
20885Sometimes a vector of vectors (representing, say, strings, sets, or lists)
20886happens to look like a matrix. If so, remember to use @kbd{V M _} if you
20887want to map a function across the whole strings or sets rather than across
20888their individual elements.
20889
20890@tindex mapc
20891The command @kbd{V M :} [@code{mapc}] maps by columns. Basically, it
20892transposes the input matrix, maps by rows, and then, if the result is a
20893matrix, transposes again. For example, @kbd{V M : A} takes the absolute
20894values of the three columns of the matrix, treating each as a 2-vector,
20895and @kbd{V M : v v} reverses the columns to get the matrix
20896@expr{[[-4, 5, -6], [1, -2, 3]]}.
20897
20898(The symbols @kbd{_} and @kbd{:} were chosen because they had row-like
20899and column-like appearances, and were not already taken by useful
20900operators. Also, they appear shifted on most keyboards so they are easy
20901to type after @kbd{V M}.)
20902
20903The @kbd{_} and @kbd{:} modifiers have no effect on arguments that are
20904not matrices (so if none of the arguments are matrices, they have no
20905effect at all). If some of the arguments are matrices and others are
20906plain numbers, the plain numbers are held constant for all rows of the
20907matrix (so that @kbd{2 V M _ ^} squares every row of a matrix; squaring
20908a vector takes a dot product of the vector with itself).
20909
20910If some of the arguments are vectors with the same lengths as the
20911rows (for @kbd{V M _}) or columns (for @kbd{V M :}) of the matrix
20912arguments, those vectors are also held constant for every row or
20913column.
20914
20915Sometimes it is useful to specify another mapping command as the operator
20916to use with @kbd{V M}. For example, @kbd{V M _ V A +} applies @kbd{V A +}
20917to each row of the input matrix, which in turn adds the two values on that
20918row. If you give another vector-operator command as the operator for
20919@kbd{V M}, it automatically uses map-by-rows mode if you don't specify
20920otherwise; thus @kbd{V M V A +} is equivalent to @kbd{V M _ V A +}. (If
20921you really want to map-by-elements another mapping command, you can use
20922a triple-nested mapping command: @kbd{V M V M V A +} means to map
20923@kbd{V M V A +} over the rows of the matrix; in turn, @kbd{V A +} is
20924mapped over the elements of each row.)
20925
20926@tindex mapa
20927@tindex mapd
20928Previous versions of Calc had ``map across'' and ``map down'' modes
20929that are now considered obsolete; the old ``map across'' is now simply
20930@kbd{V M V A}, and ``map down'' is now @kbd{V M : V A}. The algebraic
20931functions @code{mapa} and @code{mapd} are still supported, though.
20932Note also that, while the old mapping modes were persistent (once you
20933set the mode, it would apply to later mapping commands until you reset
20934it), the new @kbd{:} and @kbd{_} modifiers apply only to the current
20935mapping command. The default @kbd{V M} always means map-by-elements.
20936
20937@xref{Algebraic Manipulation}, for the @kbd{a M} command, which is like
20938@kbd{V M} but for equations and inequalities instead of vectors.
20939@xref{Storing Variables}, for the @kbd{s m} command which modifies a
20940variable's stored value using a @kbd{V M}-like operator.
20941
20942@node Reducing, Nesting and Fixed Points, Mapping, Reducing and Mapping
20943@subsection Reducing
20944
20945@noindent
20946@kindex V R
20947@pindex calc-reduce
20948@tindex reduce
20949The @kbd{V R} (@code{calc-reduce}) [@code{reduce}] command applies a given
20950binary operator across all the elements of a vector. A binary operator is
20951a function such as @code{+} or @code{max} which takes two arguments. For
20952example, reducing @code{+} over a vector computes the sum of the elements
20953of the vector. Reducing @code{-} computes the first element minus each of
20954the remaining elements. Reducing @code{max} computes the maximum element
20955and so on. In general, reducing @code{f} over the vector @samp{[a, b, c, d]}
20956produces @samp{f(f(f(a, b), c), d)}.
20957
20958@kindex I V R
20959@tindex rreduce
20960The @kbd{I V R} [@code{rreduce}] command is similar to @kbd{V R} except
20961that works from right to left through the vector. For example, plain
20962@kbd{V R -} on the vector @samp{[a, b, c, d]} produces @samp{a - b - c - d}
20963but @kbd{I V R -} on the same vector produces @samp{a - (b - (c - d))},
20964or @samp{a - b + c - d}. This ``alternating sum'' occurs frequently
20965in power series expansions.
20966
20967@kindex V U
20968@tindex accum
20969The @kbd{V U} (@code{calc-accumulate}) [@code{accum}] command does an
20970accumulation operation. Here Calc does the corresponding reduction
20971operation, but instead of producing only the final result, it produces
20972a vector of all the intermediate results. Accumulating @code{+} over
20973the vector @samp{[a, b, c, d]} produces the vector
20974@samp{[a, a + b, a + b + c, a + b + c + d]}.
20975
20976@kindex I V U
20977@tindex raccum
20978The @kbd{I V U} [@code{raccum}] command does a right-to-left accumulation.
20979For example, @kbd{I V U -} on the vector @samp{[a, b, c, d]} produces the
20980vector @samp{[a - b + c - d, b - c + d, c - d, d]}.
20981
20982@tindex reducea
20983@tindex rreducea
20984@tindex reduced
20985@tindex rreduced
20986As for @kbd{V M}, @kbd{V R} normally reduces a matrix elementwise. For
20987example, given the matrix @expr{[[a, b, c], [d, e, f]]}, @kbd{V R +} will
20988compute @expr{a + b + c + d + e + f}. You can type @kbd{V R _} or
20989@kbd{V R :} to modify this behavior. The @kbd{V R _} [@code{reducea}]
20990command reduces ``across'' the matrix; it reduces each row of the matrix
20991as a vector, then collects the results. Thus @kbd{V R _ +} of this
20992matrix would produce @expr{[a + b + c, d + e + f]}. Similarly, @kbd{V R :}
20993[@code{reduced}] reduces down; @kbd{V R : +} would produce @expr{[a + d,
20994b + e, c + f]}.
20995
20996@tindex reducer
20997@tindex rreducer
20998There is a third ``by rows'' mode for reduction that is occasionally
20999useful; @kbd{V R =} [@code{reducer}] simply reduces the operator over
21000the rows of the matrix themselves. Thus @kbd{V R = +} on the above
21001matrix would get the same result as @kbd{V R : +}, since adding two
21002row vectors is equivalent to adding their elements. But @kbd{V R = *}
21003would multiply the two rows (to get a single number, their dot product),
21004while @kbd{V R : *} would produce a vector of the products of the columns.
21005
21006These three matrix reduction modes work with @kbd{V R} and @kbd{I V R},
21007but they are not currently supported with @kbd{V U} or @kbd{I V U}.
21008
21009@tindex reducec
21010@tindex rreducec
21011The obsolete reduce-by-columns function, @code{reducec}, is still
21012supported but there is no way to get it through the @kbd{V R} command.
21013
21014The commands @kbd{C-x * :} and @kbd{C-x * _} are equivalent to typing
21015@kbd{C-x * r} to grab a rectangle of data into Calc, and then typing
21016@kbd{V R : +} or @kbd{V R _ +}, respectively, to sum the columns or
21017rows of the matrix. @xref{Grabbing From Buffers}.
21018
21019@node Nesting and Fixed Points, Generalized Products, Reducing, Reducing and Mapping
21020@subsection Nesting and Fixed Points
21021
21022@noindent
21023@kindex H V R
21024@tindex nest
21025The @kbd{H V R} [@code{nest}] command applies a function to a given
21026argument repeatedly. It takes two values, @samp{a} and @samp{n}, from
21027the stack, where @samp{n} must be an integer. It then applies the
21028function nested @samp{n} times; if the function is @samp{f} and @samp{n}
21029is 3, the result is @samp{f(f(f(a)))}. The number @samp{n} may be
21030negative if Calc knows an inverse for the function @samp{f}; for
21031example, @samp{nest(sin, a, -2)} returns @samp{arcsin(arcsin(a))}.
21032
21033@kindex H V U
21034@tindex anest
21035The @kbd{H V U} [@code{anest}] command is an accumulating version of
21036@code{nest}: It returns a vector of @samp{n+1} values, e.g.,
21037@samp{[a, f(a), f(f(a)), f(f(f(a)))]}. If @samp{n} is negative and
21038@samp{F} is the inverse of @samp{f}, then the result is of the
21039form @samp{[a, F(a), F(F(a)), F(F(F(a)))]}.
21040
21041@kindex H I V R
21042@tindex fixp
21043@cindex Fixed points
21044The @kbd{H I V R} [@code{fixp}] command is like @kbd{H V R}, except
21045that it takes only an @samp{a} value from the stack; the function is
21046applied until it reaches a ``fixed point,'' i.e., until the result
21047no longer changes.
21048
21049@kindex H I V U
21050@tindex afixp
21051The @kbd{H I V U} [@code{afixp}] command is an accumulating @code{fixp}.
21052The first element of the return vector will be the initial value @samp{a};
21053the last element will be the final result that would have been returned
21054by @code{fixp}.
21055
21056For example, 0.739085 is a fixed point of the cosine function (in radians):
21057@samp{cos(0.739085) = 0.739085}. You can find this value by putting, say,
210581.0 on the stack and typing @kbd{H I V U C}. (We use the accumulating
21059version so we can see the intermediate results: @samp{[1, 0.540302, 0.857553,
210600.65329, ...]}. With a precision of six, this command will take 36 steps
21061to converge to 0.739085.)
21062
21063Newton's method for finding roots is a classic example of iteration
21064to a fixed point. To find the square root of five starting with an
21065initial guess, Newton's method would look for a fixed point of the
21066function @samp{(x + 5/x) / 2}. Putting a guess of 1 on the stack
21067and typing @kbd{H I V R ' ($ + 5/$)/2 @key{RET}} quickly yields the result
210682.23607. This is equivalent to using the @kbd{a R} (@code{calc-find-root})
21069command to find a root of the equation @samp{x^2 = 5}.
21070
21071These examples used numbers for @samp{a} values. Calc keeps applying
21072the function until two successive results are equal to within the
21073current precision. For complex numbers, both the real parts and the
21074imaginary parts must be equal to within the current precision. If
21075@samp{a} is a formula (say, a variable name), then the function is
21076applied until two successive results are exactly the same formula.
21077It is up to you to ensure that the function will eventually converge;
21078if it doesn't, you may have to press @kbd{C-g} to stop the Calculator.
21079
21080The algebraic @code{fixp} function takes two optional arguments, @samp{n}
21081and @samp{tol}. The first is the maximum number of steps to be allowed,
21082and must be either an integer or the symbol @samp{inf} (infinity, the
21083default). The second is a convergence tolerance. If a tolerance is
21084specified, all results during the calculation must be numbers, not
21085formulas, and the iteration stops when the magnitude of the difference
21086between two successive results is less than or equal to the tolerance.
21087(This implies that a tolerance of zero iterates until the results are
21088exactly equal.)
21089
21090Putting it all together, @samp{fixp(<(# + A/#)/2>, B, 20, 1e-10)}
21091computes the square root of @samp{A} given the initial guess @samp{B},
21092stopping when the result is correct within the specified tolerance, or
21093when 20 steps have been taken, whichever is sooner.
21094
21095@node Generalized Products, , Nesting and Fixed Points, Reducing and Mapping
21096@subsection Generalized Products
21097
21098@kindex V O
21099@pindex calc-outer-product
21100@tindex outer
21101The @kbd{V O} (@code{calc-outer-product}) [@code{outer}] command applies
21102a given binary operator to all possible pairs of elements from two
21103vectors, to produce a matrix. For example, @kbd{V O *} with @samp{[a, b]}
21104and @samp{[x, y, z]} on the stack produces a multiplication table:
21105@samp{[[a x, a y, a z], [b x, b y, b z]]}. Element @var{r},@var{c} of
21106the result matrix is obtained by applying the operator to element @var{r}
21107of the lefthand vector and element @var{c} of the righthand vector.
21108
21109@kindex V I
21110@pindex calc-inner-product
21111@tindex inner
21112The @kbd{V I} (@code{calc-inner-product}) [@code{inner}] command computes
21113the generalized inner product of two vectors or matrices, given a
21114``multiplicative'' operator and an ``additive'' operator. These can each
21115actually be any binary operators; if they are @samp{*} and @samp{+},
21116respectively, the result is a standard matrix multiplication. Element
21117@var{r},@var{c} of the result matrix is obtained by mapping the
21118multiplicative operator across row @var{r} of the lefthand matrix and
21119column @var{c} of the righthand matrix, and then reducing with the additive
21120operator. Just as for the standard @kbd{*} command, this can also do a
21121vector-matrix or matrix-vector inner product, or a vector-vector
21122generalized dot product.
21123
21124Since @kbd{V I} requires two operators, it prompts twice. In each case,
21125you can use any of the usual methods for entering the operator. If you
21126use @kbd{$} twice to take both operator formulas from the stack, the
21127first (multiplicative) operator is taken from the top of the stack
21128and the second (additive) operator is taken from second-to-top.
21129
21130@node Vector and Matrix Formats, , Reducing and Mapping, Matrix Functions
21131@section Vector and Matrix Display Formats
21132
21133@noindent
21134Commands for controlling vector and matrix display use the @kbd{v} prefix
21135instead of the usual @kbd{d} prefix. But they are display modes; in
21136particular, they are influenced by the @kbd{I} and @kbd{H} prefix keys
21137in the same way (@pxref{Display Modes}). Matrix display is also
21138influenced by the @kbd{d O} (@code{calc-flat-language}) mode;
21139@pxref{Normal Language Modes}.
21140
21141@kindex V <
21142@pindex calc-matrix-left-justify
21143@kindex V =
21144@pindex calc-matrix-center-justify
21145@kindex V >
21146@pindex calc-matrix-right-justify
21147The commands @kbd{v <} (@code{calc-matrix-left-justify}), @kbd{v >}
21148(@code{calc-matrix-right-justify}), and @w{@kbd{v =}}
21149(@code{calc-matrix-center-justify}) control whether matrix elements
21150are justified to the left, right, or center of their columns.
21151
21152@kindex V [
21153@pindex calc-vector-brackets
21154@kindex V @{
21155@pindex calc-vector-braces
21156@kindex V (
21157@pindex calc-vector-parens
21158The @kbd{v [} (@code{calc-vector-brackets}) command turns the square
21159brackets that surround vectors and matrices displayed in the stack on
21160and off. The @kbd{v @{} (@code{calc-vector-braces}) and @kbd{v (}
21161(@code{calc-vector-parens}) commands use curly braces or parentheses,
21162respectively, instead of square brackets. For example, @kbd{v @{} might
21163be used in preparation for yanking a matrix into a buffer running
21164Mathematica. (In fact, the Mathematica language mode uses this mode;
21165@pxref{Mathematica Language Mode}.) Note that, regardless of the
21166display mode, either brackets or braces may be used to enter vectors,
21167and parentheses may never be used for this purpose.
21168
21169@kindex V ]
21170@pindex calc-matrix-brackets
21171The @kbd{v ]} (@code{calc-matrix-brackets}) command controls the
21172``big'' style display of matrices. It prompts for a string of code
21173letters; currently implemented letters are @code{R}, which enables
21174brackets on each row of the matrix; @code{O}, which enables outer
21175brackets in opposite corners of the matrix; and @code{C}, which
21176enables commas or semicolons at the ends of all rows but the last.
21177The default format is @samp{RO}. (Before Calc 2.00, the format
21178was fixed at @samp{ROC}.) Here are some example matrices:
21179
21180@example
21181@group
21182[ [ 123, 0, 0 ] [ [ 123, 0, 0 ],
21183 [ 0, 123, 0 ] [ 0, 123, 0 ],
21184 [ 0, 0, 123 ] ] [ 0, 0, 123 ] ]
21185
21186 RO ROC
21187
21188@end group
21189@end example
21190@noindent
21191@example
21192@group
21193 [ 123, 0, 0 [ 123, 0, 0 ;
21194 0, 123, 0 0, 123, 0 ;
21195 0, 0, 123 ] 0, 0, 123 ]
21196
21197 O OC
21198
21199@end group
21200@end example
21201@noindent
21202@example
21203@group
21204 [ 123, 0, 0 ] 123, 0, 0
21205 [ 0, 123, 0 ] 0, 123, 0
21206 [ 0, 0, 123 ] 0, 0, 123
21207
21208 R @r{blank}
21209@end group
21210@end example
21211
21212@noindent
21213Note that of the formats shown here, @samp{RO}, @samp{ROC}, and
21214@samp{OC} are all recognized as matrices during reading, while
21215the others are useful for display only.
21216
21217@kindex V ,
21218@pindex calc-vector-commas
21219The @kbd{v ,} (@code{calc-vector-commas}) command turns commas on and
21220off in vector and matrix display.
21221
21222In vectors of length one, and in all vectors when commas have been
21223turned off, Calc adds extra parentheses around formulas that might
21224otherwise be ambiguous. For example, @samp{[a b]} could be a vector
21225of the one formula @samp{a b}, or it could be a vector of two
21226variables with commas turned off. Calc will display the former
21227case as @samp{[(a b)]}. You can disable these extra parentheses
21228(to make the output less cluttered at the expense of allowing some
21229ambiguity) by adding the letter @code{P} to the control string you
21230give to @kbd{v ]} (as described above).
21231
21232@kindex V .
21233@pindex calc-full-vectors
21234The @kbd{v .} (@code{calc-full-vectors}) command turns abbreviated
21235display of long vectors on and off. In this mode, vectors of six
21236or more elements, or matrices of six or more rows or columns, will
21237be displayed in an abbreviated form that displays only the first
21238three elements and the last element: @samp{[a, b, c, ..., z]}.
21239When very large vectors are involved this will substantially
21240improve Calc's display speed.
21241
21242@kindex t .
21243@pindex calc-full-trail-vectors
21244The @kbd{t .} (@code{calc-full-trail-vectors}) command controls a
21245similar mode for recording vectors in the Trail. If you turn on
21246this mode, vectors of six or more elements and matrices of six or
21247more rows or columns will be abbreviated when they are put in the
21248Trail. The @kbd{t y} (@code{calc-trail-yank}) command will be
21249unable to recover those vectors. If you are working with very
21250large vectors, this mode will improve the speed of all operations
21251that involve the trail.
21252
21253@kindex V /
21254@pindex calc-break-vectors
21255The @kbd{v /} (@code{calc-break-vectors}) command turns multi-line
21256vector display on and off. Normally, matrices are displayed with one
21257row per line but all other types of vectors are displayed in a single
21258line. This mode causes all vectors, whether matrices or not, to be
21259displayed with a single element per line. Sub-vectors within the
21260vectors will still use the normal linear form.
21261
21262@node Algebra, Units, Matrix Functions, Top
21263@chapter Algebra
21264
21265@noindent
21266This section covers the Calc features that help you work with
21267algebraic formulas. First, the general sub-formula selection
21268mechanism is described; this works in conjunction with any Calc
21269commands. Then, commands for specific algebraic operations are
21270described. Finally, the flexible @dfn{rewrite rule} mechanism
21271is discussed.
21272
21273The algebraic commands use the @kbd{a} key prefix; selection
21274commands use the @kbd{j} (for ``just a letter that wasn't used
21275for anything else'') prefix.
21276
21277@xref{Editing Stack Entries}, to see how to manipulate formulas
21278using regular Emacs editing commands.
21279
21280When doing algebraic work, you may find several of the Calculator's
21281modes to be helpful, including Algebraic Simplification mode (@kbd{m A})
21282or No-Simplification mode (@kbd{m O}),
21283Algebraic entry mode (@kbd{m a}), Fraction mode (@kbd{m f}), and
21284Symbolic mode (@kbd{m s}). @xref{Mode Settings}, for discussions
21285of these modes. You may also wish to select Big display mode (@kbd{d B}).
21286@xref{Normal Language Modes}.
21287
21288@menu
21289* Selecting Subformulas::
21290* Algebraic Manipulation::
21291* Simplifying Formulas::
21292* Polynomials::
21293* Calculus::
21294* Solving Equations::
21295* Numerical Solutions::
21296* Curve Fitting::
21297* Summations::
21298* Logical Operations::
21299* Rewrite Rules::
21300@end menu
21301
21302@node Selecting Subformulas, Algebraic Manipulation, Algebra, Algebra
21303@section Selecting Sub-Formulas
21304
21305@noindent
21306@cindex Selections
21307@cindex Sub-formulas
21308@cindex Parts of formulas
21309When working with an algebraic formula it is often necessary to
21310manipulate a portion of the formula rather than the formula as a
21311whole. Calc allows you to ``select'' a portion of any formula on
21312the stack. Commands which would normally operate on that stack
21313entry will now operate only on the sub-formula, leaving the
21314surrounding part of the stack entry alone.
21315
21316One common non-algebraic use for selection involves vectors. To work
21317on one element of a vector in-place, simply select that element as a
21318``sub-formula'' of the vector.
21319
21320@menu
21321* Making Selections::
21322* Changing Selections::
21323* Displaying Selections::
21324* Operating on Selections::
21325* Rearranging with Selections::
21326@end menu
21327
21328@node Making Selections, Changing Selections, Selecting Subformulas, Selecting Subformulas
21329@subsection Making Selections
21330
21331@noindent
21332@kindex j s
21333@pindex calc-select-here
21334To select a sub-formula, move the Emacs cursor to any character in that
21335sub-formula, and press @w{@kbd{j s}} (@code{calc-select-here}). Calc will
21336highlight the smallest portion of the formula that contains that
21337character. By default the sub-formula is highlighted by blanking out
21338all of the rest of the formula with dots. Selection works in any
21339display mode but is perhaps easiest in Big mode (@kbd{d B}).
21340Suppose you enter the following formula:
21341
21342@smallexample
21343@group
21344 3 ___
21345 (a + b) + V c
213461: ---------------
21347 2 x + 1
21348@end group
21349@end smallexample
21350
21351@noindent
21352(by typing @kbd{' ((a+b)^3 + sqrt(c)) / (2x+1)}). If you move the
21353cursor to the letter @samp{b} and press @w{@kbd{j s}}, the display changes
21354to
21355
21356@smallexample
21357@group
21358 . ...
21359 .. . b. . . .
213601* ...............
21361 . . . .
21362@end group
21363@end smallexample
21364
21365@noindent
21366Every character not part of the sub-formula @samp{b} has been changed
21367to a dot. The @samp{*} next to the line number is to remind you that
21368the formula has a portion of it selected. (In this case, it's very
21369obvious, but it might not always be. If Embedded mode is enabled,
21370the word @samp{Sel} also appears in the mode line because the stack
21371may not be visible. @pxref{Embedded Mode}.)
21372
21373If you had instead placed the cursor on the parenthesis immediately to
21374the right of the @samp{b}, the selection would have been:
21375
21376@smallexample
21377@group
21378 . ...
21379 (a + b) . . .
213801* ...............
21381 . . . .
21382@end group
21383@end smallexample
21384
21385@noindent
21386The portion selected is always large enough to be considered a complete
21387formula all by itself, so selecting the parenthesis selects the whole
21388formula that it encloses. Putting the cursor on the @samp{+} sign
21389would have had the same effect.
21390
21391(Strictly speaking, the Emacs cursor is really the manifestation of
21392the Emacs ``point,'' which is a position @emph{between} two characters
21393in the buffer. So purists would say that Calc selects the smallest
21394sub-formula which contains the character to the right of ``point.'')
21395
21396If you supply a numeric prefix argument @var{n}, the selection is
21397expanded to the @var{n}th enclosing sub-formula. Thus, positioning
21398the cursor on the @samp{b} and typing @kbd{C-u 1 j s} will select
21399@samp{a + b}; typing @kbd{C-u 2 j s} will select @samp{(a + b)^3},
21400and so on.
21401
21402If the cursor is not on any part of the formula, or if you give a
21403numeric prefix that is too large, the entire formula is selected.
21404
21405If the cursor is on the @samp{.} line that marks the top of the stack
21406(i.e., its normal ``rest position''), this command selects the entire
21407formula at stack level 1. Most selection commands similarly operate
21408on the formula at the top of the stack if you haven't positioned the
21409cursor on any stack entry.
21410
21411@kindex j a
21412@pindex calc-select-additional
21413The @kbd{j a} (@code{calc-select-additional}) command enlarges the
21414current selection to encompass the cursor. To select the smallest
21415sub-formula defined by two different points, move to the first and
21416press @kbd{j s}, then move to the other and press @kbd{j a}. This
21417is roughly analogous to using @kbd{C-@@} (@code{set-mark-command}) to
21418select the two ends of a region of text during normal Emacs editing.
21419
21420@kindex j o
21421@pindex calc-select-once
21422The @kbd{j o} (@code{calc-select-once}) command selects a formula in
21423exactly the same way as @kbd{j s}, except that the selection will
21424last only as long as the next command that uses it. For example,
21425@kbd{j o 1 +} is a handy way to add one to the sub-formula indicated
21426by the cursor.
21427
21428(A somewhat more precise definition: The @kbd{j o} command sets a flag
21429such that the next command involving selected stack entries will clear
21430the selections on those stack entries afterwards. All other selection
21431commands except @kbd{j a} and @kbd{j O} clear this flag.)
21432
21433@kindex j S
21434@kindex j O
21435@pindex calc-select-here-maybe
21436@pindex calc-select-once-maybe
21437The @kbd{j S} (@code{calc-select-here-maybe}) and @kbd{j O}
21438(@code{calc-select-once-maybe}) commands are equivalent to @kbd{j s}
21439and @kbd{j o}, respectively, except that if the formula already
21440has a selection they have no effect. This is analogous to the
21441behavior of some commands such as @kbd{j r} (@code{calc-rewrite-selection};
21442@pxref{Selections with Rewrite Rules}) and is mainly intended to be
21443used in keyboard macros that implement your own selection-oriented
21444commands.
21445
21446Selection of sub-formulas normally treats associative terms like
21447@samp{a + b - c + d} and @samp{x * y * z} as single levels of the formula.
21448If you place the cursor anywhere inside @samp{a + b - c + d} except
21449on one of the variable names and use @kbd{j s}, you will select the
21450entire four-term sum.
21451
21452@kindex j b
21453@pindex calc-break-selections
21454The @kbd{j b} (@code{calc-break-selections}) command controls a mode
21455in which the ``deep structure'' of these associative formulas shows
45b778a6
JB
21456through. Calc actually stores the above formulas as
21457@samp{((a + b) - c) + d} and @samp{x * (y * z)}. (Note that for certain
21458obscure reasons, by default Calc treats multiplication as
21459right-associative.) Once you have enabled @kbd{j b} mode, selecting
21460with the cursor on the @samp{-} sign would only select the @samp{a + b -
21461c} portion, which makes sense when the deep structure of the sum is
21462considered. There is no way to select the @samp{b - c + d} portion;
21463although this might initially look like just as legitimate a sub-formula
21464as @samp{a + b - c}, the deep structure shows that it isn't. The @kbd{d
21465U} command can be used to view the deep structure of any formula
21466(@pxref{Normal Language Modes}).
4009494e
GM
21467
21468When @kbd{j b} mode has not been enabled, the deep structure is
21469generally hidden by the selection commands---what you see is what
21470you get.
21471
21472@kindex j u
21473@pindex calc-unselect
21474The @kbd{j u} (@code{calc-unselect}) command unselects the formula
21475that the cursor is on. If there was no selection in the formula,
21476this command has no effect. With a numeric prefix argument, it
21477unselects the @var{n}th stack element rather than using the cursor
21478position.
21479
21480@kindex j c
21481@pindex calc-clear-selections
21482The @kbd{j c} (@code{calc-clear-selections}) command unselects all
21483stack elements.
21484
21485@node Changing Selections, Displaying Selections, Making Selections, Selecting Subformulas
21486@subsection Changing Selections
21487
21488@noindent
21489@kindex j m
21490@pindex calc-select-more
21491Once you have selected a sub-formula, you can expand it using the
21492@w{@kbd{j m}} (@code{calc-select-more}) command. If @samp{a + b} is
21493selected, pressing @w{@kbd{j m}} repeatedly works as follows:
21494
21495@smallexample
21496@group
21497 3 ... 3 ___ 3 ___
21498 (a + b) . . . (a + b) + V c (a + b) + V c
214991* ............... 1* ............... 1* ---------------
21500 . . . . . . . . 2 x + 1
21501@end group
21502@end smallexample
21503
21504@noindent
21505In the last example, the entire formula is selected. This is roughly
21506the same as having no selection at all, but because there are subtle
21507differences the @samp{*} character is still there on the line number.
21508
21509With a numeric prefix argument @var{n}, @kbd{j m} expands @var{n}
21510times (or until the entire formula is selected). Note that @kbd{j s}
21511with argument @var{n} is equivalent to plain @kbd{j s} followed by
21512@kbd{j m} with argument @var{n}. If @w{@kbd{j m}} is used when there
21513is no current selection, it is equivalent to @w{@kbd{j s}}.
21514
21515Even though @kbd{j m} does not explicitly use the location of the
21516cursor within the formula, it nevertheless uses the cursor to determine
21517which stack element to operate on. As usual, @kbd{j m} when the cursor
21518is not on any stack element operates on the top stack element.
21519
21520@kindex j l
21521@pindex calc-select-less
21522The @kbd{j l} (@code{calc-select-less}) command reduces the current
21523selection around the cursor position. That is, it selects the
21524immediate sub-formula of the current selection which contains the
21525cursor, the opposite of @kbd{j m}. If the cursor is not inside the
21526current selection, the command de-selects the formula.
21527
21528@kindex j 1-9
21529@pindex calc-select-part
21530The @kbd{j 1} through @kbd{j 9} (@code{calc-select-part}) commands
21531select the @var{n}th sub-formula of the current selection. They are
21532like @kbd{j l} (@code{calc-select-less}) except they use counting
21533rather than the cursor position to decide which sub-formula to select.
21534For example, if the current selection is @kbd{a + b + c} or
21535@kbd{f(a, b, c)} or @kbd{[a, b, c]}, then @kbd{j 1} selects @samp{a},
21536@kbd{j 2} selects @samp{b}, and @kbd{j 3} selects @samp{c}; in each of
21537these cases, @kbd{j 4} through @kbd{j 9} would be errors.
21538
21539If there is no current selection, @kbd{j 1} through @kbd{j 9} select
21540the @var{n}th top-level sub-formula. (In other words, they act as if
21541the entire stack entry were selected first.) To select the @var{n}th
21542sub-formula where @var{n} is greater than nine, you must instead invoke
21543@w{@kbd{j 1}} with @var{n} as a numeric prefix argument.
21544
21545@kindex j n
21546@kindex j p
21547@pindex calc-select-next
21548@pindex calc-select-previous
21549The @kbd{j n} (@code{calc-select-next}) and @kbd{j p}
21550(@code{calc-select-previous}) commands change the current selection
21551to the next or previous sub-formula at the same level. For example,
21552if @samp{b} is selected in @w{@samp{2 + a*b*c + x}}, then @kbd{j n}
21553selects @samp{c}. Further @kbd{j n} commands would be in error because,
21554even though there is something to the right of @samp{c} (namely, @samp{x}),
21555it is not at the same level; in this case, it is not a term of the
21556same product as @samp{b} and @samp{c}. However, @kbd{j m} (to select
21557the whole product @samp{a*b*c} as a term of the sum) followed by
21558@w{@kbd{j n}} would successfully select the @samp{x}.
21559
21560Similarly, @kbd{j p} moves the selection from the @samp{b} in this
21561sample formula to the @samp{a}. Both commands accept numeric prefix
21562arguments to move several steps at a time.
21563
21564It is interesting to compare Calc's selection commands with the
21565Emacs Info system's commands for navigating through hierarchically
21566organized documentation. Calc's @kbd{j n} command is completely
21567analogous to Info's @kbd{n} command. Likewise, @kbd{j p} maps to
21568@kbd{p}, @kbd{j 2} maps to @kbd{2}, and Info's @kbd{u} is like @kbd{j m}.
21569(Note that @kbd{j u} stands for @code{calc-unselect}, not ``up''.)
21570The Info @kbd{m} command is somewhat similar to Calc's @kbd{j s} and
21571@kbd{j l}; in each case, you can jump directly to a sub-component
21572of the hierarchy simply by pointing to it with the cursor.
21573
21574@node Displaying Selections, Operating on Selections, Changing Selections, Selecting Subformulas
21575@subsection Displaying Selections
21576
21577@noindent
21578@kindex j d
21579@pindex calc-show-selections
21580The @kbd{j d} (@code{calc-show-selections}) command controls how
21581selected sub-formulas are displayed. One of the alternatives is
21582illustrated in the above examples; if we press @kbd{j d} we switch
21583to the other style in which the selected portion itself is obscured
21584by @samp{#} signs:
21585
21586@smallexample
21587@group
21588 3 ... # ___
21589 (a + b) . . . ## # ## + V c
215901* ............... 1* ---------------
21591 . . . . 2 x + 1
21592@end group
21593@end smallexample
21594
21595@node Operating on Selections, Rearranging with Selections, Displaying Selections, Selecting Subformulas
21596@subsection Operating on Selections
21597
21598@noindent
21599Once a selection is made, all Calc commands that manipulate items
21600on the stack will operate on the selected portions of the items
21601instead. (Note that several stack elements may have selections
21602at once, though there can be only one selection at a time in any
21603given stack element.)
21604
21605@kindex j e
21606@pindex calc-enable-selections
21607The @kbd{j e} (@code{calc-enable-selections}) command disables the
21608effect that selections have on Calc commands. The current selections
21609still exist, but Calc commands operate on whole stack elements anyway.
21610This mode can be identified by the fact that the @samp{*} markers on
21611the line numbers are gone, even though selections are visible. To
21612reactivate the selections, press @kbd{j e} again.
21613
21614To extract a sub-formula as a new formula, simply select the
21615sub-formula and press @key{RET}. This normally duplicates the top
21616stack element; here it duplicates only the selected portion of that
21617element.
21618
21619To replace a sub-formula with something different, you can enter the
21620new value onto the stack and press @key{TAB}. This normally exchanges
21621the top two stack elements; here it swaps the value you entered into
21622the selected portion of the formula, returning the old selected
21623portion to the top of the stack.
21624
21625@smallexample
21626@group
21627 3 ... ... ___
21628 (a + b) . . . 17 x y . . . 17 x y + V c
216292* ............... 2* ............. 2: -------------
21630 . . . . . . . . 2 x + 1
21631
21632 3 3
216331: 17 x y 1: (a + b) 1: (a + b)
21634@end group
21635@end smallexample
21636
21637In this example we select a sub-formula of our original example,
21638enter a new formula, @key{TAB} it into place, then deselect to see
21639the complete, edited formula.
21640
21641If you want to swap whole formulas around even though they contain
21642selections, just use @kbd{j e} before and after.
21643
21644@kindex j '
21645@pindex calc-enter-selection
21646The @kbd{j '} (@code{calc-enter-selection}) command is another way
21647to replace a selected sub-formula. This command does an algebraic
21648entry just like the regular @kbd{'} key. When you press @key{RET},
21649the formula you type replaces the original selection. You can use
21650the @samp{$} symbol in the formula to refer to the original
21651selection. If there is no selection in the formula under the cursor,
21652the cursor is used to make a temporary selection for the purposes of
21653the command. Thus, to change a term of a formula, all you have to
21654do is move the Emacs cursor to that term and press @kbd{j '}.
21655
21656@kindex j `
21657@pindex calc-edit-selection
21658The @kbd{j `} (@code{calc-edit-selection}) command is a similar
21659analogue of the @kbd{`} (@code{calc-edit}) command. It edits the
21660selected sub-formula in a separate buffer. If there is no
21661selection, it edits the sub-formula indicated by the cursor.
21662
21663To delete a sub-formula, press @key{DEL}. This generally replaces
21664the sub-formula with the constant zero, but in a few suitable contexts
21665it uses the constant one instead. The @key{DEL} key automatically
21666deselects and re-simplifies the entire formula afterwards. Thus:
21667
21668@smallexample
21669@group
21670 ###
21671 17 x y + # # 17 x y 17 # y 17 y
216721* ------------- 1: ------- 1* ------- 1: -------
21673 2 x + 1 2 x + 1 2 x + 1 2 x + 1
21674@end group
21675@end smallexample
21676
21677In this example, we first delete the @samp{sqrt(c)} term; Calc
21678accomplishes this by replacing @samp{sqrt(c)} with zero and
21679resimplifying. We then delete the @kbd{x} in the numerator;
21680since this is part of a product, Calc replaces it with @samp{1}
21681and resimplifies.
21682
21683If you select an element of a vector and press @key{DEL}, that
21684element is deleted from the vector. If you delete one side of
21685an equation or inequality, only the opposite side remains.
21686
21687@kindex j @key{DEL}
21688@pindex calc-del-selection
21689The @kbd{j @key{DEL}} (@code{calc-del-selection}) command is like
21690@key{DEL} but with the auto-selecting behavior of @kbd{j '} and
21691@kbd{j `}. It deletes the selected portion of the formula
21692indicated by the cursor, or, in the absence of a selection, it
21693deletes the sub-formula indicated by the cursor position.
21694
21695@kindex j @key{RET}
21696@pindex calc-grab-selection
21697(There is also an auto-selecting @kbd{j @key{RET}} (@code{calc-copy-selection})
21698command.)
21699
21700Normal arithmetic operations also apply to sub-formulas. Here we
21701select the denominator, press @kbd{5 -} to subtract five from the
21702denominator, press @kbd{n} to negate the denominator, then
21703press @kbd{Q} to take the square root.
21704
21705@smallexample
21706@group
21707 .. . .. . .. . .. .
217081* ....... 1* ....... 1* ....... 1* ..........
21709 2 x + 1 2 x - 4 4 - 2 x _________
21710 V 4 - 2 x
21711@end group
21712@end smallexample
21713
21714Certain types of operations on selections are not allowed. For
21715example, for an arithmetic function like @kbd{-} no more than one of
21716the arguments may be a selected sub-formula. (As the above example
21717shows, the result of the subtraction is spliced back into the argument
21718which had the selection; if there were more than one selection involved,
21719this would not be well-defined.) If you try to subtract two selections,
21720the command will abort with an error message.
21721
21722Operations on sub-formulas sometimes leave the formula as a whole
21723in an ``un-natural'' state. Consider negating the @samp{2 x} term
21724of our sample formula by selecting it and pressing @kbd{n}
21725(@code{calc-change-sign}).
21726
21727@smallexample
21728@group
21729 .. . .. .
217301* .......... 1* ...........
21731 ......... ..........
21732 . . . 2 x . . . -2 x
21733@end group
21734@end smallexample
21735
21736Unselecting the sub-formula reveals that the minus sign, which would
21737normally have cancelled out with the subtraction automatically, has
21738not been able to do so because the subtraction was not part of the
21739selected portion. Pressing @kbd{=} (@code{calc-evaluate}) or doing
21740any other mathematical operation on the whole formula will cause it
21741to be simplified.
21742
21743@smallexample
21744@group
21745 17 y 17 y
217461: ----------- 1: ----------
21747 __________ _________
21748 V 4 - -2 x V 4 + 2 x
21749@end group
21750@end smallexample
21751
21752@node Rearranging with Selections, , Operating on Selections, Selecting Subformulas
21753@subsection Rearranging Formulas using Selections
21754
21755@noindent
21756@kindex j R
21757@pindex calc-commute-right
21758The @kbd{j R} (@code{calc-commute-right}) command moves the selected
21759sub-formula to the right in its surrounding formula. Generally the
21760selection is one term of a sum or product; the sum or product is
21761rearranged according to the commutative laws of algebra.
21762
21763As with @kbd{j '} and @kbd{j @key{DEL}}, the term under the cursor is used
21764if there is no selection in the current formula. All commands described
21765in this section share this property. In this example, we place the
21766cursor on the @samp{a} and type @kbd{j R}, then repeat.
21767
21768@smallexample
217691: a + b - c 1: b + a - c 1: b - c + a
21770@end smallexample
21771
21772@noindent
21773Note that in the final step above, the @samp{a} is switched with
21774the @samp{c} but the signs are adjusted accordingly. When moving
21775terms of sums and products, @kbd{j R} will never change the
21776mathematical meaning of the formula.
21777
21778The selected term may also be an element of a vector or an argument
21779of a function. The term is exchanged with the one to its right.
21780In this case, the ``meaning'' of the vector or function may of
21781course be drastically changed.
21782
21783@smallexample
217841: [a, b, c] 1: [b, a, c] 1: [b, c, a]
21785
217861: f(a, b, c) 1: f(b, a, c) 1: f(b, c, a)
21787@end smallexample
21788
21789@kindex j L
21790@pindex calc-commute-left
21791The @kbd{j L} (@code{calc-commute-left}) command is like @kbd{j R}
21792except that it swaps the selected term with the one to its left.
21793
21794With numeric prefix arguments, these commands move the selected
21795term several steps at a time. It is an error to try to move a
21796term left or right past the end of its enclosing formula.
21797With numeric prefix arguments of zero, these commands move the
21798selected term as far as possible in the given direction.
21799
21800@kindex j D
21801@pindex calc-sel-distribute
21802The @kbd{j D} (@code{calc-sel-distribute}) command mixes the selected
21803sum or product into the surrounding formula using the distributive
21804law. For example, in @samp{a * (b - c)} with the @samp{b - c}
21805selected, the result is @samp{a b - a c}. This also distributes
21806products or quotients into surrounding powers, and can also do
21807transformations like @samp{exp(a + b)} to @samp{exp(a) exp(b)},
21808where @samp{a + b} is the selected term, and @samp{ln(a ^ b)}
21809to @samp{ln(a) b}, where @samp{a ^ b} is the selected term.
21810
21811For multiple-term sums or products, @kbd{j D} takes off one term
21812at a time: @samp{a * (b + c - d)} goes to @samp{a * (c - d) + a b}
21813with the @samp{c - d} selected so that you can type @kbd{j D}
21814repeatedly to expand completely. The @kbd{j D} command allows a
21815numeric prefix argument which specifies the maximum number of
21816times to expand at once; the default is one time only.
21817
21818@vindex DistribRules
21819The @kbd{j D} command is implemented using rewrite rules.
21820@xref{Selections with Rewrite Rules}. The rules are stored in
21821the Calc variable @code{DistribRules}. A convenient way to view
21822these rules is to use @kbd{s e} (@code{calc-edit-variable}) which
21823displays and edits the stored value of a variable. Press @kbd{C-c C-c}
21824to return from editing mode; be careful not to make any actual changes
21825or else you will affect the behavior of future @kbd{j D} commands!
21826
21827To extend @kbd{j D} to handle new cases, just edit @code{DistribRules}
21828as described above. You can then use the @kbd{s p} command to save
21829this variable's value permanently for future Calc sessions.
21830@xref{Operations on Variables}.
21831
21832@kindex j M
21833@pindex calc-sel-merge
21834@vindex MergeRules
21835The @kbd{j M} (@code{calc-sel-merge}) command is the complement
21836of @kbd{j D}; given @samp{a b - a c} with either @samp{a b} or
21837@samp{a c} selected, the result is @samp{a * (b - c)}. Once
21838again, @kbd{j M} can also merge calls to functions like @code{exp}
21839and @code{ln}; examine the variable @code{MergeRules} to see all
21840the relevant rules.
21841
21842@kindex j C
21843@pindex calc-sel-commute
21844@vindex CommuteRules
21845The @kbd{j C} (@code{calc-sel-commute}) command swaps the arguments
21846of the selected sum, product, or equation. It always behaves as
21847if @kbd{j b} mode were in effect, i.e., the sum @samp{a + b + c} is
21848treated as the nested sums @samp{(a + b) + c} by this command.
21849If you put the cursor on the first @samp{+}, the result is
21850@samp{(b + a) + c}; if you put the cursor on the second @samp{+}, the
21851result is @samp{c + (a + b)} (which the default simplifications
21852will rearrange to @samp{(c + a) + b}). The relevant rules are stored
21853in the variable @code{CommuteRules}.
21854
21855You may need to turn default simplifications off (with the @kbd{m O}
21856command) in order to get the full benefit of @kbd{j C}. For example,
21857commuting @samp{a - b} produces @samp{-b + a}, but the default
21858simplifications will ``simplify'' this right back to @samp{a - b} if
21859you don't turn them off. The same is true of some of the other
21860manipulations described in this section.
21861
21862@kindex j N
21863@pindex calc-sel-negate
21864@vindex NegateRules
21865The @kbd{j N} (@code{calc-sel-negate}) command replaces the selected
21866term with the negative of that term, then adjusts the surrounding
21867formula in order to preserve the meaning. For example, given
21868@samp{exp(a - b)} where @samp{a - b} is selected, the result is
21869@samp{1 / exp(b - a)}. By contrast, selecting a term and using the
21870regular @kbd{n} (@code{calc-change-sign}) command negates the
21871term without adjusting the surroundings, thus changing the meaning
21872of the formula as a whole. The rules variable is @code{NegateRules}.
21873
21874@kindex j &
21875@pindex calc-sel-invert
21876@vindex InvertRules
21877The @kbd{j &} (@code{calc-sel-invert}) command is similar to @kbd{j N}
21878except it takes the reciprocal of the selected term. For example,
21879given @samp{a - ln(b)} with @samp{b} selected, the result is
21880@samp{a + ln(1/b)}. The rules variable is @code{InvertRules}.
21881
21882@kindex j E
21883@pindex calc-sel-jump-equals
21884@vindex JumpRules
21885The @kbd{j E} (@code{calc-sel-jump-equals}) command moves the
21886selected term from one side of an equation to the other. Given
21887@samp{a + b = c + d} with @samp{c} selected, the result is
21888@samp{a + b - c = d}. This command also works if the selected
21889term is part of a @samp{*}, @samp{/}, or @samp{^} formula. The
21890relevant rules variable is @code{JumpRules}.
21891
21892@kindex j I
21893@kindex H j I
21894@pindex calc-sel-isolate
21895The @kbd{j I} (@code{calc-sel-isolate}) command isolates the
21896selected term on its side of an equation. It uses the @kbd{a S}
21897(@code{calc-solve-for}) command to solve the equation, and the
21898Hyperbolic flag affects it in the same way. @xref{Solving Equations}.
21899When it applies, @kbd{j I} is often easier to use than @kbd{j E}.
21900It understands more rules of algebra, and works for inequalities
21901as well as equations.
21902
21903@kindex j *
21904@kindex j /
21905@pindex calc-sel-mult-both-sides
21906@pindex calc-sel-div-both-sides
21907The @kbd{j *} (@code{calc-sel-mult-both-sides}) command prompts for a
21908formula using algebraic entry, then multiplies both sides of the
21909selected quotient or equation by that formula. It simplifies each
21910side with @kbd{a s} (@code{calc-simplify}) before re-forming the
21911quotient or equation. You can suppress this simplification by
21912providing any numeric prefix argument. There is also a @kbd{j /}
21913(@code{calc-sel-div-both-sides}) which is similar to @kbd{j *} but
21914dividing instead of multiplying by the factor you enter.
21915
21916As a special feature, if the numerator of the quotient is 1, then
21917the denominator is expanded at the top level using the distributive
21918law (i.e., using the @kbd{C-u -1 a x} command). Suppose the
21919formula on the stack is @samp{1 / (sqrt(a) + 1)}, and you wish
21920to eliminate the square root in the denominator by multiplying both
21921sides by @samp{sqrt(a) - 1}. Calc's default simplifications would
21922change the result @samp{(sqrt(a) - 1) / (sqrt(a) - 1) (sqrt(a) + 1)}
21923right back to the original form by cancellation; Calc expands the
21924denominator to @samp{sqrt(a) (sqrt(a) - 1) + sqrt(a) - 1} to prevent
21925this. (You would now want to use an @kbd{a x} command to expand
21926the rest of the way, whereupon the denominator would cancel out to
21927the desired form, @samp{a - 1}.) When the numerator is not 1, this
21928initial expansion is not necessary because Calc's default
21929simplifications will not notice the potential cancellation.
21930
21931If the selection is an inequality, @kbd{j *} and @kbd{j /} will
21932accept any factor, but will warn unless they can prove the factor
21933is either positive or negative. (In the latter case the direction
21934of the inequality will be switched appropriately.) @xref{Declarations},
21935for ways to inform Calc that a given variable is positive or
21936negative. If Calc can't tell for sure what the sign of the factor
21937will be, it will assume it is positive and display a warning
21938message.
21939
21940For selections that are not quotients, equations, or inequalities,
21941these commands pull out a multiplicative factor: They divide (or
21942multiply) by the entered formula, simplify, then multiply (or divide)
21943back by the formula.
21944
21945@kindex j +
21946@kindex j -
21947@pindex calc-sel-add-both-sides
21948@pindex calc-sel-sub-both-sides
21949The @kbd{j +} (@code{calc-sel-add-both-sides}) and @kbd{j -}
21950(@code{calc-sel-sub-both-sides}) commands analogously add to or
21951subtract from both sides of an equation or inequality. For other
21952types of selections, they extract an additive factor. A numeric
21953prefix argument suppresses simplification of the intermediate
21954results.
21955
21956@kindex j U
21957@pindex calc-sel-unpack
21958The @kbd{j U} (@code{calc-sel-unpack}) command replaces the
21959selected function call with its argument. For example, given
21960@samp{a + sin(x^2)} with @samp{sin(x^2)} selected, the result
21961is @samp{a + x^2}. (The @samp{x^2} will remain selected; if you
21962wanted to change the @code{sin} to @code{cos}, just press @kbd{C}
21963now to take the cosine of the selected part.)
21964
21965@kindex j v
21966@pindex calc-sel-evaluate
21967The @kbd{j v} (@code{calc-sel-evaluate}) command performs the
21968normal default simplifications on the selected sub-formula.
21969These are the simplifications that are normally done automatically
21970on all results, but which may have been partially inhibited by
21971previous selection-related operations, or turned off altogether
21972by the @kbd{m O} command. This command is just an auto-selecting
21973version of the @w{@kbd{a v}} command (@pxref{Algebraic Manipulation}).
21974
21975With a numeric prefix argument of 2, @kbd{C-u 2 j v} applies
21976the @kbd{a s} (@code{calc-simplify}) command to the selected
21977sub-formula. With a prefix argument of 3 or more, e.g., @kbd{C-u j v}
21978applies the @kbd{a e} (@code{calc-simplify-extended}) command.
21979@xref{Simplifying Formulas}. With a negative prefix argument
21980it simplifies at the top level only, just as with @kbd{a v}.
21981Here the ``top'' level refers to the top level of the selected
21982sub-formula.
21983
21984@kindex j "
21985@pindex calc-sel-expand-formula
21986The @kbd{j "} (@code{calc-sel-expand-formula}) command is to @kbd{a "}
21987(@pxref{Algebraic Manipulation}) what @kbd{j v} is to @kbd{a v}.
21988
21989You can use the @kbd{j r} (@code{calc-rewrite-selection}) command
21990to define other algebraic operations on sub-formulas. @xref{Rewrite Rules}.
21991
21992@node Algebraic Manipulation, Simplifying Formulas, Selecting Subformulas, Algebra
21993@section Algebraic Manipulation
21994
21995@noindent
21996The commands in this section perform general-purpose algebraic
21997manipulations. They work on the whole formula at the top of the
21998stack (unless, of course, you have made a selection in that
21999formula).
22000
22001Many algebra commands prompt for a variable name or formula. If you
22002answer the prompt with a blank line, the variable or formula is taken
22003from top-of-stack, and the normal argument for the command is taken
22004from the second-to-top stack level.
22005
22006@kindex a v
22007@pindex calc-alg-evaluate
22008The @kbd{a v} (@code{calc-alg-evaluate}) command performs the normal
22009default simplifications on a formula; for example, @samp{a - -b} is
22010changed to @samp{a + b}. These simplifications are normally done
22011automatically on all Calc results, so this command is useful only if
22012you have turned default simplifications off with an @kbd{m O}
22013command. @xref{Simplification Modes}.
22014
22015It is often more convenient to type @kbd{=}, which is like @kbd{a v}
22016but which also substitutes stored values for variables in the formula.
22017Use @kbd{a v} if you want the variables to ignore their stored values.
22018
22019If you give a numeric prefix argument of 2 to @kbd{a v}, it simplifies
22020as if in Algebraic Simplification mode. This is equivalent to typing
22021@kbd{a s}; @pxref{Simplifying Formulas}. If you give a numeric prefix
22022of 3 or more, it uses Extended Simplification mode (@kbd{a e}).
22023
22024If you give a negative prefix argument @mathit{-1}, @mathit{-2}, or @mathit{-3},
22025it simplifies in the corresponding mode but only works on the top-level
22026function call of the formula. For example, @samp{(2 + 3) * (2 + 3)} will
22027simplify to @samp{(2 + 3)^2}, without simplifying the sub-formulas
22028@samp{2 + 3}. As another example, typing @kbd{V R +} to sum the vector
22029@samp{[1, 2, 3, 4]} produces the formula @samp{reduce(add, [1, 2, 3, 4])}
22030in No-Simplify mode. Using @kbd{a v} will evaluate this all the way to
2203110; using @kbd{C-u - a v} will evaluate it only to @samp{1 + 2 + 3 + 4}.
22032(@xref{Reducing and Mapping}.)
22033
22034@tindex evalv
22035@tindex evalvn
22036The @kbd{=} command corresponds to the @code{evalv} function, and
22037the related @kbd{N} command, which is like @kbd{=} but temporarily
22038disables Symbolic mode (@kbd{m s}) during the evaluation, corresponds
22039to the @code{evalvn} function. (These commands interpret their prefix
22040arguments differently than @kbd{a v}; @kbd{=} treats the prefix as
22041the number of stack elements to evaluate at once, and @kbd{N} treats
22042it as a temporary different working precision.)
22043
22044The @code{evalvn} function can take an alternate working precision
22045as an optional second argument. This argument can be either an
22046integer, to set the precision absolutely, or a vector containing
22047a single integer, to adjust the precision relative to the current
22048precision. Note that @code{evalvn} with a larger than current
22049precision will do the calculation at this higher precision, but the
22050result will as usual be rounded back down to the current precision
22051afterward. For example, @samp{evalvn(pi - 3.1415)} at a precision
22052of 12 will return @samp{9.265359e-5}; @samp{evalvn(pi - 3.1415, 30)}
22053will return @samp{9.26535897932e-5} (computing a 25-digit result which
22054is then rounded down to 12); and @samp{evalvn(pi - 3.1415, [-2])}
22055will return @samp{9.2654e-5}.
22056
22057@kindex a "
22058@pindex calc-expand-formula
22059The @kbd{a "} (@code{calc-expand-formula}) command expands functions
22060into their defining formulas wherever possible. For example,
22061@samp{deg(x^2)} is changed to @samp{180 x^2 / pi}. Most functions,
22062like @code{sin} and @code{gcd}, are not defined by simple formulas
22063and so are unaffected by this command. One important class of
22064functions which @emph{can} be expanded is the user-defined functions
22065created by the @kbd{Z F} command. @xref{Algebraic Definitions}.
22066Other functions which @kbd{a "} can expand include the probability
22067distribution functions, most of the financial functions, and the
22068hyperbolic and inverse hyperbolic functions. A numeric prefix argument
22069affects @kbd{a "} in the same way as it does @kbd{a v}: A positive
22070argument expands all functions in the formula and then simplifies in
22071various ways; a negative argument expands and simplifies only the
22072top-level function call.
22073
22074@kindex a M
22075@pindex calc-map-equation
22076@tindex mapeq
22077The @kbd{a M} (@code{calc-map-equation}) [@code{mapeq}] command applies
22078a given function or operator to one or more equations. It is analogous
22079to @kbd{V M}, which operates on vectors instead of equations.
22080@pxref{Reducing and Mapping}. For example, @kbd{a M S} changes
22081@samp{x = y+1} to @samp{sin(x) = sin(y+1)}, and @kbd{a M +} with
22082@samp{x = y+1} and @expr{6} on the stack produces @samp{x+6 = y+7}.
22083With two equations on the stack, @kbd{a M +} would add the lefthand
22084sides together and the righthand sides together to get the two
22085respective sides of a new equation.
22086
22087Mapping also works on inequalities. Mapping two similar inequalities
22088produces another inequality of the same type. Mapping an inequality
22089with an equation produces an inequality of the same type. Mapping a
22090@samp{<=} with a @samp{<} or @samp{!=} (not-equal) produces a @samp{<}.
22091If inequalities with opposite direction (e.g., @samp{<} and @samp{>})
22092are mapped, the direction of the second inequality is reversed to
22093match the first: Using @kbd{a M +} on @samp{a < b} and @samp{a > 2}
22094reverses the latter to get @samp{2 < a}, which then allows the
22095combination @samp{a + 2 < b + a}, which the @kbd{a s} command can
22096then simplify to get @samp{2 < b}.
22097
22098Using @kbd{a M *}, @kbd{a M /}, @kbd{a M n}, or @kbd{a M &} to negate
22099or invert an inequality will reverse the direction of the inequality.
22100Other adjustments to inequalities are @emph{not} done automatically;
22101@kbd{a M S} will change @w{@samp{x < y}} to @samp{sin(x) < sin(y)} even
22102though this is not true for all values of the variables.
22103
22104@kindex H a M
22105@tindex mapeqp
22106With the Hyperbolic flag, @kbd{H a M} [@code{mapeqp}] does a plain
22107mapping operation without reversing the direction of any inequalities.
22108Thus, @kbd{H a M &} would change @kbd{x > 2} to @kbd{1/x > 0.5}.
22109(This change is mathematically incorrect, but perhaps you were
22110fixing an inequality which was already incorrect.)
22111
22112@kindex I a M
22113@tindex mapeqr
22114With the Inverse flag, @kbd{I a M} [@code{mapeqr}] always reverses
22115the direction of the inequality. You might use @kbd{I a M C} to
22116change @samp{x < y} to @samp{cos(x) > cos(y)} if you know you are
22117working with small positive angles.
22118
22119@kindex a b
22120@pindex calc-substitute
22121@tindex subst
22122The @kbd{a b} (@code{calc-substitute}) [@code{subst}] command substitutes
22123all occurrences
22124of some variable or sub-expression of an expression with a new
22125sub-expression. For example, substituting @samp{sin(x)} with @samp{cos(y)}
22126in @samp{2 sin(x)^2 + x sin(x) + sin(2 x)} produces
22127@samp{2 cos(y)^2 + x cos(y) + @w{sin(2 x)}}.
22128Note that this is a purely structural substitution; the lone @samp{x} and
22129the @samp{sin(2 x)} stayed the same because they did not look like
22130@samp{sin(x)}. @xref{Rewrite Rules}, for a more general method for
22131doing substitutions.
22132
22133The @kbd{a b} command normally prompts for two formulas, the old
22134one and the new one. If you enter a blank line for the first
22135prompt, all three arguments are taken from the stack (new, then old,
22136then target expression). If you type an old formula but then enter a
22137blank line for the new one, the new formula is taken from top-of-stack
22138and the target from second-to-top. If you answer both prompts, the
22139target is taken from top-of-stack as usual.
22140
22141Note that @kbd{a b} has no understanding of commutativity or
22142associativity. The pattern @samp{x+y} will not match the formula
22143@samp{y+x}. Also, @samp{y+z} will not match inside the formula @samp{x+y+z}
22144because the @samp{+} operator is left-associative, so the ``deep
22145structure'' of that formula is @samp{(x+y) + z}. Use @kbd{d U}
22146(@code{calc-unformatted-language}) mode to see the true structure of
22147a formula. The rewrite rule mechanism, discussed later, does not have
22148these limitations.
22149
22150As an algebraic function, @code{subst} takes three arguments:
22151Target expression, old, new. Note that @code{subst} is always
22152evaluated immediately, even if its arguments are variables, so if
22153you wish to put a call to @code{subst} onto the stack you must
22154turn the default simplifications off first (with @kbd{m O}).
22155
22156@node Simplifying Formulas, Polynomials, Algebraic Manipulation, Algebra
22157@section Simplifying Formulas
22158
22159@noindent
22160@kindex a s
22161@pindex calc-simplify
22162@tindex simplify
22163The @kbd{a s} (@code{calc-simplify}) [@code{simplify}] command applies
22164various algebraic rules to simplify a formula. This includes rules which
22165are not part of the default simplifications because they may be too slow
22166to apply all the time, or may not be desirable all of the time. For
22167example, non-adjacent terms of sums are combined, as in @samp{a + b + 2 a}
22168to @samp{b + 3 a}, and some formulas like @samp{sin(arcsin(x))} are
22169simplified to @samp{x}.
22170
22171The sections below describe all the various kinds of algebraic
22172simplifications Calc provides in full detail. None of Calc's
22173simplification commands are designed to pull rabbits out of hats;
22174they simply apply certain specific rules to put formulas into
22175less redundant or more pleasing forms. Serious algebra in Calc
22176must be done manually, usually with a combination of selections
22177and rewrite rules. @xref{Rearranging with Selections}.
22178@xref{Rewrite Rules}.
22179
22180@xref{Simplification Modes}, for commands to control what level of
22181simplification occurs automatically. Normally only the ``default
22182simplifications'' occur.
22183
22184@menu
22185* Default Simplifications::
22186* Algebraic Simplifications::
22187* Unsafe Simplifications::
22188* Simplification of Units::
22189@end menu
22190
22191@node Default Simplifications, Algebraic Simplifications, Simplifying Formulas, Simplifying Formulas
22192@subsection Default Simplifications
22193
22194@noindent
22195@cindex Default simplifications
22196This section describes the ``default simplifications,'' those which are
22197normally applied to all results. For example, if you enter the variable
22198@expr{x} on the stack twice and push @kbd{+}, Calc's default
22199simplifications automatically change @expr{x + x} to @expr{2 x}.
22200
22201The @kbd{m O} command turns off the default simplifications, so that
22202@expr{x + x} will remain in this form unless you give an explicit
22203``simplify'' command like @kbd{=} or @kbd{a v}. @xref{Algebraic
22204Manipulation}. The @kbd{m D} command turns the default simplifications
22205back on.
22206
22207The most basic default simplification is the evaluation of functions.
22208For example, @expr{2 + 3} is evaluated to @expr{5}, and @expr{@tfn{sqrt}(9)}
22209is evaluated to @expr{3}. Evaluation does not occur if the arguments
22210to a function are somehow of the wrong type @expr{@tfn{tan}([2,3,4])}),
22211range (@expr{@tfn{tan}(90)}), or number (@expr{@tfn{tan}(3,5)}),
22212or if the function name is not recognized (@expr{@tfn{f}(5)}), or if
22213Symbolic mode (@pxref{Symbolic Mode}) prevents evaluation
22214(@expr{@tfn{sqrt}(2)}).
22215
22216Calc simplifies (evaluates) the arguments to a function before it
22217simplifies the function itself. Thus @expr{@tfn{sqrt}(5+4)} is
22218simplified to @expr{@tfn{sqrt}(9)} before the @code{sqrt} function
22219itself is applied. There are very few exceptions to this rule:
22220@code{quote}, @code{lambda}, and @code{condition} (the @code{::}
22221operator) do not evaluate their arguments, @code{if} (the @code{? :}
22222operator) does not evaluate all of its arguments, and @code{evalto}
22223does not evaluate its lefthand argument.
22224
22225Most commands apply the default simplifications to all arguments they
22226take from the stack, perform a particular operation, then simplify
22227the result before pushing it back on the stack. In the common special
22228case of regular arithmetic commands like @kbd{+} and @kbd{Q} [@code{sqrt}],
22229the arguments are simply popped from the stack and collected into a
22230suitable function call, which is then simplified (the arguments being
22231simplified first as part of the process, as described above).
22232
22233The default simplifications are too numerous to describe completely
22234here, but this section will describe the ones that apply to the
22235major arithmetic operators. This list will be rather technical in
22236nature, and will probably be interesting to you only if you are
22237a serious user of Calc's algebra facilities.
22238
22239@tex
22240\bigskip
22241@end tex
22242
22243As well as the simplifications described here, if you have stored
22244any rewrite rules in the variable @code{EvalRules} then these rules
22245will also be applied before any built-in default simplifications.
22246@xref{Automatic Rewrites}, for details.
22247
22248@tex
22249\bigskip
22250@end tex
22251
22252And now, on with the default simplifications:
22253
22254Arithmetic operators like @kbd{+} and @kbd{*} always take two
22255arguments in Calc's internal form. Sums and products of three or
22256more terms are arranged by the associative law of algebra into
22257a left-associative form for sums, @expr{((a + b) + c) + d}, and
45b778a6
JB
22258(by default) a right-associative form for products,
22259@expr{a * (b * (c * d))}. Formulas like @expr{(a + b) + (c + d)} are
22260rearranged to left-associative form, though this rarely matters since
22261Calc's algebra commands are designed to hide the inner structure of sums
22262and products as much as possible. Sums and products in their proper
22263associative form will be written without parentheses in the examples
22264below.
4009494e
GM
22265
22266Sums and products are @emph{not} rearranged according to the
22267commutative law (@expr{a + b} to @expr{b + a}) except in a few
22268special cases described below. Some algebra programs always
22269rearrange terms into a canonical order, which enables them to
22270see that @expr{a b + b a} can be simplified to @expr{2 a b}.
22271Calc assumes you have put the terms into the order you want
22272and generally leaves that order alone, with the consequence
22273that formulas like the above will only be simplified if you
22274explicitly give the @kbd{a s} command. @xref{Algebraic
22275Simplifications}.
22276
22277Differences @expr{a - b} are treated like sums @expr{a + (-b)}
22278for purposes of simplification; one of the default simplifications
22279is to rewrite @expr{a + (-b)} or @expr{(-b) + a}, where @expr{-b}
22280represents a ``negative-looking'' term, into @expr{a - b} form.
22281``Negative-looking'' means negative numbers, negated formulas like
22282@expr{-x}, and products or quotients in which either term is
22283negative-looking.
22284
22285Other simplifications involving negation are @expr{-(-x)} to @expr{x};
22286@expr{-(a b)} or @expr{-(a/b)} where either @expr{a} or @expr{b} is
22287negative-looking, simplified by negating that term, or else where
22288@expr{a} or @expr{b} is any number, by negating that number;
22289@expr{-(a + b)} to @expr{-a - b}, and @expr{-(b - a)} to @expr{a - b}.
22290(This, and rewriting @expr{(-b) + a} to @expr{a - b}, are the only
22291cases where the order of terms in a sum is changed by the default
22292simplifications.)
22293
22294The distributive law is used to simplify sums in some cases:
22295@expr{a x + b x} to @expr{(a + b) x}, where @expr{a} represents
22296a number or an implicit 1 or @mathit{-1} (as in @expr{x} or @expr{-x})
22297and similarly for @expr{b}. Use the @kbd{a c}, @w{@kbd{a f}}, or
22298@kbd{j M} commands to merge sums with non-numeric coefficients
22299using the distributive law.
22300
22301The distributive law is only used for sums of two terms, or
22302for adjacent terms in a larger sum. Thus @expr{a + b + b + c}
22303is simplified to @expr{a + 2 b + c}, but @expr{a + b + c + b}
22304is not simplified. The reason is that comparing all terms of a
22305sum with one another would require time proportional to the
22306square of the number of terms; Calc relegates potentially slow
22307operations like this to commands that have to be invoked
22308explicitly, like @kbd{a s}.
22309
22310Finally, @expr{a + 0} and @expr{0 + a} are simplified to @expr{a}.
22311A consequence of the above rules is that @expr{0 - a} is simplified
22312to @expr{-a}.
22313
22314@tex
22315\bigskip
22316@end tex
22317
22318The products @expr{1 a} and @expr{a 1} are simplified to @expr{a};
22319@expr{(-1) a} and @expr{a (-1)} are simplified to @expr{-a};
22320@expr{0 a} and @expr{a 0} are simplified to @expr{0}, except that
22321in Matrix mode where @expr{a} is not provably scalar the result
22322is the generic zero matrix @samp{idn(0)}, and that if @expr{a} is
22323infinite the result is @samp{nan}.
22324
22325Also, @expr{(-a) b} and @expr{a (-b)} are simplified to @expr{-(a b)},
22326where this occurs for negated formulas but not for regular negative
22327numbers.
22328
22329Products are commuted only to move numbers to the front:
22330@expr{a b 2} is commuted to @expr{2 a b}.
22331
22332The product @expr{a (b + c)} is distributed over the sum only if
22333@expr{a} and at least one of @expr{b} and @expr{c} are numbers:
22334@expr{2 (x + 3)} goes to @expr{2 x + 6}. The formula
22335@expr{(-a) (b - c)}, where @expr{-a} is a negative number, is
22336rewritten to @expr{a (c - b)}.
22337
22338The distributive law of products and powers is used for adjacent
22339terms of the product: @expr{x^a x^b} goes to
22340@texline @math{x^{a+b}}
22341@infoline @expr{x^(a+b)}
22342where @expr{a} is a number, or an implicit 1 (as in @expr{x}),
22343or the implicit one-half of @expr{@tfn{sqrt}(x)}, and similarly for
22344@expr{b}. The result is written using @samp{sqrt} or @samp{1/sqrt}
22345if the sum of the powers is @expr{1/2} or @expr{-1/2}, respectively.
22346If the sum of the powers is zero, the product is simplified to
22347@expr{1} or to @samp{idn(1)} if Matrix mode is enabled.
22348
22349The product of a negative power times anything but another negative
22350power is changed to use division:
22351@texline @math{x^{-2} y}
22352@infoline @expr{x^(-2) y}
22353goes to @expr{y / x^2} unless Matrix mode is
22354in effect and neither @expr{x} nor @expr{y} are scalar (in which
22355case it is considered unsafe to rearrange the order of the terms).
22356
22357Finally, @expr{a (b/c)} is rewritten to @expr{(a b)/c}, and also
22358@expr{(a/b) c} is changed to @expr{(a c)/b} unless in Matrix mode.
22359
22360@tex
22361\bigskip
22362@end tex
22363
22364Simplifications for quotients are analogous to those for products.
22365The quotient @expr{0 / x} is simplified to @expr{0}, with the same
22366exceptions that were noted for @expr{0 x}. Likewise, @expr{x / 1}
22367and @expr{x / (-1)} are simplified to @expr{x} and @expr{-x},
22368respectively.
22369
22370The quotient @expr{x / 0} is left unsimplified or changed to an
22371infinite quantity, as directed by the current infinite mode.
22372@xref{Infinite Mode}.
22373
22374The expression
22375@texline @math{a / b^{-c}}
22376@infoline @expr{a / b^(-c)}
22377is changed to @expr{a b^c}, where @expr{-c} is any negative-looking
22378power. Also, @expr{1 / b^c} is changed to
22379@texline @math{b^{-c}}
22380@infoline @expr{b^(-c)}
22381for any power @expr{c}.
22382
22383Also, @expr{(-a) / b} and @expr{a / (-b)} go to @expr{-(a/b)};
22384@expr{(a/b) / c} goes to @expr{a / (b c)}; and @expr{a / (b/c)}
22385goes to @expr{(a c) / b} unless Matrix mode prevents this
22386rearrangement. Similarly, @expr{a / (b:c)} is simplified to
22387@expr{(c:b) a} for any fraction @expr{b:c}.
22388
22389The distributive law is applied to @expr{(a + b) / c} only if
22390@expr{c} and at least one of @expr{a} and @expr{b} are numbers.
22391Quotients of powers and square roots are distributed just as
22392described for multiplication.
22393
22394Quotients of products cancel only in the leading terms of the
22395numerator and denominator. In other words, @expr{a x b / a y b}
22396is cancelled to @expr{x b / y b} but not to @expr{x / y}. Once
22397again this is because full cancellation can be slow; use @kbd{a s}
22398to cancel all terms of the quotient.
22399
22400Quotients of negative-looking values are simplified according
22401to @expr{(-a) / (-b)} to @expr{a / b}, @expr{(-a) / (b - c)}
22402to @expr{a / (c - b)}, and @expr{(a - b) / (-c)} to @expr{(b - a) / c}.
22403
22404@tex
22405\bigskip
22406@end tex
22407
22408The formula @expr{x^0} is simplified to @expr{1}, or to @samp{idn(1)}
22409in Matrix mode. The formula @expr{0^x} is simplified to @expr{0}
22410unless @expr{x} is a negative number, complex number or zero.
22411If @expr{x} is negative, complex or @expr{0.0}, @expr{0^x} is an
22412infinity or an unsimplified formula according to the current infinite
22413mode. The expression @expr{0^0} is simplified to @expr{1}.
22414
22415Powers of products or quotients @expr{(a b)^c}, @expr{(a/b)^c}
22416are distributed to @expr{a^c b^c}, @expr{a^c / b^c} only if @expr{c}
22417is an integer, or if either @expr{a} or @expr{b} are nonnegative
22418real numbers. Powers of powers @expr{(a^b)^c} are simplified to
22419@texline @math{a^{b c}}
22420@infoline @expr{a^(b c)}
22421only when @expr{c} is an integer and @expr{b c} also
22422evaluates to an integer. Without these restrictions these simplifications
22423would not be safe because of problems with principal values.
22424(In other words,
22425@texline @math{((-3)^{1/2})^2}
22426@infoline @expr{((-3)^1:2)^2}
22427is safe to simplify, but
22428@texline @math{((-3)^2)^{1/2}}
22429@infoline @expr{((-3)^2)^1:2}
22430is not.) @xref{Declarations}, for ways to inform Calc that your
22431variables satisfy these requirements.
22432
22433As a special case of this rule, @expr{@tfn{sqrt}(x)^n} is simplified to
22434@texline @math{x^{n/2}}
22435@infoline @expr{x^(n/2)}
22436only for even integers @expr{n}.
22437
22438If @expr{a} is known to be real, @expr{b} is an even integer, and
22439@expr{c} is a half- or quarter-integer, then @expr{(a^b)^c} is
22440simplified to @expr{@tfn{abs}(a^(b c))}.
22441
22442Also, @expr{(-a)^b} is simplified to @expr{a^b} if @expr{b} is an
22443even integer, or to @expr{-(a^b)} if @expr{b} is an odd integer,
22444for any negative-looking expression @expr{-a}.
22445
22446Square roots @expr{@tfn{sqrt}(x)} generally act like one-half powers
22447@texline @math{x^{1:2}}
22448@infoline @expr{x^1:2}
22449for the purposes of the above-listed simplifications.
22450
22451Also, note that
22452@texline @math{1 / x^{1:2}}
22453@infoline @expr{1 / x^1:2}
22454is changed to
22455@texline @math{x^{-1:2}},
22456@infoline @expr{x^(-1:2)},
22457but @expr{1 / @tfn{sqrt}(x)} is left alone.
22458
22459@tex
22460\bigskip
22461@end tex
22462
22463Generic identity matrices (@pxref{Matrix Mode}) are simplified by the
22464following rules: @expr{@tfn{idn}(a) + b} to @expr{a + b} if @expr{b}
22465is provably scalar, or expanded out if @expr{b} is a matrix;
22466@expr{@tfn{idn}(a) + @tfn{idn}(b)} to @expr{@tfn{idn}(a + b)};
22467@expr{-@tfn{idn}(a)} to @expr{@tfn{idn}(-a)}; @expr{a @tfn{idn}(b)} to
22468@expr{@tfn{idn}(a b)} if @expr{a} is provably scalar, or to @expr{a b}
22469if @expr{a} is provably non-scalar; @expr{@tfn{idn}(a) @tfn{idn}(b)} to
22470@expr{@tfn{idn}(a b)}; analogous simplifications for quotients involving
22471@code{idn}; and @expr{@tfn{idn}(a)^n} to @expr{@tfn{idn}(a^n)} where
22472@expr{n} is an integer.
22473
22474@tex
22475\bigskip
22476@end tex
22477
22478The @code{floor} function and other integer truncation functions
22479vanish if the argument is provably integer-valued, so that
22480@expr{@tfn{floor}(@tfn{round}(x))} simplifies to @expr{@tfn{round}(x)}.
22481Also, combinations of @code{float}, @code{floor} and its friends,
22482and @code{ffloor} and its friends, are simplified in appropriate
22483ways. @xref{Integer Truncation}.
22484
22485The expression @expr{@tfn{abs}(-x)} changes to @expr{@tfn{abs}(x)}.
22486The expression @expr{@tfn{abs}(@tfn{abs}(x))} changes to
22487@expr{@tfn{abs}(x)}; in fact, @expr{@tfn{abs}(x)} changes to @expr{x} or
22488@expr{-x} if @expr{x} is provably nonnegative or nonpositive
22489(@pxref{Declarations}).
22490
22491While most functions do not recognize the variable @code{i} as an
22492imaginary number, the @code{arg} function does handle the two cases
22493@expr{@tfn{arg}(@tfn{i})} and @expr{@tfn{arg}(-@tfn{i})} just for convenience.
22494
22495The expression @expr{@tfn{conj}(@tfn{conj}(x))} simplifies to @expr{x}.
22496Various other expressions involving @code{conj}, @code{re}, and
22497@code{im} are simplified, especially if some of the arguments are
22498provably real or involve the constant @code{i}. For example,
22499@expr{@tfn{conj}(a + b i)} is changed to
22500@expr{@tfn{conj}(a) - @tfn{conj}(b) i}, or to @expr{a - b i} if @expr{a}
22501and @expr{b} are known to be real.
22502
22503Functions like @code{sin} and @code{arctan} generally don't have
22504any default simplifications beyond simply evaluating the functions
22505for suitable numeric arguments and infinity. The @kbd{a s} command
22506described in the next section does provide some simplifications for
22507these functions, though.
22508
22509One important simplification that does occur is that
22510@expr{@tfn{ln}(@tfn{e})} is simplified to 1, and @expr{@tfn{ln}(@tfn{e}^x)} is
22511simplified to @expr{x} for any @expr{x}. This occurs even if you have
22512stored a different value in the Calc variable @samp{e}; but this would
22513be a bad idea in any case if you were also using natural logarithms!
22514
22515Among the logical functions, @tfn{!(@var{a} <= @var{b})} changes to
22516@tfn{@var{a} > @var{b}} and so on. Equations and inequalities where both sides
22517are either negative-looking or zero are simplified by negating both sides
22518and reversing the inequality. While it might seem reasonable to simplify
22519@expr{!!x} to @expr{x}, this would not be valid in general because
22520@expr{!!2} is 1, not 2.
22521
22522Most other Calc functions have few if any default simplifications
22523defined, aside of course from evaluation when the arguments are
22524suitable numbers.
22525
22526@node Algebraic Simplifications, Unsafe Simplifications, Default Simplifications, Simplifying Formulas
22527@subsection Algebraic Simplifications
22528
22529@noindent
22530@cindex Algebraic simplifications
22531The @kbd{a s} command makes simplifications that may be too slow to
22532do all the time, or that may not be desirable all of the time.
22533If you find these simplifications are worthwhile, you can type
22534@kbd{m A} to have Calc apply them automatically.
22535
22536This section describes all simplifications that are performed by
22537the @kbd{a s} command. Note that these occur in addition to the
22538default simplifications; even if the default simplifications have
22539been turned off by an @kbd{m O} command, @kbd{a s} will turn them
22540back on temporarily while it simplifies the formula.
22541
22542There is a variable, @code{AlgSimpRules}, in which you can put rewrites
22543to be applied by @kbd{a s}. Its use is analogous to @code{EvalRules},
22544but without the special restrictions. Basically, the simplifier does
22545@samp{@w{a r} AlgSimpRules} with an infinite repeat count on the whole
22546expression being simplified, then it traverses the expression applying
22547the built-in rules described below. If the result is different from
22548the original expression, the process repeats with the default
22549simplifications (including @code{EvalRules}), then @code{AlgSimpRules},
22550then the built-in simplifications, and so on.
22551
22552@tex
22553\bigskip
22554@end tex
22555
22556Sums are simplified in two ways. Constant terms are commuted to the
22557end of the sum, so that @expr{a + 2 + b} changes to @expr{a + b + 2}.
22558The only exception is that a constant will not be commuted away
22559from the first position of a difference, i.e., @expr{2 - x} is not
22560commuted to @expr{-x + 2}.
22561
22562Also, terms of sums are combined by the distributive law, as in
22563@expr{x + y + 2 x} to @expr{y + 3 x}. This always occurs for
22564adjacent terms, but @kbd{a s} compares all pairs of terms including
22565non-adjacent ones.
22566
22567@tex
22568\bigskip
22569@end tex
22570
22571Products are sorted into a canonical order using the commutative
22572law. For example, @expr{b c a} is commuted to @expr{a b c}.
22573This allows easier comparison of products; for example, the default
22574simplifications will not change @expr{x y + y x} to @expr{2 x y},
22575but @kbd{a s} will; it first rewrites the sum to @expr{x y + x y},
22576and then the default simplifications are able to recognize a sum
22577of identical terms.
22578
22579The canonical ordering used to sort terms of products has the
22580property that real-valued numbers, interval forms and infinities
22581come first, and are sorted into increasing order. The @kbd{V S}
22582command uses the same ordering when sorting a vector.
22583
22584Sorting of terms of products is inhibited when Matrix mode is
22585turned on; in this case, Calc will never exchange the order of
22586two terms unless it knows at least one of the terms is a scalar.
22587
22588Products of powers are distributed by comparing all pairs of
22589terms, using the same method that the default simplifications
22590use for adjacent terms of products.
22591
22592Even though sums are not sorted, the commutative law is still
22593taken into account when terms of a product are being compared.
22594Thus @expr{(x + y) (y + x)} will be simplified to @expr{(x + y)^2}.
22595A subtle point is that @expr{(x - y) (y - x)} will @emph{not}
22596be simplified to @expr{-(x - y)^2}; Calc does not notice that
22597one term can be written as a constant times the other, even if
22598that constant is @mathit{-1}.
22599
22600A fraction times any expression, @expr{(a:b) x}, is changed to
22601a quotient involving integers: @expr{a x / b}. This is not
22602done for floating-point numbers like @expr{0.5}, however. This
22603is one reason why you may find it convenient to turn Fraction mode
22604on while doing algebra; @pxref{Fraction Mode}.
22605
22606@tex
22607\bigskip
22608@end tex
22609
22610Quotients are simplified by comparing all terms in the numerator
22611with all terms in the denominator for possible cancellation using
22612the distributive law. For example, @expr{a x^2 b / c x^3 d} will
22613cancel @expr{x^2} from the top and bottom to get @expr{a b / c x d}.
22614(The terms in the denominator will then be rearranged to @expr{c d x}
22615as described above.) If there is any common integer or fractional
22616factor in the numerator and denominator, it is cancelled out;
22617for example, @expr{(4 x + 6) / 8 x} simplifies to @expr{(2 x + 3) / 4 x}.
22618
22619Non-constant common factors are not found even by @kbd{a s}. To
22620cancel the factor @expr{a} in @expr{(a x + a) / a^2} you could first
22621use @kbd{j M} on the product @expr{a x} to Merge the numerator to
22622@expr{a (1+x)}, which can then be simplified successfully.
22623
22624@tex
22625\bigskip
22626@end tex
22627
22628Integer powers of the variable @code{i} are simplified according
22629to the identity @expr{i^2 = -1}. If you store a new value other
22630than the complex number @expr{(0,1)} in @code{i}, this simplification
22631will no longer occur. This is done by @kbd{a s} instead of by default
22632in case someone (unwisely) uses the name @code{i} for a variable
22633unrelated to complex numbers; it would be unfortunate if Calc
22634quietly and automatically changed this formula for reasons the
22635user might not have been thinking of.
22636
22637Square roots of integer or rational arguments are simplified in
22638several ways. (Note that these will be left unevaluated only in
22639Symbolic mode.) First, square integer or rational factors are
22640pulled out so that @expr{@tfn{sqrt}(8)} is rewritten as
22641@texline @math{2\,@tfn{sqrt}(2)}.
22642@infoline @expr{2 sqrt(2)}.
22643Conceptually speaking this implies factoring the argument into primes
22644and moving pairs of primes out of the square root, but for reasons of
22645efficiency Calc only looks for primes up to 29.
22646
22647Square roots in the denominator of a quotient are moved to the
22648numerator: @expr{1 / @tfn{sqrt}(3)} changes to @expr{@tfn{sqrt}(3) / 3}.
22649The same effect occurs for the square root of a fraction:
22650@expr{@tfn{sqrt}(2:3)} changes to @expr{@tfn{sqrt}(6) / 3}.
22651
22652@tex
22653\bigskip
22654@end tex
22655
22656The @code{%} (modulo) operator is simplified in several ways
22657when the modulus @expr{M} is a positive real number. First, if
22658the argument is of the form @expr{x + n} for some real number
22659@expr{n}, then @expr{n} is itself reduced modulo @expr{M}. For
22660example, @samp{(x - 23) % 10} is simplified to @samp{(x + 7) % 10}.
22661
22662If the argument is multiplied by a constant, and this constant
22663has a common integer divisor with the modulus, then this factor is
22664cancelled out. For example, @samp{12 x % 15} is changed to
22665@samp{3 (4 x % 5)} by factoring out 3. Also, @samp{(12 x + 1) % 15}
22666is changed to @samp{3 ((4 x + 1:3) % 5)}. While these forms may
22667not seem ``simpler,'' they allow Calc to discover useful information
22668about modulo forms in the presence of declarations.
22669
22670If the modulus is 1, then Calc can use @code{int} declarations to
22671evaluate the expression. For example, the idiom @samp{x % 2} is
22672often used to check whether a number is odd or even. As described
22673above, @w{@samp{2 n % 2}} and @samp{(2 n + 1) % 2} are simplified to
22674@samp{2 (n % 1)} and @samp{2 ((n + 1:2) % 1)}, respectively; Calc
22675can simplify these to 0 and 1 (respectively) if @code{n} has been
22676declared to be an integer.
22677
22678@tex
22679\bigskip
22680@end tex
22681
22682Trigonometric functions are simplified in several ways. Whenever a
22683products of two trigonometric functions can be replaced by a single
22684function, the replacement is made; for example,
22685@expr{@tfn{tan}(x) @tfn{cos}(x)} is simplified to @expr{@tfn{sin}(x)}.
22686Reciprocals of trigonometric functions are replaced by their reciprocal
22687function; for example, @expr{1/@tfn{sec}(x)} is simplified to
22688@expr{@tfn{cos}(x)}. The corresponding simplifications for the
22689hyperbolic functions are also handled.
22690
22691Trigonometric functions of their inverse functions are
22692simplified. The expression @expr{@tfn{sin}(@tfn{arcsin}(x))} is
22693simplified to @expr{x}, and similarly for @code{cos} and @code{tan}.
22694Trigonometric functions of inverses of different trigonometric
22695functions can also be simplified, as in @expr{@tfn{sin}(@tfn{arccos}(x))}
22696to @expr{@tfn{sqrt}(1 - x^2)}.
22697
22698If the argument to @code{sin} is negative-looking, it is simplified to
22699@expr{-@tfn{sin}(x)}, and similarly for @code{cos} and @code{tan}.
22700Finally, certain special values of the argument are recognized;
22701@pxref{Trigonometric and Hyperbolic Functions}.
22702
22703Hyperbolic functions of their inverses and of negative-looking
22704arguments are also handled, as are exponentials of inverse
22705hyperbolic functions.
22706
22707No simplifications for inverse trigonometric and hyperbolic
22708functions are known, except for negative arguments of @code{arcsin},
22709@code{arctan}, @code{arcsinh}, and @code{arctanh}. Note that
22710@expr{@tfn{arcsin}(@tfn{sin}(x))} can @emph{not} safely change to
22711@expr{x}, since this only correct within an integer multiple of
22712@texline @math{2 \pi}
22713@infoline @expr{2 pi}
22714radians or 360 degrees. However, @expr{@tfn{arcsinh}(@tfn{sinh}(x))} is
22715simplified to @expr{x} if @expr{x} is known to be real.
22716
22717Several simplifications that apply to logarithms and exponentials
22718are that @expr{@tfn{exp}(@tfn{ln}(x))},
22719@texline @tfn{e}@math{^{\ln(x)}},
22720@infoline @expr{e^@tfn{ln}(x)},
22721and
22722@texline @math{10^{{\rm log10}(x)}}
22723@infoline @expr{10^@tfn{log10}(x)}
22724all reduce to @expr{x}. Also, @expr{@tfn{ln}(@tfn{exp}(x))}, etc., can
22725reduce to @expr{x} if @expr{x} is provably real. The form
22726@expr{@tfn{exp}(x)^y} is simplified to @expr{@tfn{exp}(x y)}. If @expr{x}
22727is a suitable multiple of
22728@texline @math{\pi i}
22729@infoline @expr{pi i}
22730(as described above for the trigonometric functions), then
22731@expr{@tfn{exp}(x)} or @expr{e^x} will be expanded. Finally,
22732@expr{@tfn{ln}(x)} is simplified to a form involving @code{pi} and
22733@code{i} where @expr{x} is provably negative, positive imaginary, or
22734negative imaginary.
22735
22736The error functions @code{erf} and @code{erfc} are simplified when
22737their arguments are negative-looking or are calls to the @code{conj}
22738function.
22739
22740@tex
22741\bigskip
22742@end tex
22743
22744Equations and inequalities are simplified by cancelling factors
22745of products, quotients, or sums on both sides. Inequalities
22746change sign if a negative multiplicative factor is cancelled.
22747Non-constant multiplicative factors as in @expr{a b = a c} are
22748cancelled from equations only if they are provably nonzero (generally
22749because they were declared so; @pxref{Declarations}). Factors
22750are cancelled from inequalities only if they are nonzero and their
22751sign is known.
22752
22753Simplification also replaces an equation or inequality with
227541 or 0 (``true'' or ``false'') if it can through the use of
22755declarations. If @expr{x} is declared to be an integer greater
22756than 5, then @expr{x < 3}, @expr{x = 3}, and @expr{x = 7.5} are
22757all simplified to 0, but @expr{x > 3} is simplified to 1.
22758By a similar analysis, @expr{abs(x) >= 0} is simplified to 1,
22759as is @expr{x^2 >= 0} if @expr{x} is known to be real.
22760
22761@node Unsafe Simplifications, Simplification of Units, Algebraic Simplifications, Simplifying Formulas
22762@subsection ``Unsafe'' Simplifications
22763
22764@noindent
22765@cindex Unsafe simplifications
22766@cindex Extended simplification
22767@kindex a e
22768@pindex calc-simplify-extended
22769@ignore
22770@mindex esimpl@idots
22771@end ignore
22772@tindex esimplify
22773The @kbd{a e} (@code{calc-simplify-extended}) [@code{esimplify}] command
22774is like @kbd{a s}
22775except that it applies some additional simplifications which are not
22776``safe'' in all cases. Use this only if you know the values in your
22777formula lie in the restricted ranges for which these simplifications
22778are valid. The symbolic integrator uses @kbd{a e};
22779one effect of this is that the integrator's results must be used with
22780caution. Where an integral table will often attach conditions like
22781``for positive @expr{a} only,'' Calc (like most other symbolic
22782integration programs) will simply produce an unqualified result.
22783
22784Because @kbd{a e}'s simplifications are unsafe, it is sometimes better
22785to type @kbd{C-u -3 a v}, which does extended simplification only
22786on the top level of the formula without affecting the sub-formulas.
22787In fact, @kbd{C-u -3 j v} allows you to target extended simplification
22788to any specific part of a formula.
22789
22790The variable @code{ExtSimpRules} contains rewrites to be applied by
22791the @kbd{a e} command. These are applied in addition to
22792@code{EvalRules} and @code{AlgSimpRules}. (The @kbd{a r AlgSimpRules}
22793step described above is simply followed by an @kbd{a r ExtSimpRules} step.)
22794
22795Following is a complete list of ``unsafe'' simplifications performed
22796by @kbd{a e}.
22797
22798@tex
22799\bigskip
22800@end tex
22801
22802Inverse trigonometric or hyperbolic functions, called with their
22803corresponding non-inverse functions as arguments, are simplified
22804by @kbd{a e}. For example, @expr{@tfn{arcsin}(@tfn{sin}(x))} changes
22805to @expr{x}. Also, @expr{@tfn{arcsin}(@tfn{cos}(x))} and
22806@expr{@tfn{arccos}(@tfn{sin}(x))} both change to @expr{@tfn{pi}/2 - x}.
22807These simplifications are unsafe because they are valid only for
22808values of @expr{x} in a certain range; outside that range, values
22809are folded down to the 360-degree range that the inverse trigonometric
22810functions always produce.
22811
22812Powers of powers @expr{(x^a)^b} are simplified to
22813@texline @math{x^{a b}}
22814@infoline @expr{x^(a b)}
22815for all @expr{a} and @expr{b}. These results will be valid only
22816in a restricted range of @expr{x}; for example, in
22817@texline @math{(x^2)^{1:2}}
22818@infoline @expr{(x^2)^1:2}
22819the powers cancel to get @expr{x}, which is valid for positive values
22820of @expr{x} but not for negative or complex values.
22821
22822Similarly, @expr{@tfn{sqrt}(x^a)} and @expr{@tfn{sqrt}(x)^a} are both
22823simplified (possibly unsafely) to
22824@texline @math{x^{a/2}}.
22825@infoline @expr{x^(a/2)}.
22826
22827Forms like @expr{@tfn{sqrt}(1 - sin(x)^2)} are simplified to, e.g.,
22828@expr{@tfn{cos}(x)}. Calc has identities of this sort for @code{sin},
22829@code{cos}, @code{tan}, @code{sinh}, and @code{cosh}.
22830
22831Arguments of square roots are partially factored to look for
22832squared terms that can be extracted. For example,
22833@expr{@tfn{sqrt}(a^2 b^3 + a^3 b^2)} simplifies to
22834@expr{a b @tfn{sqrt}(a+b)}.
22835
22836The simplifications of @expr{@tfn{ln}(@tfn{exp}(x))},
22837@expr{@tfn{ln}(@tfn{e}^x)}, and @expr{@tfn{log10}(10^x)} to @expr{x} are also
22838unsafe because of problems with principal values (although these
22839simplifications are safe if @expr{x} is known to be real).
22840
22841Common factors are cancelled from products on both sides of an
22842equation, even if those factors may be zero: @expr{a x / b x}
22843to @expr{a / b}. Such factors are never cancelled from
22844inequalities: Even @kbd{a e} is not bold enough to reduce
22845@expr{a x < b x} to @expr{a < b} (or @expr{a > b}, depending
22846on whether you believe @expr{x} is positive or negative).
22847The @kbd{a M /} command can be used to divide a factor out of
22848both sides of an inequality.
22849
22850@node Simplification of Units, , Unsafe Simplifications, Simplifying Formulas
22851@subsection Simplification of Units
22852
22853@noindent
22854The simplifications described in this section are applied by the
22855@kbd{u s} (@code{calc-simplify-units}) command. These are in addition
22856to the regular @kbd{a s} (but not @kbd{a e}) simplifications described
22857earlier. @xref{Basic Operations on Units}.
22858
22859The variable @code{UnitSimpRules} contains rewrites to be applied by
22860the @kbd{u s} command. These are applied in addition to @code{EvalRules}
22861and @code{AlgSimpRules}.
22862
22863Scalar mode is automatically put into effect when simplifying units.
22864@xref{Matrix Mode}.
22865
22866Sums @expr{a + b} involving units are simplified by extracting the
22867units of @expr{a} as if by the @kbd{u x} command (call the result
22868@expr{u_a}), then simplifying the expression @expr{b / u_a}
22869using @kbd{u b} and @kbd{u s}. If the result has units then the sum
22870is inconsistent and is left alone. Otherwise, it is rewritten
22871in terms of the units @expr{u_a}.
22872
22873If units auto-ranging mode is enabled, products or quotients in
22874which the first argument is a number which is out of range for the
22875leading unit are modified accordingly.
22876
22877When cancelling and combining units in products and quotients,
22878Calc accounts for unit names that differ only in the prefix letter.
22879For example, @samp{2 km m} is simplified to @samp{2000 m^2}.
22880However, compatible but different units like @code{ft} and @code{in}
22881are not combined in this way.
22882
22883Quotients @expr{a / b} are simplified in three additional ways. First,
22884if @expr{b} is a number or a product beginning with a number, Calc
22885computes the reciprocal of this number and moves it to the numerator.
22886
22887Second, for each pair of unit names from the numerator and denominator
22888of a quotient, if the units are compatible (e.g., they are both
22889units of area) then they are replaced by the ratio between those
22890units. For example, in @samp{3 s in N / kg cm} the units
22891@samp{in / cm} will be replaced by @expr{2.54}.
22892
22893Third, if the units in the quotient exactly cancel out, so that
22894a @kbd{u b} command on the quotient would produce a dimensionless
22895number for an answer, then the quotient simplifies to that number.
22896
22897For powers and square roots, the ``unsafe'' simplifications
22898@expr{(a b)^c} to @expr{a^c b^c}, @expr{(a/b)^c} to @expr{a^c / b^c},
22899and @expr{(a^b)^c} to
22900@texline @math{a^{b c}}
22901@infoline @expr{a^(b c)}
22902are done if the powers are real numbers. (These are safe in the context
22903of units because all numbers involved can reasonably be assumed to be
22904real.)
22905
22906Also, if a unit name is raised to a fractional power, and the
22907base units in that unit name all occur to powers which are a
22908multiple of the denominator of the power, then the unit name
22909is expanded out into its base units, which can then be simplified
22910according to the previous paragraph. For example, @samp{acre^1.5}
22911is simplified by noting that @expr{1.5 = 3:2}, that @samp{acre}
22912is defined in terms of @samp{m^2}, and that the 2 in the power of
22913@code{m} is a multiple of 2 in @expr{3:2}. Thus, @code{acre^1.5} is
22914replaced by approximately
22915@texline @math{(4046 m^2)^{1.5}}
22916@infoline @expr{(4046 m^2)^1.5},
22917which is then changed to
22918@texline @math{4046^{1.5} \, (m^2)^{1.5}},
22919@infoline @expr{4046^1.5 (m^2)^1.5},
22920then to @expr{257440 m^3}.
22921
22922The functions @code{float}, @code{frac}, @code{clean}, @code{abs},
22923as well as @code{floor} and the other integer truncation functions,
22924applied to unit names or products or quotients involving units, are
22925simplified. For example, @samp{round(1.6 in)} is changed to
22926@samp{round(1.6) round(in)}; the lefthand term evaluates to 2,
22927and the righthand term simplifies to @code{in}.
22928
22929The functions @code{sin}, @code{cos}, and @code{tan} with arguments
22930that have angular units like @code{rad} or @code{arcmin} are
22931simplified by converting to base units (radians), then evaluating
22932with the angular mode temporarily set to radians.
22933
22934@node Polynomials, Calculus, Simplifying Formulas, Algebra
22935@section Polynomials
22936
22937A @dfn{polynomial} is a sum of terms which are coefficients times
22938various powers of a ``base'' variable. For example, @expr{2 x^2 + 3 x - 4}
22939is a polynomial in @expr{x}. Some formulas can be considered
22940polynomials in several different variables: @expr{1 + 2 x + 3 y + 4 x y^2}
22941is a polynomial in both @expr{x} and @expr{y}. Polynomial coefficients
22942are often numbers, but they may in general be any formulas not
22943involving the base variable.
22944
22945@kindex a f
22946@pindex calc-factor
22947@tindex factor
22948The @kbd{a f} (@code{calc-factor}) [@code{factor}] command factors a
22949polynomial into a product of terms. For example, the polynomial
22950@expr{x^3 + 2 x^2 + x} is factored into @samp{x*(x+1)^2}. As another
22951example, @expr{a c + b d + b c + a d} is factored into the product
22952@expr{(a + b) (c + d)}.
22953
22954Calc currently has three algorithms for factoring. Formulas which are
22955linear in several variables, such as the second example above, are
22956merged according to the distributive law. Formulas which are
22957polynomials in a single variable, with constant integer or fractional
22958coefficients, are factored into irreducible linear and/or quadratic
22959terms. The first example above factors into three linear terms
22960(@expr{x}, @expr{x+1}, and @expr{x+1} again). Finally, formulas
22961which do not fit the above criteria are handled by the algebraic
22962rewrite mechanism.
22963
22964Calc's polynomial factorization algorithm works by using the general
22965root-finding command (@w{@kbd{a P}}) to solve for the roots of the
22966polynomial. It then looks for roots which are rational numbers
22967or complex-conjugate pairs, and converts these into linear and
22968quadratic terms, respectively. Because it uses floating-point
22969arithmetic, it may be unable to find terms that involve large
22970integers (whose number of digits approaches the current precision).
22971Also, irreducible factors of degree higher than quadratic are not
22972found, and polynomials in more than one variable are not treated.
22973(A more robust factorization algorithm may be included in a future
22974version of Calc.)
22975
22976@vindex FactorRules
22977@ignore
22978@starindex
22979@end ignore
22980@tindex thecoefs
22981@ignore
22982@starindex
22983@end ignore
22984@ignore
22985@mindex @idots
22986@end ignore
22987@tindex thefactors
22988The rewrite-based factorization method uses rules stored in the variable
22989@code{FactorRules}. @xref{Rewrite Rules}, for a discussion of the
22990operation of rewrite rules. The default @code{FactorRules} are able
22991to factor quadratic forms symbolically into two linear terms,
22992@expr{(a x + b) (c x + d)}. You can edit these rules to include other
22993cases if you wish. To use the rules, Calc builds the formula
22994@samp{thecoefs(x, [a, b, c, ...])} where @code{x} is the polynomial
22995base variable and @code{a}, @code{b}, etc., are polynomial coefficients
22996(which may be numbers or formulas). The constant term is written first,
22997i.e., in the @code{a} position. When the rules complete, they should have
22998changed the formula into the form @samp{thefactors(x, [f1, f2, f3, ...])}
22999where each @code{fi} should be a factored term, e.g., @samp{x - ai}.
23000Calc then multiplies these terms together to get the complete
23001factored form of the polynomial. If the rules do not change the
23002@code{thecoefs} call to a @code{thefactors} call, @kbd{a f} leaves the
23003polynomial alone on the assumption that it is unfactorable. (Note that
23004the function names @code{thecoefs} and @code{thefactors} are used only
23005as placeholders; there are no actual Calc functions by those names.)
23006
23007@kindex H a f
23008@tindex factors
23009The @kbd{H a f} [@code{factors}] command also factors a polynomial,
23010but it returns a list of factors instead of an expression which is the
23011product of the factors. Each factor is represented by a sub-vector
23012of the factor, and the power with which it appears. For example,
23013@expr{x^5 + x^4 - 33 x^3 + 63 x^2} factors to @expr{(x + 7) x^2 (x - 3)^2}
23014in @kbd{a f}, or to @expr{[ [x, 2], [x+7, 1], [x-3, 2] ]} in @kbd{H a f}.
23015If there is an overall numeric factor, it always comes first in the list.
23016The functions @code{factor} and @code{factors} allow a second argument
23017when written in algebraic form; @samp{factor(x,v)} factors @expr{x} with
23018respect to the specific variable @expr{v}. The default is to factor with
23019respect to all the variables that appear in @expr{x}.
23020
23021@kindex a c
23022@pindex calc-collect
23023@tindex collect
23024The @kbd{a c} (@code{calc-collect}) [@code{collect}] command rearranges a
23025formula as a
23026polynomial in a given variable, ordered in decreasing powers of that
23027variable. For example, given @expr{1 + 2 x + 3 y + 4 x y^2} on
23028the stack, @kbd{a c x} would produce @expr{(2 + 4 y^2) x + (1 + 3 y)},
23029and @kbd{a c y} would produce @expr{(4 x) y^2 + 3 y + (1 + 2 x)}.
23030The polynomial will be expanded out using the distributive law as
23031necessary: Collecting @expr{x} in @expr{(x - 1)^3} produces
23032@expr{x^3 - 3 x^2 + 3 x - 1}. Terms not involving @expr{x} will
23033not be expanded.
23034
23035The ``variable'' you specify at the prompt can actually be any
23036expression: @kbd{a c ln(x+1)} will collect together all terms multiplied
23037by @samp{ln(x+1)} or integer powers thereof. If @samp{x} also appears
23038in the formula in a context other than @samp{ln(x+1)}, @kbd{a c} will
23039treat those occurrences as unrelated to @samp{ln(x+1)}, i.e., as constants.
23040
23041@kindex a x
23042@pindex calc-expand
23043@tindex expand
23044The @kbd{a x} (@code{calc-expand}) [@code{expand}] command expands an
23045expression by applying the distributive law everywhere. It applies to
23046products, quotients, and powers involving sums. By default, it fully
23047distributes all parts of the expression. With a numeric prefix argument,
23048the distributive law is applied only the specified number of times, then
23049the partially expanded expression is left on the stack.
23050
23051The @kbd{a x} and @kbd{j D} commands are somewhat redundant. Use
23052@kbd{a x} if you want to expand all products of sums in your formula.
23053Use @kbd{j D} if you want to expand a particular specified term of
23054the formula. There is an exactly analogous correspondence between
23055@kbd{a f} and @kbd{j M}. (The @kbd{j D} and @kbd{j M} commands
23056also know many other kinds of expansions, such as
23057@samp{exp(a + b) = exp(a) exp(b)}, which @kbd{a x} and @kbd{a f}
23058do not do.)
23059
23060Calc's automatic simplifications will sometimes reverse a partial
23061expansion. For example, the first step in expanding @expr{(x+1)^3} is
23062to write @expr{(x+1) (x+1)^2}. If @kbd{a x} stops there and tries
23063to put this formula onto the stack, though, Calc will automatically
23064simplify it back to @expr{(x+1)^3} form. The solution is to turn
23065simplification off first (@pxref{Simplification Modes}), or to run
23066@kbd{a x} without a numeric prefix argument so that it expands all
23067the way in one step.
23068
23069@kindex a a
23070@pindex calc-apart
23071@tindex apart
23072The @kbd{a a} (@code{calc-apart}) [@code{apart}] command expands a
23073rational function by partial fractions. A rational function is the
23074quotient of two polynomials; @code{apart} pulls this apart into a
23075sum of rational functions with simple denominators. In algebraic
23076notation, the @code{apart} function allows a second argument that
23077specifies which variable to use as the ``base''; by default, Calc
23078chooses the base variable automatically.
23079
23080@kindex a n
23081@pindex calc-normalize-rat
23082@tindex nrat
23083The @kbd{a n} (@code{calc-normalize-rat}) [@code{nrat}] command
23084attempts to arrange a formula into a quotient of two polynomials.
23085For example, given @expr{1 + (a + b/c) / d}, the result would be
23086@expr{(b + a c + c d) / c d}. The quotient is reduced, so that
23087@kbd{a n} will simplify @expr{(x^2 + 2x + 1) / (x^2 - 1)} by dividing
23088out the common factor @expr{x + 1}, yielding @expr{(x + 1) / (x - 1)}.
23089
23090@kindex a \
23091@pindex calc-poly-div
23092@tindex pdiv
23093The @kbd{a \} (@code{calc-poly-div}) [@code{pdiv}] command divides
23094two polynomials @expr{u} and @expr{v}, yielding a new polynomial
23095@expr{q}. If several variables occur in the inputs, the inputs are
23096considered multivariate polynomials. (Calc divides by the variable
23097with the largest power in @expr{u} first, or, in the case of equal
23098powers, chooses the variables in alphabetical order.) For example,
23099dividing @expr{x^2 + 3 x + 2} by @expr{x + 2} yields @expr{x + 1}.
23100The remainder from the division, if any, is reported at the bottom
23101of the screen and is also placed in the Trail along with the quotient.
23102
23103Using @code{pdiv} in algebraic notation, you can specify the particular
23104variable to be used as the base: @code{pdiv(@var{a},@var{b},@var{x})}.
23105If @code{pdiv} is given only two arguments (as is always the case with
23106the @kbd{a \} command), then it does a multivariate division as outlined
23107above.
23108
23109@kindex a %
23110@pindex calc-poly-rem
23111@tindex prem
23112The @kbd{a %} (@code{calc-poly-rem}) [@code{prem}] command divides
23113two polynomials and keeps the remainder @expr{r}. The quotient
23114@expr{q} is discarded. For any formulas @expr{a} and @expr{b}, the
23115results of @kbd{a \} and @kbd{a %} satisfy @expr{a = q b + r}.
23116(This is analogous to plain @kbd{\} and @kbd{%}, which compute the
23117integer quotient and remainder from dividing two numbers.)
23118
23119@kindex a /
23120@kindex H a /
23121@pindex calc-poly-div-rem
23122@tindex pdivrem
23123@tindex pdivide
23124The @kbd{a /} (@code{calc-poly-div-rem}) [@code{pdivrem}] command
23125divides two polynomials and reports both the quotient and the
23126remainder as a vector @expr{[q, r]}. The @kbd{H a /} [@code{pdivide}]
23127command divides two polynomials and constructs the formula
23128@expr{q + r/b} on the stack. (Naturally if the remainder is zero,
23129this will immediately simplify to @expr{q}.)
23130
23131@kindex a g
23132@pindex calc-poly-gcd
23133@tindex pgcd
23134The @kbd{a g} (@code{calc-poly-gcd}) [@code{pgcd}] command computes
23135the greatest common divisor of two polynomials. (The GCD actually
23136is unique only to within a constant multiplier; Calc attempts to
23137choose a GCD which will be unsurprising.) For example, the @kbd{a n}
23138command uses @kbd{a g} to take the GCD of the numerator and denominator
23139of a quotient, then divides each by the result using @kbd{a \}. (The
23140definition of GCD ensures that this division can take place without
23141leaving a remainder.)
23142
23143While the polynomials used in operations like @kbd{a /} and @kbd{a g}
23144often have integer coefficients, this is not required. Calc can also
23145deal with polynomials over the rationals or floating-point reals.
23146Polynomials with modulo-form coefficients are also useful in many
23147applications; if you enter @samp{(x^2 + 3 x - 1) mod 5}, Calc
23148automatically transforms this into a polynomial over the field of
23149integers mod 5: @samp{(1 mod 5) x^2 + (3 mod 5) x + (4 mod 5)}.
23150
23151Congratulations and thanks go to Ove Ewerlid
23152(@code{ewerlid@@mizar.DoCS.UU.SE}), who contributed many of the
23153polynomial routines used in the above commands.
23154
23155@xref{Decomposing Polynomials}, for several useful functions for
23156extracting the individual coefficients of a polynomial.
23157
23158@node Calculus, Solving Equations, Polynomials, Algebra
23159@section Calculus
23160
23161@noindent
23162The following calculus commands do not automatically simplify their
23163inputs or outputs using @code{calc-simplify}. You may find it helps
23164to do this by hand by typing @kbd{a s} or @kbd{a e}. It may also help
23165to use @kbd{a x} and/or @kbd{a c} to arrange a result in the most
23166readable way.
23167
23168@menu
23169* Differentiation::
23170* Integration::
23171* Customizing the Integrator::
23172* Numerical Integration::
23173* Taylor Series::
23174@end menu
23175
23176@node Differentiation, Integration, Calculus, Calculus
23177@subsection Differentiation
23178
23179@noindent
23180@kindex a d
23181@kindex H a d
23182@pindex calc-derivative
23183@tindex deriv
23184@tindex tderiv
23185The @kbd{a d} (@code{calc-derivative}) [@code{deriv}] command computes
23186the derivative of the expression on the top of the stack with respect to
23187some variable, which it will prompt you to enter. Normally, variables
23188in the formula other than the specified differentiation variable are
23189considered constant, i.e., @samp{deriv(y,x)} is reduced to zero. With
23190the Hyperbolic flag, the @code{tderiv} (total derivative) operation is used
23191instead, in which derivatives of variables are not reduced to zero
23192unless those variables are known to be ``constant,'' i.e., independent
23193of any other variables. (The built-in special variables like @code{pi}
23194are considered constant, as are variables that have been declared
23195@code{const}; @pxref{Declarations}.)
23196
23197With a numeric prefix argument @var{n}, this command computes the
23198@var{n}th derivative.
23199
23200When working with trigonometric functions, it is best to switch to
23201Radians mode first (with @w{@kbd{m r}}). The derivative of @samp{sin(x)}
23202in degrees is @samp{(pi/180) cos(x)}, probably not the expected
23203answer!
23204
23205If you use the @code{deriv} function directly in an algebraic formula,
23206you can write @samp{deriv(f,x,x0)} which represents the derivative
23207of @expr{f} with respect to @expr{x}, evaluated at the point
23208@texline @math{x=x_0}.
23209@infoline @expr{x=x0}.
23210
23211If the formula being differentiated contains functions which Calc does
23212not know, the derivatives of those functions are produced by adding
23213primes (apostrophe characters). For example, @samp{deriv(f(2x), x)}
23214produces @samp{2 f'(2 x)}, where the function @code{f'} represents the
23215derivative of @code{f}.
23216
23217For functions you have defined with the @kbd{Z F} command, Calc expands
23218the functions according to their defining formulas unless you have
23219also defined @code{f'} suitably. For example, suppose we define
23220@samp{sinc(x) = sin(x)/x} using @kbd{Z F}. If we then differentiate
23221the formula @samp{sinc(2 x)}, the formula will be expanded to
23222@samp{sin(2 x) / (2 x)} and differentiated. However, if we also
23223define @samp{sinc'(x) = dsinc(x)}, say, then Calc will write the
23224result as @samp{2 dsinc(2 x)}. @xref{Algebraic Definitions}.
23225
23226For multi-argument functions @samp{f(x,y,z)}, the derivative with respect
23227to the first argument is written @samp{f'(x,y,z)}; derivatives with
23228respect to the other arguments are @samp{f'2(x,y,z)} and @samp{f'3(x,y,z)}.
23229Various higher-order derivatives can be formed in the obvious way, e.g.,
23230@samp{f'@var{}'(x)} (the second derivative of @code{f}) or
23231@samp{f'@var{}'2'3(x,y,z)} (@code{f} differentiated with respect to each
23232argument once).
23233
23234@node Integration, Customizing the Integrator, Differentiation, Calculus
23235@subsection Integration
23236
23237@noindent
23238@kindex a i
23239@pindex calc-integral
23240@tindex integ
23241The @kbd{a i} (@code{calc-integral}) [@code{integ}] command computes the
23242indefinite integral of the expression on the top of the stack with
23243respect to a prompted-for variable. The integrator is not guaranteed to
23244work for all integrable functions, but it is able to integrate several
23245large classes of formulas. In particular, any polynomial or rational
23246function (a polynomial divided by a polynomial) is acceptable.
23247(Rational functions don't have to be in explicit quotient form, however;
23248@texline @math{x/(1+x^{-2})}
23249@infoline @expr{x/(1+x^-2)}
23250is not strictly a quotient of polynomials, but it is equivalent to
23251@expr{x^3/(x^2+1)}, which is.) Also, square roots of terms involving
23252@expr{x} and @expr{x^2} may appear in rational functions being
23253integrated. Finally, rational functions involving trigonometric or
23254hyperbolic functions can be integrated.
23255
23256With an argument (@kbd{C-u a i}), this command will compute the definite
23257integral of the expression on top of the stack. In this case, the
23258command will again prompt for an integration variable, then prompt for a
23259lower limit and an upper limit.
23260
23261@ifnottex
23262If you use the @code{integ} function directly in an algebraic formula,
23263you can also write @samp{integ(f,x,v)} which expresses the resulting
23264indefinite integral in terms of variable @code{v} instead of @code{x}.
23265With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
23266integral from @code{a} to @code{b}.
23267@end ifnottex
23268@tex
23269If you use the @code{integ} function directly in an algebraic formula,
23270you can also write @samp{integ(f,x,v)} which expresses the resulting
23271indefinite integral in terms of variable @code{v} instead of @code{x}.
23272With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
23273integral $\int_a^b f(x) \, dx$.
23274@end tex
23275
23276Please note that the current implementation of Calc's integrator sometimes
23277produces results that are significantly more complex than they need to
23278be. For example, the integral Calc finds for
23279@texline @math{1/(x+\sqrt{x^2+1})}
23280@infoline @expr{1/(x+sqrt(x^2+1))}
23281is several times more complicated than the answer Mathematica
23282returns for the same input, although the two forms are numerically
23283equivalent. Also, any indefinite integral should be considered to have
23284an arbitrary constant of integration added to it, although Calc does not
23285write an explicit constant of integration in its result. For example,
23286Calc's solution for
23287@texline @math{1/(1+\tan x)}
23288@infoline @expr{1/(1+tan(x))}
23289differs from the solution given in the @emph{CRC Math Tables} by a
23290constant factor of
23291@texline @math{\pi i / 2}
23292@infoline @expr{pi i / 2},
23293due to a different choice of constant of integration.
23294
23295The Calculator remembers all the integrals it has done. If conditions
23296change in a way that would invalidate the old integrals, say, a switch
23297from Degrees to Radians mode, then they will be thrown out. If you
23298suspect this is not happening when it should, use the
23299@code{calc-flush-caches} command; @pxref{Caches}.
23300
23301@vindex IntegLimit
23302Calc normally will pursue integration by substitution or integration by
23303parts up to 3 nested times before abandoning an approach as fruitless.
23304If the integrator is taking too long, you can lower this limit by storing
23305a number (like 2) in the variable @code{IntegLimit}. (The @kbd{s I}
23306command is a convenient way to edit @code{IntegLimit}.) If this variable
23307has no stored value or does not contain a nonnegative integer, a limit
23308of 3 is used. The lower this limit is, the greater the chance that Calc
23309will be unable to integrate a function it could otherwise handle. Raising
23310this limit allows the Calculator to solve more integrals, though the time
23311it takes may grow exponentially. You can monitor the integrator's actions
23312by creating an Emacs buffer called @code{*Trace*}. If such a buffer
23313exists, the @kbd{a i} command will write a log of its actions there.
23314
23315If you want to manipulate integrals in a purely symbolic way, you can
23316set the integration nesting limit to 0 to prevent all but fast
23317table-lookup solutions of integrals. You might then wish to define
23318rewrite rules for integration by parts, various kinds of substitutions,
23319and so on. @xref{Rewrite Rules}.
23320
23321@node Customizing the Integrator, Numerical Integration, Integration, Calculus
23322@subsection Customizing the Integrator
23323
23324@noindent
23325@vindex IntegRules
23326Calc has two built-in rewrite rules called @code{IntegRules} and
23327@code{IntegAfterRules} which you can edit to define new integration
23328methods. @xref{Rewrite Rules}. At each step of the integration process,
23329Calc wraps the current integrand in a call to the fictitious function
23330@samp{integtry(@var{expr},@var{var})}, where @var{expr} is the
23331integrand and @var{var} is the integration variable. If your rules
23332rewrite this to be a plain formula (not a call to @code{integtry}), then
23333Calc will use this formula as the integral of @var{expr}. For example,
23334the rule @samp{integtry(mysin(x),x) := -mycos(x)} would define a rule to
23335integrate a function @code{mysin} that acts like the sine function.
23336Then, putting @samp{4 mysin(2y+1)} on the stack and typing @kbd{a i y}
23337will produce the integral @samp{-2 mycos(2y+1)}. Note that Calc has
23338automatically made various transformations on the integral to allow it
23339to use your rule; integral tables generally give rules for
23340@samp{mysin(a x + b)}, but you don't need to use this much generality
23341in your @code{IntegRules}.
23342
23343@cindex Exponential integral Ei(x)
23344@ignore
23345@starindex
23346@end ignore
23347@tindex Ei
23348As a more serious example, the expression @samp{exp(x)/x} cannot be
23349integrated in terms of the standard functions, so the ``exponential
23350integral'' function
23351@texline @math{{\rm Ei}(x)}
23352@infoline @expr{Ei(x)}
23353was invented to describe it.
23354We can get Calc to do this integral in terms of a made-up @code{Ei}
23355function by adding the rule @samp{[integtry(exp(x)/x, x) := Ei(x)]}
23356to @code{IntegRules}. Now entering @samp{exp(2x)/x} on the stack
23357and typing @kbd{a i x} yields @samp{Ei(2 x)}. This new rule will
23358work with Calc's various built-in integration methods (such as
23359integration by substitution) to solve a variety of other problems
23360involving @code{Ei}: For example, now Calc will also be able to
23361integrate @samp{exp(exp(x))} and @samp{ln(ln(x))} (to get @samp{Ei(exp(x))}
23362and @samp{x ln(ln(x)) - Ei(ln(x))}, respectively).
23363
23364Your rule may do further integration by calling @code{integ}. For
23365example, @samp{integtry(twice(u),x) := twice(integ(u))} allows Calc
23366to integrate @samp{twice(sin(x))} to get @samp{twice(-cos(x))}.
23367Note that @code{integ} was called with only one argument. This notation
23368is allowed only within @code{IntegRules}; it means ``integrate this
23369with respect to the same integration variable.'' If Calc is unable
23370to integrate @code{u}, the integration that invoked @code{IntegRules}
23371also fails. Thus integrating @samp{twice(f(x))} fails, returning the
23372unevaluated integral @samp{integ(twice(f(x)), x)}. It is still valid
23373to call @code{integ} with two or more arguments, however; in this case,
23374if @code{u} is not integrable, @code{twice} itself will still be
23375integrated: If the above rule is changed to @samp{... := twice(integ(u,x))},
23376then integrating @samp{twice(f(x))} will yield @samp{twice(integ(f(x),x))}.
23377
23378If a rule instead produces the formula @samp{integsubst(@var{sexpr},
23379@var{svar})}, either replacing the top-level @code{integtry} call or
23380nested anywhere inside the expression, then Calc will apply the
23381substitution @samp{@var{u} = @var{sexpr}(@var{svar})} to try to
23382integrate the original @var{expr}. For example, the rule
23383@samp{sqrt(a) := integsubst(sqrt(x),x)} says that if Calc ever finds
23384a square root in the integrand, it should attempt the substitution
23385@samp{u = sqrt(x)}. (This particular rule is unnecessary because
23386Calc always tries ``obvious'' substitutions where @var{sexpr} actually
23387appears in the integrand.) The variable @var{svar} may be the same
23388as the @var{var} that appeared in the call to @code{integtry}, but
23389it need not be.
23390
23391When integrating according to an @code{integsubst}, Calc uses the
23392equation solver to find the inverse of @var{sexpr} (if the integrand
23393refers to @var{var} anywhere except in subexpressions that exactly
23394match @var{sexpr}). It uses the differentiator to find the derivative
23395of @var{sexpr} and/or its inverse (it has two methods that use one
23396derivative or the other). You can also specify these items by adding
23397extra arguments to the @code{integsubst} your rules construct; the
23398general form is @samp{integsubst(@var{sexpr}, @var{svar}, @var{sinv},
23399@var{sprime})}, where @var{sinv} is the inverse of @var{sexpr} (still
23400written as a function of @var{svar}), and @var{sprime} is the
23401derivative of @var{sexpr} with respect to @var{svar}. If you don't
23402specify these things, and Calc is not able to work them out on its
23403own with the information it knows, then your substitution rule will
23404work only in very specific, simple cases.
23405
23406Calc applies @code{IntegRules} as if by @kbd{C-u 1 a r IntegRules};
23407in other words, Calc stops rewriting as soon as any rule in your rule
23408set succeeds. (If it weren't for this, the @samp{integsubst(sqrt(x),x)}
23409example above would keep on adding layers of @code{integsubst} calls
23410forever!)
23411
23412@vindex IntegSimpRules
23413Another set of rules, stored in @code{IntegSimpRules}, are applied
23414every time the integrator uses @kbd{a s} to simplify an intermediate
23415result. For example, putting the rule @samp{twice(x) := 2 x} into
23416@code{IntegSimpRules} would tell Calc to convert the @code{twice}
23417function into a form it knows whenever integration is attempted.
23418
23419One more way to influence the integrator is to define a function with
23420the @kbd{Z F} command (@pxref{Algebraic Definitions}). Calc's
23421integrator automatically expands such functions according to their
23422defining formulas, even if you originally asked for the function to
23423be left unevaluated for symbolic arguments. (Certain other Calc
23424systems, such as the differentiator and the equation solver, also
23425do this.)
23426
23427@vindex IntegAfterRules
23428Sometimes Calc is able to find a solution to your integral, but it
23429expresses the result in a way that is unnecessarily complicated. If
23430this happens, you can either use @code{integsubst} as described
23431above to try to hint at a more direct path to the desired result, or
23432you can use @code{IntegAfterRules}. This is an extra rule set that
23433runs after the main integrator returns its result; basically, Calc does
23434an @kbd{a r IntegAfterRules} on the result before showing it to you.
23435(It also does an @kbd{a s}, without @code{IntegSimpRules}, after that
23436to further simplify the result.) For example, Calc's integrator
23437sometimes produces expressions of the form @samp{ln(1+x) - ln(1-x)};
23438the default @code{IntegAfterRules} rewrite this into the more readable
23439form @samp{2 arctanh(x)}. Note that, unlike @code{IntegRules},
23440@code{IntegSimpRules} and @code{IntegAfterRules} are applied any number
23441of times until no further changes are possible. Rewriting by
23442@code{IntegAfterRules} occurs only after the main integrator has
23443finished, not at every step as for @code{IntegRules} and
23444@code{IntegSimpRules}.
23445
23446@node Numerical Integration, Taylor Series, Customizing the Integrator, Calculus
23447@subsection Numerical Integration
23448
23449@noindent
23450@kindex a I
23451@pindex calc-num-integral
23452@tindex ninteg
23453If you want a purely numerical answer to an integration problem, you can
23454use the @kbd{a I} (@code{calc-num-integral}) [@code{ninteg}] command. This
23455command prompts for an integration variable, a lower limit, and an
23456upper limit. Except for the integration variable, all other variables
23457that appear in the integrand formula must have stored values. (A stored
23458value, if any, for the integration variable itself is ignored.)
23459
23460Numerical integration works by evaluating your formula at many points in
23461the specified interval. Calc uses an ``open Romberg'' method; this means
23462that it does not evaluate the formula actually at the endpoints (so that
23463it is safe to integrate @samp{sin(x)/x} from zero, for example). Also,
23464the Romberg method works especially well when the function being
23465integrated is fairly smooth. If the function is not smooth, Calc will
23466have to evaluate it at quite a few points before it can accurately
23467determine the value of the integral.
23468
23469Integration is much faster when the current precision is small. It is
23470best to set the precision to the smallest acceptable number of digits
23471before you use @kbd{a I}. If Calc appears to be taking too long, press
23472@kbd{C-g} to halt it and try a lower precision. If Calc still appears
23473to need hundreds of evaluations, check to make sure your function is
23474well-behaved in the specified interval.
23475
23476It is possible for the lower integration limit to be @samp{-inf} (minus
23477infinity). Likewise, the upper limit may be plus infinity. Calc
23478internally transforms the integral into an equivalent one with finite
23479limits. However, integration to or across singularities is not supported:
23480The integral of @samp{1/sqrt(x)} from 0 to 1 exists (it can be found
23481by Calc's symbolic integrator, for example), but @kbd{a I} will fail
23482because the integrand goes to infinity at one of the endpoints.
23483
23484@node Taylor Series, , Numerical Integration, Calculus
23485@subsection Taylor Series
23486
23487@noindent
23488@kindex a t
23489@pindex calc-taylor
23490@tindex taylor
23491The @kbd{a t} (@code{calc-taylor}) [@code{taylor}] command computes a
23492power series expansion or Taylor series of a function. You specify the
23493variable and the desired number of terms. You may give an expression of
23494the form @samp{@var{var} = @var{a}} or @samp{@var{var} - @var{a}} instead
23495of just a variable to produce a Taylor expansion about the point @var{a}.
23496You may specify the number of terms with a numeric prefix argument;
23497otherwise the command will prompt you for the number of terms. Note that
23498many series expansions have coefficients of zero for some terms, so you
23499may appear to get fewer terms than you asked for.
23500
23501If the @kbd{a i} command is unable to find a symbolic integral for a
23502function, you can get an approximation by integrating the function's
23503Taylor series.
23504
23505@node Solving Equations, Numerical Solutions, Calculus, Algebra
23506@section Solving Equations
23507
23508@noindent
23509@kindex a S
23510@pindex calc-solve-for
23511@tindex solve
23512@cindex Equations, solving
23513@cindex Solving equations
23514The @kbd{a S} (@code{calc-solve-for}) [@code{solve}] command rearranges
23515an equation to solve for a specific variable. An equation is an
23516expression of the form @expr{L = R}. For example, the command @kbd{a S x}
23517will rearrange @expr{y = 3x + 6} to the form, @expr{x = y/3 - 2}. If the
23518input is not an equation, it is treated like an equation of the
23519form @expr{X = 0}.
23520
23521This command also works for inequalities, as in @expr{y < 3x + 6}.
23522Some inequalities cannot be solved where the analogous equation could
23523be; for example, solving
23524@texline @math{a < b \, c}
23525@infoline @expr{a < b c}
23526for @expr{b} is impossible
23527without knowing the sign of @expr{c}. In this case, @kbd{a S} will
23528produce the result
23529@texline @math{b \mathbin{\hbox{\code{!=}}} a/c}
23530@infoline @expr{b != a/c}
23531(using the not-equal-to operator) to signify that the direction of the
23532inequality is now unknown. The inequality
23533@texline @math{a \le b \, c}
23534@infoline @expr{a <= b c}
23535is not even partially solved. @xref{Declarations}, for a way to tell
23536Calc that the signs of the variables in a formula are in fact known.
23537
23538Two useful commands for working with the result of @kbd{a S} are
23539@kbd{a .} (@pxref{Logical Operations}), which converts @expr{x = y/3 - 2}
23540to @expr{y/3 - 2}, and @kbd{s l} (@pxref{Let Command}) which evaluates
23541another formula with @expr{x} set equal to @expr{y/3 - 2}.
23542
23543@menu
23544* Multiple Solutions::
23545* Solving Systems of Equations::
23546* Decomposing Polynomials::
23547@end menu
23548
23549@node Multiple Solutions, Solving Systems of Equations, Solving Equations, Solving Equations
23550@subsection Multiple Solutions
23551
23552@noindent
23553@kindex H a S
23554@tindex fsolve
23555Some equations have more than one solution. The Hyperbolic flag
23556(@code{H a S}) [@code{fsolve}] tells the solver to report the fully
23557general family of solutions. It will invent variables @code{n1},
23558@code{n2}, @dots{}, which represent independent arbitrary integers, and
23559@code{s1}, @code{s2}, @dots{}, which represent independent arbitrary
23560signs (either @mathit{+1} or @mathit{-1}). If you don't use the Hyperbolic
23561flag, Calc will use zero in place of all arbitrary integers, and plus
23562one in place of all arbitrary signs. Note that variables like @code{n1}
23563and @code{s1} are not given any special interpretation in Calc except by
23564the equation solver itself. As usual, you can use the @w{@kbd{s l}}
23565(@code{calc-let}) command to obtain solutions for various actual values
23566of these variables.
23567
23568For example, @kbd{' x^2 = y @key{RET} H a S x @key{RET}} solves to
23569get @samp{x = s1 sqrt(y)}, indicating that the two solutions to the
23570equation are @samp{sqrt(y)} and @samp{-sqrt(y)}. Another way to
23571think about it is that the square-root operation is really a
23572two-valued function; since every Calc function must return a
23573single result, @code{sqrt} chooses to return the positive result.
23574Then @kbd{H a S} doctors this result using @code{s1} to indicate
23575the full set of possible values of the mathematical square-root.
23576
23577There is a similar phenomenon going the other direction: Suppose
23578we solve @samp{sqrt(y) = x} for @code{y}. Calc squares both sides
23579to get @samp{y = x^2}. This is correct, except that it introduces
23580some dubious solutions. Consider solving @samp{sqrt(y) = -3}:
23581Calc will report @expr{y = 9} as a valid solution, which is true
23582in the mathematical sense of square-root, but false (there is no
23583solution) for the actual Calc positive-valued @code{sqrt}. This
23584happens for both @kbd{a S} and @kbd{H a S}.
23585
23586@cindex @code{GenCount} variable
23587@vindex GenCount
23588@ignore
23589@starindex
23590@end ignore
23591@tindex an
23592@ignore
23593@starindex
23594@end ignore
23595@tindex as
23596If you store a positive integer in the Calc variable @code{GenCount},
23597then Calc will generate formulas of the form @samp{as(@var{n})} for
23598arbitrary signs, and @samp{an(@var{n})} for arbitrary integers,
23599where @var{n} represents successive values taken by incrementing
23600@code{GenCount} by one. While the normal arbitrary sign and
23601integer symbols start over at @code{s1} and @code{n1} with each
23602new Calc command, the @code{GenCount} approach will give each
23603arbitrary value a name that is unique throughout the entire Calc
23604session. Also, the arbitrary values are function calls instead
23605of variables, which is advantageous in some cases. For example,
23606you can make a rewrite rule that recognizes all arbitrary signs
23607using a pattern like @samp{as(n)}. The @kbd{s l} command only works
23608on variables, but you can use the @kbd{a b} (@code{calc-substitute})
23609command to substitute actual values for function calls like @samp{as(3)}.
23610
23611The @kbd{s G} (@code{calc-edit-GenCount}) command is a convenient
23612way to create or edit this variable. Press @kbd{C-c C-c} to finish.
23613
23614If you have not stored a value in @code{GenCount}, or if the value
23615in that variable is not a positive integer, the regular
23616@code{s1}/@code{n1} notation is used.
23617
23618@kindex I a S
23619@kindex H I a S
23620@tindex finv
23621@tindex ffinv
23622With the Inverse flag, @kbd{I a S} [@code{finv}] treats the expression
23623on top of the stack as a function of the specified variable and solves
23624to find the inverse function, written in terms of the same variable.
23625For example, @kbd{I a S x} inverts @expr{2x + 6} to @expr{x/2 - 3}.
23626You can use both Inverse and Hyperbolic [@code{ffinv}] to obtain a
23627fully general inverse, as described above.
23628
23629@kindex a P
23630@pindex calc-poly-roots
23631@tindex roots
23632Some equations, specifically polynomials, have a known, finite number
23633of solutions. The @kbd{a P} (@code{calc-poly-roots}) [@code{roots}]
23634command uses @kbd{H a S} to solve an equation in general form, then, for
23635all arbitrary-sign variables like @code{s1}, and all arbitrary-integer
23636variables like @code{n1} for which @code{n1} only usefully varies over
23637a finite range, it expands these variables out to all their possible
23638values. The results are collected into a vector, which is returned.
23639For example, @samp{roots(x^4 = 1, x)} returns the four solutions
23640@samp{[1, -1, (0, 1), (0, -1)]}. Generally an @var{n}th degree
23641polynomial will always have @var{n} roots on the complex plane.
23642(If you have given a @code{real} declaration for the solution
23643variable, then only the real-valued solutions, if any, will be
23644reported; @pxref{Declarations}.)
23645
23646Note that because @kbd{a P} uses @kbd{H a S}, it is able to deliver
23647symbolic solutions if the polynomial has symbolic coefficients. Also
23648note that Calc's solver is not able to get exact symbolic solutions
23649to all polynomials. Polynomials containing powers up to @expr{x^4}
23650can always be solved exactly; polynomials of higher degree sometimes
23651can be: @expr{x^6 + x^3 + 1} is converted to @expr{(x^3)^2 + (x^3) + 1},
23652which can be solved for @expr{x^3} using the quadratic equation, and then
23653for @expr{x} by taking cube roots. But in many cases, like
23654@expr{x^6 + x + 1}, Calc does not know how to rewrite the polynomial
23655into a form it can solve. The @kbd{a P} command can still deliver a
23656list of numerical roots, however, provided that Symbolic mode (@kbd{m s})
23657is not turned on. (If you work with Symbolic mode on, recall that the
23658@kbd{N} (@code{calc-eval-num}) key is a handy way to reevaluate the
23659formula on the stack with Symbolic mode temporarily off.) Naturally,
23660@kbd{a P} can only provide numerical roots if the polynomial coefficients
23661are all numbers (real or complex).
23662
23663@node Solving Systems of Equations, Decomposing Polynomials, Multiple Solutions, Solving Equations
23664@subsection Solving Systems of Equations
23665
23666@noindent
23667@cindex Systems of equations, symbolic
23668You can also use the commands described above to solve systems of
23669simultaneous equations. Just create a vector of equations, then
23670specify a vector of variables for which to solve. (You can omit
23671the surrounding brackets when entering the vector of variables
23672at the prompt.)
23673
23674For example, putting @samp{[x + y = a, x - y = b]} on the stack
23675and typing @kbd{a S x,y @key{RET}} produces the vector of solutions
23676@samp{[x = a - (a-b)/2, y = (a-b)/2]}. The result vector will
23677have the same length as the variables vector, and the variables
23678will be listed in the same order there. Note that the solutions
23679are not always simplified as far as possible; the solution for
23680@expr{x} here could be improved by an application of the @kbd{a n}
23681command.
23682
23683Calc's algorithm works by trying to eliminate one variable at a
23684time by solving one of the equations for that variable and then
23685substituting into the other equations. Calc will try all the
23686possibilities, but you can speed things up by noting that Calc
23687first tries to eliminate the first variable with the first
23688equation, then the second variable with the second equation,
23689and so on. It also helps to put the simpler (e.g., more linear)
23690equations toward the front of the list. Calc's algorithm will
23691solve any system of linear equations, and also many kinds of
23692nonlinear systems.
23693
23694@ignore
23695@starindex
23696@end ignore
23697@tindex elim
23698Normally there will be as many variables as equations. If you
23699give fewer variables than equations (an ``over-determined'' system
23700of equations), Calc will find a partial solution. For example,
23701typing @kbd{a S y @key{RET}} with the above system of equations
23702would produce @samp{[y = a - x]}. There are now several ways to
23703express this solution in terms of the original variables; Calc uses
23704the first one that it finds. You can control the choice by adding
23705variable specifiers of the form @samp{elim(@var{v})} to the
23706variables list. This says that @var{v} should be eliminated from
23707the equations; the variable will not appear at all in the solution.
23708For example, typing @kbd{a S y,elim(x)} would yield
23709@samp{[y = a - (b+a)/2]}.
23710
23711If the variables list contains only @code{elim} specifiers,
23712Calc simply eliminates those variables from the equations
23713and then returns the resulting set of equations. For example,
23714@kbd{a S elim(x)} produces @samp{[a - 2 y = b]}. Every variable
23715eliminated will reduce the number of equations in the system
23716by one.
23717
23718Again, @kbd{a S} gives you one solution to the system of
23719equations. If there are several solutions, you can use @kbd{H a S}
23720to get a general family of solutions, or, if there is a finite
23721number of solutions, you can use @kbd{a P} to get a list. (In
23722the latter case, the result will take the form of a matrix where
23723the rows are different solutions and the columns correspond to the
23724variables you requested.)
23725
23726Another way to deal with certain kinds of overdetermined systems of
23727equations is the @kbd{a F} command, which does least-squares fitting
23728to satisfy the equations. @xref{Curve Fitting}.
23729
23730@node Decomposing Polynomials, , Solving Systems of Equations, Solving Equations
23731@subsection Decomposing Polynomials
23732
23733@noindent
23734@ignore
23735@starindex
23736@end ignore
23737@tindex poly
23738The @code{poly} function takes a polynomial and a variable as
23739arguments, and returns a vector of polynomial coefficients (constant
23740coefficient first). For example, @samp{poly(x^3 + 2 x, x)} returns
23741@expr{[0, 2, 0, 1]}. If the input is not a polynomial in @expr{x},
23742the call to @code{poly} is left in symbolic form. If the input does
23743not involve the variable @expr{x}, the input is returned in a list
23744of length one, representing a polynomial with only a constant
23745coefficient. The call @samp{poly(x, x)} returns the vector @expr{[0, 1]}.
23746The last element of the returned vector is guaranteed to be nonzero;
23747note that @samp{poly(0, x)} returns the empty vector @expr{[]}.
23748Note also that @expr{x} may actually be any formula; for example,
23749@samp{poly(sin(x)^2 - sin(x) + 3, sin(x))} returns @expr{[3, -1, 1]}.
23750
23751@cindex Coefficients of polynomial
23752@cindex Degree of polynomial
23753To get the @expr{x^k} coefficient of polynomial @expr{p}, use
23754@samp{poly(p, x)_(k+1)}. To get the degree of polynomial @expr{p},
23755use @samp{vlen(poly(p, x)) - 1}. For example, @samp{poly((x+1)^4, x)}
23756returns @samp{[1, 4, 6, 4, 1]}, so @samp{poly((x+1)^4, x)_(2+1)}
23757gives the @expr{x^2} coefficient of this polynomial, 6.
23758
23759@ignore
23760@starindex
23761@end ignore
23762@tindex gpoly
23763One important feature of the solver is its ability to recognize
23764formulas which are ``essentially'' polynomials. This ability is
23765made available to the user through the @code{gpoly} function, which
23766is used just like @code{poly}: @samp{gpoly(@var{expr}, @var{var})}.
23767If @var{expr} is a polynomial in some term which includes @var{var}, then
23768this function will return a vector @samp{[@var{x}, @var{c}, @var{a}]}
23769where @var{x} is the term that depends on @var{var}, @var{c} is a
23770vector of polynomial coefficients (like the one returned by @code{poly}),
23771and @var{a} is a multiplier which is usually 1. Basically,
23772@samp{@var{expr} = @var{a}*(@var{c}_1 + @var{c}_2 @var{x} +
23773@var{c}_3 @var{x}^2 + ...)}. The last element of @var{c} is
23774guaranteed to be non-zero, and @var{c} will not equal @samp{[1]}
23775(i.e., the trivial decomposition @var{expr} = @var{x} is not
23776considered a polynomial). One side effect is that @samp{gpoly(x, x)}
23777and @samp{gpoly(6, x)}, both of which might be expected to recognize
23778their arguments as polynomials, will not because the decomposition
23779is considered trivial.
23780
23781For example, @samp{gpoly((x-2)^2, x)} returns @samp{[x, [4, -4, 1], 1]},
23782since the expanded form of this polynomial is @expr{4 - 4 x + x^2}.
23783
23784The term @var{x} may itself be a polynomial in @var{var}. This is
23785done to reduce the size of the @var{c} vector. For example,
23786@samp{gpoly(x^4 + x^2 - 1, x)} returns @samp{[x^2, [-1, 1, 1], 1]},
23787since a quadratic polynomial in @expr{x^2} is easier to solve than
23788a quartic polynomial in @expr{x}.
23789
23790A few more examples of the kinds of polynomials @code{gpoly} can
23791discover:
23792
23793@smallexample
23794sin(x) - 1 [sin(x), [-1, 1], 1]
23795x + 1/x - 1 [x, [1, -1, 1], 1/x]
23796x + 1/x [x^2, [1, 1], 1/x]
23797x^3 + 2 x [x^2, [2, 1], x]
23798x + x^2:3 + sqrt(x) [x^1:6, [1, 1, 0, 1], x^1:2]
23799x^(2a) + 2 x^a + 5 [x^a, [5, 2, 1], 1]
23800(exp(-x) + exp(x)) / 2 [e^(2 x), [0.5, 0.5], e^-x]
23801@end smallexample
23802
23803The @code{poly} and @code{gpoly} functions accept a third integer argument
23804which specifies the largest degree of polynomial that is acceptable.
23805If this is @expr{n}, then only @var{c} vectors of length @expr{n+1}
23806or less will be returned. Otherwise, the @code{poly} or @code{gpoly}
23807call will remain in symbolic form. For example, the equation solver
23808can handle quartics and smaller polynomials, so it calls
23809@samp{gpoly(@var{expr}, @var{var}, 4)} to discover whether @var{expr}
23810can be treated by its linear, quadratic, cubic, or quartic formulas.
23811
23812@ignore
23813@starindex
23814@end ignore
23815@tindex pdeg
23816The @code{pdeg} function computes the degree of a polynomial;
23817@samp{pdeg(p,x)} is the highest power of @code{x} that appears in
23818@code{p}. This is the same as @samp{vlen(poly(p,x))-1}, but is
23819much more efficient. If @code{p} is constant with respect to @code{x},
23820then @samp{pdeg(p,x) = 0}. If @code{p} is not a polynomial in @code{x}
23821(e.g., @samp{pdeg(2 cos(x), x)}, the function remains unevaluated.
23822It is possible to omit the second argument @code{x}, in which case
23823@samp{pdeg(p)} returns the highest total degree of any term of the
23824polynomial, counting all variables that appear in @code{p}. Note
23825that @code{pdeg(c) = pdeg(c,x) = 0} for any nonzero constant @code{c};
23826the degree of the constant zero is considered to be @code{-inf}
23827(minus infinity).
23828
23829@ignore
23830@starindex
23831@end ignore
23832@tindex plead
23833The @code{plead} function finds the leading term of a polynomial.
23834Thus @samp{plead(p,x)} is equivalent to @samp{poly(p,x)_vlen(poly(p,x))},
23835though again more efficient. In particular, @samp{plead((2x+1)^10, x)}
23836returns 1024 without expanding out the list of coefficients. The
23837value of @code{plead(p,x)} will be zero only if @expr{p = 0}.
23838
23839@ignore
23840@starindex
23841@end ignore
23842@tindex pcont
23843The @code{pcont} function finds the @dfn{content} of a polynomial. This
23844is the greatest common divisor of all the coefficients of the polynomial.
23845With two arguments, @code{pcont(p,x)} effectively uses @samp{poly(p,x)}
23846to get a list of coefficients, then uses @code{pgcd} (the polynomial
23847GCD function) to combine these into an answer. For example,
23848@samp{pcont(4 x y^2 + 6 x^2 y, x)} is @samp{2 y}. The content is
23849basically the ``biggest'' polynomial that can be divided into @code{p}
23850exactly. The sign of the content is the same as the sign of the leading
23851coefficient.
23852
23853With only one argument, @samp{pcont(p)} computes the numerical
23854content of the polynomial, i.e., the @code{gcd} of the numerical
23855coefficients of all the terms in the formula. Note that @code{gcd}
23856is defined on rational numbers as well as integers; it computes
23857the @code{gcd} of the numerators and the @code{lcm} of the
23858denominators. Thus @samp{pcont(4:3 x y^2 + 6 x^2 y)} returns 2:3.
23859Dividing the polynomial by this number will clear all the
23860denominators, as well as dividing by any common content in the
23861numerators. The numerical content of a polynomial is negative only
23862if all the coefficients in the polynomial are negative.
23863
23864@ignore
23865@starindex
23866@end ignore
23867@tindex pprim
23868The @code{pprim} function finds the @dfn{primitive part} of a
23869polynomial, which is simply the polynomial divided (using @code{pdiv}
23870if necessary) by its content. If the input polynomial has rational
23871coefficients, the result will have integer coefficients in simplest
23872terms.
23873
23874@node Numerical Solutions, Curve Fitting, Solving Equations, Algebra
23875@section Numerical Solutions
23876
23877@noindent
23878Not all equations can be solved symbolically. The commands in this
23879section use numerical algorithms that can find a solution to a specific
23880instance of an equation to any desired accuracy. Note that the
23881numerical commands are slower than their algebraic cousins; it is a
23882good idea to try @kbd{a S} before resorting to these commands.
23883
23884(@xref{Curve Fitting}, for some other, more specialized, operations
23885on numerical data.)
23886
23887@menu
23888* Root Finding::
23889* Minimization::
23890* Numerical Systems of Equations::
23891@end menu
23892
23893@node Root Finding, Minimization, Numerical Solutions, Numerical Solutions
23894@subsection Root Finding
23895
23896@noindent
23897@kindex a R
23898@pindex calc-find-root
23899@tindex root
23900@cindex Newton's method
23901@cindex Roots of equations
23902@cindex Numerical root-finding
23903The @kbd{a R} (@code{calc-find-root}) [@code{root}] command finds a
23904numerical solution (or @dfn{root}) of an equation. (This command treats
23905inequalities the same as equations. If the input is any other kind
23906of formula, it is interpreted as an equation of the form @expr{X = 0}.)
23907
23908The @kbd{a R} command requires an initial guess on the top of the
23909stack, and a formula in the second-to-top position. It prompts for a
23910solution variable, which must appear in the formula. All other variables
23911that appear in the formula must have assigned values, i.e., when
23912a value is assigned to the solution variable and the formula is
23913evaluated with @kbd{=}, it should evaluate to a number. Any assigned
23914value for the solution variable itself is ignored and unaffected by
23915this command.
23916
23917When the command completes, the initial guess is replaced on the stack
23918by a vector of two numbers: The value of the solution variable that
23919solves the equation, and the difference between the lefthand and
23920righthand sides of the equation at that value. Ordinarily, the second
23921number will be zero or very nearly zero. (Note that Calc uses a
23922slightly higher precision while finding the root, and thus the second
23923number may be slightly different from the value you would compute from
23924the equation yourself.)
23925
23926The @kbd{v h} (@code{calc-head}) command is a handy way to extract
23927the first element of the result vector, discarding the error term.
23928
23929The initial guess can be a real number, in which case Calc searches
23930for a real solution near that number, or a complex number, in which
23931case Calc searches the whole complex plane near that number for a
23932solution, or it can be an interval form which restricts the search
23933to real numbers inside that interval.
23934
23935Calc tries to use @kbd{a d} to take the derivative of the equation.
23936If this succeeds, it uses Newton's method. If the equation is not
23937differentiable Calc uses a bisection method. (If Newton's method
23938appears to be going astray, Calc switches over to bisection if it
23939can, or otherwise gives up. In this case it may help to try again
23940with a slightly different initial guess.) If the initial guess is a
23941complex number, the function must be differentiable.
23942
23943If the formula (or the difference between the sides of an equation)
23944is negative at one end of the interval you specify and positive at
23945the other end, the root finder is guaranteed to find a root.
23946Otherwise, Calc subdivides the interval into small parts looking for
23947positive and negative values to bracket the root. When your guess is
23948an interval, Calc will not look outside that interval for a root.
23949
23950@kindex H a R
23951@tindex wroot
23952The @kbd{H a R} [@code{wroot}] command is similar to @kbd{a R}, except
23953that if the initial guess is an interval for which the function has
23954the same sign at both ends, then rather than subdividing the interval
23955Calc attempts to widen it to enclose a root. Use this mode if
23956you are not sure if the function has a root in your interval.
23957
23958If the function is not differentiable, and you give a simple number
23959instead of an interval as your initial guess, Calc uses this widening
23960process even if you did not type the Hyperbolic flag. (If the function
23961@emph{is} differentiable, Calc uses Newton's method which does not
23962require a bounding interval in order to work.)
23963
23964If Calc leaves the @code{root} or @code{wroot} function in symbolic
23965form on the stack, it will normally display an explanation for why
23966no root was found. If you miss this explanation, press @kbd{w}
23967(@code{calc-why}) to get it back.
23968
23969@node Minimization, Numerical Systems of Equations, Root Finding, Numerical Solutions
23970@subsection Minimization
23971
23972@noindent
23973@kindex a N
23974@kindex H a N
23975@kindex a X
23976@kindex H a X
23977@pindex calc-find-minimum
23978@pindex calc-find-maximum
23979@tindex minimize
23980@tindex maximize
23981@cindex Minimization, numerical
23982The @kbd{a N} (@code{calc-find-minimum}) [@code{minimize}] command
23983finds a minimum value for a formula. It is very similar in operation
23984to @kbd{a R} (@code{calc-find-root}): You give the formula and an initial
23985guess on the stack, and are prompted for the name of a variable. The guess
23986may be either a number near the desired minimum, or an interval enclosing
23987the desired minimum. The function returns a vector containing the
23988value of the variable which minimizes the formula's value, along
23989with the minimum value itself.
23990
23991Note that this command looks for a @emph{local} minimum. Many functions
23992have more than one minimum; some, like
23993@texline @math{x \sin x},
23994@infoline @expr{x sin(x)},
23995have infinitely many. In fact, there is no easy way to define the
23996``global'' minimum of
23997@texline @math{x \sin x}
23998@infoline @expr{x sin(x)}
23999but Calc can still locate any particular local minimum
24000for you. Calc basically goes downhill from the initial guess until it
24001finds a point at which the function's value is greater both to the left
24002and to the right. Calc does not use derivatives when minimizing a function.
24003
24004If your initial guess is an interval and it looks like the minimum
24005occurs at one or the other endpoint of the interval, Calc will return
24006that endpoint only if that endpoint is closed; thus, minimizing @expr{17 x}
24007over @expr{[2..3]} will return @expr{[2, 38]}, but minimizing over
24008@expr{(2..3]} would report no minimum found. In general, you should
24009use closed intervals to find literally the minimum value in that
24010range of @expr{x}, or open intervals to find the local minimum, if
24011any, that happens to lie in that range.
24012
24013Most functions are smooth and flat near their minimum values. Because
24014of this flatness, if the current precision is, say, 12 digits, the
24015variable can only be determined meaningfully to about six digits. Thus
24016you should set the precision to twice as many digits as you need in your
24017answer.
24018
24019@ignore
24020@mindex wmin@idots
24021@end ignore
24022@tindex wminimize
24023@ignore
24024@mindex wmax@idots
24025@end ignore
24026@tindex wmaximize
24027The @kbd{H a N} [@code{wminimize}] command, analogously to @kbd{H a R},
24028expands the guess interval to enclose a minimum rather than requiring
24029that the minimum lie inside the interval you supply.
24030
24031The @kbd{a X} (@code{calc-find-maximum}) [@code{maximize}] and
24032@kbd{H a X} [@code{wmaximize}] commands effectively minimize the
24033negative of the formula you supply.
24034
24035The formula must evaluate to a real number at all points inside the
24036interval (or near the initial guess if the guess is a number). If
24037the initial guess is a complex number the variable will be minimized
24038over the complex numbers; if it is real or an interval it will
24039be minimized over the reals.
24040
24041@node Numerical Systems of Equations, , Minimization, Numerical Solutions
24042@subsection Systems of Equations
24043
24044@noindent
24045@cindex Systems of equations, numerical
24046The @kbd{a R} command can also solve systems of equations. In this
24047case, the equation should instead be a vector of equations, the
24048guess should instead be a vector of numbers (intervals are not
24049supported), and the variable should be a vector of variables. You
24050can omit the brackets while entering the list of variables. Each
24051equation must be differentiable by each variable for this mode to
24052work. The result will be a vector of two vectors: The variable
24053values that solved the system of equations, and the differences
24054between the sides of the equations with those variable values.
24055There must be the same number of equations as variables. Since
24056only plain numbers are allowed as guesses, the Hyperbolic flag has
24057no effect when solving a system of equations.
24058
24059It is also possible to minimize over many variables with @kbd{a N}
24060(or maximize with @kbd{a X}). Once again the variable name should
24061be replaced by a vector of variables, and the initial guess should
24062be an equal-sized vector of initial guesses. But, unlike the case of
24063multidimensional @kbd{a R}, the formula being minimized should
24064still be a single formula, @emph{not} a vector. Beware that
24065multidimensional minimization is currently @emph{very} slow.
24066
24067@node Curve Fitting, Summations, Numerical Solutions, Algebra
24068@section Curve Fitting
24069
24070@noindent
24071The @kbd{a F} command fits a set of data to a @dfn{model formula},
24072such as @expr{y = m x + b} where @expr{m} and @expr{b} are parameters
24073to be determined. For a typical set of measured data there will be
24074no single @expr{m} and @expr{b} that exactly fit the data; in this
24075case, Calc chooses values of the parameters that provide the closest
24076possible fit. The model formula can be entered in various ways after
24077the key sequence @kbd{a F} is pressed.
24078
24079If the letter @kbd{P} is pressed after @kbd{a F} but before the model
24080description is entered, the data as well as the model formula will be
24081plotted after the formula is determined. This will be indicated by a
24082``P'' in the minibuffer after the help message.
24083
24084@menu
24085* Linear Fits::
24086* Polynomial and Multilinear Fits::
24087* Error Estimates for Fits::
24088* Standard Nonlinear Models::
24089* Curve Fitting Details::
24090* Interpolation::
24091@end menu
24092
24093@node Linear Fits, Polynomial and Multilinear Fits, Curve Fitting, Curve Fitting
24094@subsection Linear Fits
24095
24096@noindent
24097@kindex a F
24098@pindex calc-curve-fit
24099@tindex fit
24100@cindex Linear regression
24101@cindex Least-squares fits
24102The @kbd{a F} (@code{calc-curve-fit}) [@code{fit}] command attempts
24103to fit a set of data (@expr{x} and @expr{y} vectors of numbers) to a
24104straight line, polynomial, or other function of @expr{x}. For the
24105moment we will consider only the case of fitting to a line, and we
24106will ignore the issue of whether or not the model was in fact a good
24107fit for the data.
24108
24109In a standard linear least-squares fit, we have a set of @expr{(x,y)}
24110data points that we wish to fit to the model @expr{y = m x + b}
24111by adjusting the parameters @expr{m} and @expr{b} to make the @expr{y}
24112values calculated from the formula be as close as possible to the actual
24113@expr{y} values in the data set. (In a polynomial fit, the model is
24114instead, say, @expr{y = a x^3 + b x^2 + c x + d}. In a multilinear fit,
24115we have data points of the form @expr{(x_1,x_2,x_3,y)} and our model is
24116@expr{y = a x_1 + b x_2 + c x_3 + d}. These will be discussed later.)
24117
24118In the model formula, variables like @expr{x} and @expr{x_2} are called
24119the @dfn{independent variables}, and @expr{y} is the @dfn{dependent
24120variable}. Variables like @expr{m}, @expr{a}, and @expr{b} are called
24121the @dfn{parameters} of the model.
24122
24123The @kbd{a F} command takes the data set to be fitted from the stack.
24124By default, it expects the data in the form of a matrix. For example,
24125for a linear or polynomial fit, this would be a
24126@texline @math{2\times N}
24127@infoline 2xN
24128matrix where the first row is a list of @expr{x} values and the second
24129row has the corresponding @expr{y} values. For the multilinear fit
24130shown above, the matrix would have four rows (@expr{x_1}, @expr{x_2},
24131@expr{x_3}, and @expr{y}, respectively).
24132
24133If you happen to have an
24134@texline @math{N\times2}
24135@infoline Nx2
24136matrix instead of a
24137@texline @math{2\times N}
24138@infoline 2xN
24139matrix, just press @kbd{v t} first to transpose the matrix.
24140
24141After you type @kbd{a F}, Calc prompts you to select a model. For a
24142linear fit, press the digit @kbd{1}.
24143
24144Calc then prompts for you to name the variables. By default it chooses
24145high letters like @expr{x} and @expr{y} for independent variables and
24146low letters like @expr{a} and @expr{b} for parameters. (The dependent
24147variable doesn't need a name.) The two kinds of variables are separated
24148by a semicolon. Since you generally care more about the names of the
24149independent variables than of the parameters, Calc also allows you to
24150name only those and let the parameters use default names.
24151
24152For example, suppose the data matrix
24153
24154@ifnottex
24155@example
24156@group
24157[ [ 1, 2, 3, 4, 5 ]
24158 [ 5, 7, 9, 11, 13 ] ]
24159@end group
24160@end example
24161@end ifnottex
24162@tex
24163\turnoffactive
24164\turnoffactive
24165\beforedisplay
24166$$ \pmatrix{ 1 & 2 & 3 & 4 & 5 \cr
24167 5 & 7 & 9 & 11 & 13 }
24168$$
24169\afterdisplay
24170@end tex
24171
24172@noindent
24173is on the stack and we wish to do a simple linear fit. Type
24174@kbd{a F}, then @kbd{1} for the model, then @key{RET} to use
24175the default names. The result will be the formula @expr{3. + 2. x}
24176on the stack. Calc has created the model expression @kbd{a + b x},
24177then found the optimal values of @expr{a} and @expr{b} to fit the
24178data. (In this case, it was able to find an exact fit.) Calc then
24179substituted those values for @expr{a} and @expr{b} in the model
24180formula.
24181
24182The @kbd{a F} command puts two entries in the trail. One is, as
24183always, a copy of the result that went to the stack; the other is
24184a vector of the actual parameter values, written as equations:
24185@expr{[a = 3, b = 2]}, in case you'd rather read them in a list
24186than pick them out of the formula. (You can type @kbd{t y}
24187to move this vector to the stack; see @ref{Trail Commands}.
24188
24189Specifying a different independent variable name will affect the
24190resulting formula: @kbd{a F 1 k @key{RET}} produces @kbd{3 + 2 k}.
24191Changing the parameter names (say, @kbd{a F 1 k;b,m @key{RET}}) will affect
24192the equations that go into the trail.
24193
24194@tex
24195\bigskip
24196@end tex
24197
24198To see what happens when the fit is not exact, we could change
24199the number 13 in the data matrix to 14 and try the fit again.
24200The result is:
24201
24202@example
242032.6 + 2.2 x
24204@end example
24205
24206Evaluating this formula, say with @kbd{v x 5 @key{RET} @key{TAB} V M $ @key{RET}}, shows
24207a reasonably close match to the y-values in the data.
24208
24209@example
24210[4.8, 7., 9.2, 11.4, 13.6]
24211@end example
24212
24213Since there is no line which passes through all the @var{n} data points,
24214Calc has chosen a line that best approximates the data points using
24215the method of least squares. The idea is to define the @dfn{chi-square}
24216error measure
24217
24218@ifnottex
24219@example
24220chi^2 = sum((y_i - (a + b x_i))^2, i, 1, N)
24221@end example
24222@end ifnottex
24223@tex
24224\turnoffactive
24225\beforedisplay
24226$$ \chi^2 = \sum_{i=1}^N (y_i - (a + b x_i))^2 $$
24227\afterdisplay
24228@end tex
24229
24230@noindent
24231which is clearly zero if @expr{a + b x} exactly fits all data points,
24232and increases as various @expr{a + b x_i} values fail to match the
24233corresponding @expr{y_i} values. There are several reasons why the
24234summand is squared, one of them being to ensure that
24235@texline @math{\chi^2 \ge 0}.
24236@infoline @expr{chi^2 >= 0}.
24237Least-squares fitting simply chooses the values of @expr{a} and @expr{b}
24238for which the error
24239@texline @math{\chi^2}
24240@infoline @expr{chi^2}
24241is as small as possible.
24242
24243Other kinds of models do the same thing but with a different model
24244formula in place of @expr{a + b x_i}.
24245
24246@tex
24247\bigskip
24248@end tex
24249
24250A numeric prefix argument causes the @kbd{a F} command to take the
24251data in some other form than one big matrix. A positive argument @var{n}
24252will take @var{N} items from the stack, corresponding to the @var{n} rows
24253of a data matrix. In the linear case, @var{n} must be 2 since there
24254is always one independent variable and one dependent variable.
24255
24256A prefix of zero or plain @kbd{C-u} is a compromise; Calc takes two
24257items from the stack, an @var{n}-row matrix of @expr{x} values, and a
24258vector of @expr{y} values. If there is only one independent variable,
24259the @expr{x} values can be either a one-row matrix or a plain vector,
24260in which case the @kbd{C-u} prefix is the same as a @w{@kbd{C-u 2}} prefix.
24261
24262@node Polynomial and Multilinear Fits, Error Estimates for Fits, Linear Fits, Curve Fitting
24263@subsection Polynomial and Multilinear Fits
24264
24265@noindent
24266To fit the data to higher-order polynomials, just type one of the
24267digits @kbd{2} through @kbd{9} when prompted for a model. For example,
24268we could fit the original data matrix from the previous section
24269(with 13, not 14) to a parabola instead of a line by typing
24270@kbd{a F 2 @key{RET}}.
24271
24272@example
242732.00000000001 x - 1.5e-12 x^2 + 2.99999999999
24274@end example
24275
24276Note that since the constant and linear terms are enough to fit the
24277data exactly, it's no surprise that Calc chose a tiny contribution
24278for @expr{x^2}. (The fact that it's not exactly zero is due only
24279to roundoff error. Since our data are exact integers, we could get
24280an exact answer by typing @kbd{m f} first to get Fraction mode.
24281Then the @expr{x^2} term would vanish altogether. Usually, though,
24282the data being fitted will be approximate floats so Fraction mode
24283won't help.)
24284
24285Doing the @kbd{a F 2} fit on the data set with 14 instead of 13
24286gives a much larger @expr{x^2} contribution, as Calc bends the
24287line slightly to improve the fit.
24288
24289@example
242900.142857142855 x^2 + 1.34285714287 x + 3.59999999998
24291@end example
24292
24293An important result from the theory of polynomial fitting is that it
24294is always possible to fit @var{n} data points exactly using a polynomial
24295of degree @mathit{@var{n}-1}, sometimes called an @dfn{interpolating polynomial}.
24296Using the modified (14) data matrix, a model number of 4 gives
24297a polynomial that exactly matches all five data points:
24298
24299@example
243000.04167 x^4 - 0.4167 x^3 + 1.458 x^2 - 0.08333 x + 4.
24301@end example
24302
24303The actual coefficients we get with a precision of 12, like
24304@expr{0.0416666663588}, clearly suffer from loss of precision.
24305It is a good idea to increase the working precision to several
24306digits beyond what you need when you do a fitting operation.
24307Or, if your data are exact, use Fraction mode to get exact
24308results.
24309
24310You can type @kbd{i} instead of a digit at the model prompt to fit
24311the data exactly to a polynomial. This just counts the number of
24312columns of the data matrix to choose the degree of the polynomial
24313automatically.
24314
24315Fitting data ``exactly'' to high-degree polynomials is not always
24316a good idea, though. High-degree polynomials have a tendency to
24317wiggle uncontrollably in between the fitting data points. Also,
24318if the exact-fit polynomial is going to be used to interpolate or
24319extrapolate the data, it is numerically better to use the @kbd{a p}
24320command described below. @xref{Interpolation}.
24321
24322@tex
24323\bigskip
24324@end tex
24325
24326Another generalization of the linear model is to assume the
24327@expr{y} values are a sum of linear contributions from several
24328@expr{x} values. This is a @dfn{multilinear} fit, and it is also
24329selected by the @kbd{1} digit key. (Calc decides whether the fit
24330is linear or multilinear by counting the rows in the data matrix.)
24331
24332Given the data matrix,
24333
24334@example
24335@group
24336[ [ 1, 2, 3, 4, 5 ]
24337 [ 7, 2, 3, 5, 2 ]
24338 [ 14.5, 15, 18.5, 22.5, 24 ] ]
24339@end group
24340@end example
24341
24342@noindent
24343the command @kbd{a F 1 @key{RET}} will call the first row @expr{x} and the
24344second row @expr{y}, and will fit the values in the third row to the
24345model @expr{a + b x + c y}.
24346
24347@example
243488. + 3. x + 0.5 y
24349@end example
24350
24351Calc can do multilinear fits with any number of independent variables
24352(i.e., with any number of data rows).
24353
24354@tex
24355\bigskip
24356@end tex
24357
24358Yet another variation is @dfn{homogeneous} linear models, in which
24359the constant term is known to be zero. In the linear case, this
24360means the model formula is simply @expr{a x}; in the multilinear
24361case, the model might be @expr{a x + b y + c z}; and in the polynomial
24362case, the model could be @expr{a x + b x^2 + c x^3}. You can get
24363a homogeneous linear or multilinear model by pressing the letter
24364@kbd{h} followed by a regular model key, like @kbd{1} or @kbd{2}.
24365This will be indicated by an ``h'' in the minibuffer after the help
24366message.
24367
24368It is certainly possible to have other constrained linear models,
24369like @expr{2.3 + a x} or @expr{a - 4 x}. While there is no single
24370key to select models like these, a later section shows how to enter
24371any desired model by hand. In the first case, for example, you
24372would enter @kbd{a F ' 2.3 + a x}.
24373
24374Another class of models that will work but must be entered by hand
24375are multinomial fits, e.g., @expr{a + b x + c y + d x^2 + e y^2 + f x y}.
24376
24377@node Error Estimates for Fits, Standard Nonlinear Models, Polynomial and Multilinear Fits, Curve Fitting
24378@subsection Error Estimates for Fits
24379
24380@noindent
24381@kindex H a F
24382@tindex efit
24383With the Hyperbolic flag, @kbd{H a F} [@code{efit}] performs the same
24384fitting operation as @kbd{a F}, but reports the coefficients as error
24385forms instead of plain numbers. Fitting our two data matrices (first
24386with 13, then with 14) to a line with @kbd{H a F} gives the results,
24387
24388@example
243893. + 2. x
243902.6 +/- 0.382970843103 + 2.2 +/- 0.115470053838 x
24391@end example
24392
24393In the first case the estimated errors are zero because the linear
24394fit is perfect. In the second case, the errors are nonzero but
24395moderately small, because the data are still very close to linear.
24396
24397It is also possible for the @emph{input} to a fitting operation to
24398contain error forms. The data values must either all include errors
24399or all be plain numbers. Error forms can go anywhere but generally
24400go on the numbers in the last row of the data matrix. If the last
24401row contains error forms
24402@texline `@var{y_i}@w{ @tfn{+/-} }@math{\sigma_i}',
24403@infoline `@var{y_i}@w{ @tfn{+/-} }@var{sigma_i}',
24404then the
24405@texline @math{\chi^2}
24406@infoline @expr{chi^2}
24407statistic is now,
24408
24409@ifnottex
24410@example
24411chi^2 = sum(((y_i - (a + b x_i)) / sigma_i)^2, i, 1, N)
24412@end example
24413@end ifnottex
24414@tex
24415\turnoffactive
24416\beforedisplay
24417$$ \chi^2 = \sum_{i=1}^N \left(y_i - (a + b x_i) \over \sigma_i\right)^2 $$
24418\afterdisplay
24419@end tex
24420
24421@noindent
24422so that data points with larger error estimates contribute less to
24423the fitting operation.
24424
24425If there are error forms on other rows of the data matrix, all the
24426errors for a given data point are combined; the square root of the
24427sum of the squares of the errors forms the
24428@texline @math{\sigma_i}
24429@infoline @expr{sigma_i}
24430used for the data point.
24431
24432Both @kbd{a F} and @kbd{H a F} can accept error forms in the input
24433matrix, although if you are concerned about error analysis you will
24434probably use @kbd{H a F} so that the output also contains error
24435estimates.
24436
24437If the input contains error forms but all the
24438@texline @math{\sigma_i}
24439@infoline @expr{sigma_i}
24440values are the same, it is easy to see that the resulting fitted model
24441will be the same as if the input did not have error forms at all
24442@texline (@math{\chi^2}
24443@infoline (@expr{chi^2}
24444is simply scaled uniformly by
24445@texline @math{1 / \sigma^2},
24446@infoline @expr{1 / sigma^2},
24447which doesn't affect where it has a minimum). But there @emph{will} be
24448a difference in the estimated errors of the coefficients reported by
24449@kbd{H a F}.
24450
24451Consult any text on statistical modeling of data for a discussion
24452of where these error estimates come from and how they should be
24453interpreted.
24454
24455@tex
24456\bigskip
24457@end tex
24458
24459@kindex I a F
24460@tindex xfit
24461With the Inverse flag, @kbd{I a F} [@code{xfit}] produces even more
24462information. The result is a vector of six items:
24463
24464@enumerate
24465@item
24466The model formula with error forms for its coefficients or
24467parameters. This is the result that @kbd{H a F} would have
24468produced.
24469
24470@item
24471A vector of ``raw'' parameter values for the model. These are the
24472polynomial coefficients or other parameters as plain numbers, in the
24473same order as the parameters appeared in the final prompt of the
24474@kbd{I a F} command. For polynomials of degree @expr{d}, this vector
24475will have length @expr{M = d+1} with the constant term first.
24476
24477@item
24478The covariance matrix @expr{C} computed from the fit. This is
24479an @var{m}x@var{m} symmetric matrix; the diagonal elements
24480@texline @math{C_{jj}}
24481@infoline @expr{C_j_j}
24482are the variances
24483@texline @math{\sigma_j^2}
24484@infoline @expr{sigma_j^2}
24485of the parameters. The other elements are covariances
24486@texline @math{\sigma_{ij}^2}
24487@infoline @expr{sigma_i_j^2}
24488that describe the correlation between pairs of parameters. (A related
24489set of numbers, the @dfn{linear correlation coefficients}
24490@texline @math{r_{ij}},
24491@infoline @expr{r_i_j},
24492are defined as
24493@texline @math{\sigma_{ij}^2 / \sigma_i \, \sigma_j}.)
24494@infoline @expr{sigma_i_j^2 / sigma_i sigma_j}.)
24495
24496@item
24497A vector of @expr{M} ``parameter filter'' functions whose
24498meanings are described below. If no filters are necessary this
24499will instead be an empty vector; this is always the case for the
24500polynomial and multilinear fits described so far.
24501
24502@item
24503The value of
24504@texline @math{\chi^2}
24505@infoline @expr{chi^2}
24506for the fit, calculated by the formulas shown above. This gives a
24507measure of the quality of the fit; statisticians consider
24508@texline @math{\chi^2 \approx N - M}
24509@infoline @expr{chi^2 = N - M}
24510to indicate a moderately good fit (where again @expr{N} is the number of
24511data points and @expr{M} is the number of parameters).
24512
24513@item
24514A measure of goodness of fit expressed as a probability @expr{Q}.
24515This is computed from the @code{utpc} probability distribution
24516function using
24517@texline @math{\chi^2}
24518@infoline @expr{chi^2}
24519with @expr{N - M} degrees of freedom. A
24520value of 0.5 implies a good fit; some texts recommend that often
24521@expr{Q = 0.1} or even 0.001 can signify an acceptable fit. In
24522particular,
24523@texline @math{\chi^2}
24524@infoline @expr{chi^2}
24525statistics assume the errors in your inputs
24526follow a normal (Gaussian) distribution; if they don't, you may
24527have to accept smaller values of @expr{Q}.
24528
24529The @expr{Q} value is computed only if the input included error
24530estimates. Otherwise, Calc will report the symbol @code{nan}
24531for @expr{Q}. The reason is that in this case the
24532@texline @math{\chi^2}
24533@infoline @expr{chi^2}
24534value has effectively been used to estimate the original errors
24535in the input, and thus there is no redundant information left
24536over to use for a confidence test.
24537@end enumerate
24538
24539@node Standard Nonlinear Models, Curve Fitting Details, Error Estimates for Fits, Curve Fitting
24540@subsection Standard Nonlinear Models
24541
24542@noindent
24543The @kbd{a F} command also accepts other kinds of models besides
24544lines and polynomials. Some common models have quick single-key
24545abbreviations; others must be entered by hand as algebraic formulas.
24546
24547Here is a complete list of the standard models recognized by @kbd{a F}:
24548
24549@table @kbd
24550@item 1
24551Linear or multilinear. @mathit{a + b x + c y + d z}.
24552@item 2-9
24553Polynomials. @mathit{a + b x + c x^2 + d x^3}.
24554@item e
24555Exponential. @mathit{a} @tfn{exp}@mathit{(b x)} @tfn{exp}@mathit{(c y)}.
24556@item E
24557Base-10 exponential. @mathit{a} @tfn{10^}@mathit{(b x)} @tfn{10^}@mathit{(c y)}.
24558@item x
24559Exponential (alternate notation). @tfn{exp}@mathit{(a + b x + c y)}.
24560@item X
24561Base-10 exponential (alternate). @tfn{10^}@mathit{(a + b x + c y)}.
24562@item l
24563Logarithmic. @mathit{a + b} @tfn{ln}@mathit{(x) + c} @tfn{ln}@mathit{(y)}.
24564@item L
24565Base-10 logarithmic. @mathit{a + b} @tfn{log10}@mathit{(x) + c} @tfn{log10}@mathit{(y)}.
24566@item ^
24567General exponential. @mathit{a b^x c^y}.
24568@item p
24569Power law. @mathit{a x^b y^c}.
24570@item q
24571Quadratic. @mathit{a + b (x-c)^2 + d (x-e)^2}.
24572@item g
24573Gaussian.
24574@texline @math{{a \over b \sqrt{2 \pi}} \exp\left( -{1 \over 2} \left( x - c \over b \right)^2 \right)}.
24575@infoline @mathit{(a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)}.
24576@item s
24577Logistic @emph{s} curve.
24578@texline @math{a/(1+e^{b(x-c)})}.
24579@infoline @mathit{a/(1 + exp(b (x - c)))}.
24580@item b
24581Logistic bell curve.
24582@texline @math{ae^{b(x-c)}/(1+e^{b(x-c)})^2}.
24583@infoline @mathit{a exp(b (x - c))/(1 + exp(b (x - c)))^2}.
24584@item o
24585Hubbert linearization.
24586@texline @math{{y \over x} = a(1-x/b)}.
24587@infoline @mathit{(y/x) = a (1 - x/b)}.
24588@end table
24589
24590All of these models are used in the usual way; just press the appropriate
24591letter at the model prompt, and choose variable names if you wish. The
24592result will be a formula as shown in the above table, with the best-fit
24593values of the parameters substituted. (You may find it easier to read
24594the parameter values from the vector that is placed in the trail.)
24595
24596All models except Gaussian, logistics, Hubbert and polynomials can
24597generalize as shown to any number of independent variables. Also, all
24598the built-in models except for the logistic and Hubbert curves have an
24599additive or multiplicative parameter shown as @expr{a} in the above table
24600which can be replaced by zero or one, as appropriate, by typing @kbd{h}
24601before the model key.
24602
24603Note that many of these models are essentially equivalent, but express
24604the parameters slightly differently. For example, @expr{a b^x} and
24605the other two exponential models are all algebraic rearrangements of
24606each other. Also, the ``quadratic'' model is just a degree-2 polynomial
24607with the parameters expressed differently. Use whichever form best
24608matches the problem.
24609
24610The HP-28/48 calculators support four different models for curve
24611fitting, called @code{LIN}, @code{LOG}, @code{EXP}, and @code{PWR}.
24612These correspond to Calc models @samp{a + b x}, @samp{a + b ln(x)},
24613@samp{a exp(b x)}, and @samp{a x^b}, respectively. In each case,
24614@expr{a} is what the HP-48 identifies as the ``intercept,'' and
24615@expr{b} is what it calls the ``slope.''
24616
24617@tex
24618\bigskip
24619@end tex
24620
24621If the model you want doesn't appear on this list, press @kbd{'}
24622(the apostrophe key) at the model prompt to enter any algebraic
24623formula, such as @kbd{m x - b}, as the model. (Not all models
24624will work, though---see the next section for details.)
24625
24626The model can also be an equation like @expr{y = m x + b}.
24627In this case, Calc thinks of all the rows of the data matrix on
24628equal terms; this model effectively has two parameters
24629(@expr{m} and @expr{b}) and two independent variables (@expr{x}
24630and @expr{y}), with no ``dependent'' variables. Model equations
24631do not need to take this @expr{y =} form. For example, the
24632implicit line equation @expr{a x + b y = 1} works fine as a
24633model.
24634
24635When you enter a model, Calc makes an alphabetical list of all
24636the variables that appear in the model. These are used for the
24637default parameters, independent variables, and dependent variable
24638(in that order). If you enter a plain formula (not an equation),
24639Calc assumes the dependent variable does not appear in the formula
24640and thus does not need a name.
24641
24642For example, if the model formula has the variables @expr{a,mu,sigma,t,x},
24643and the data matrix has three rows (meaning two independent variables),
24644Calc will use @expr{a,mu,sigma} as the default parameters, and the
24645data rows will be named @expr{t} and @expr{x}, respectively. If you
24646enter an equation instead of a plain formula, Calc will use @expr{a,mu}
24647as the parameters, and @expr{sigma,t,x} as the three independent
24648variables.
24649
24650You can, of course, override these choices by entering something
24651different at the prompt. If you leave some variables out of the list,
24652those variables must have stored values and those stored values will
24653be used as constants in the model. (Stored values for the parameters
24654and independent variables are ignored by the @kbd{a F} command.)
24655If you list only independent variables, all the remaining variables
24656in the model formula will become parameters.
24657
24658If there are @kbd{$} signs in the model you type, they will stand
24659for parameters and all other variables (in alphabetical order)
24660will be independent. Use @kbd{$} for one parameter, @kbd{$$} for
24661another, and so on. Thus @kbd{$ x + $$} is another way to describe
24662a linear model.
24663
24664If you type a @kbd{$} instead of @kbd{'} at the model prompt itself,
24665Calc will take the model formula from the stack. (The data must then
24666appear at the second stack level.) The same conventions are used to
24667choose which variables in the formula are independent by default and
24668which are parameters.
24669
24670Models taken from the stack can also be expressed as vectors of
24671two or three elements, @expr{[@var{model}, @var{vars}]} or
24672@expr{[@var{model}, @var{vars}, @var{params}]}. Each of @var{vars}
24673and @var{params} may be either a variable or a vector of variables.
24674(If @var{params} is omitted, all variables in @var{model} except
24675those listed as @var{vars} are parameters.)
24676
24677When you enter a model manually with @kbd{'}, Calc puts a 3-vector
24678describing the model in the trail so you can get it back if you wish.
24679
24680@tex
24681\bigskip
24682@end tex
24683
24684@vindex Model1
24685@vindex Model2
24686Finally, you can store a model in one of the Calc variables
24687@code{Model1} or @code{Model2}, then use this model by typing
24688@kbd{a F u} or @kbd{a F U} (respectively). The value stored in
24689the variable can be any of the formats that @kbd{a F $} would
24690accept for a model on the stack.
24691
24692@tex
24693\bigskip
24694@end tex
24695
24696Calc uses the principal values of inverse functions like @code{ln}
24697and @code{arcsin} when doing fits. For example, when you enter
24698the model @samp{y = sin(a t + b)} Calc actually uses the easier
24699form @samp{arcsin(y) = a t + b}. The @code{arcsin} function always
24700returns results in the range from @mathit{-90} to 90 degrees (or the
24701equivalent range in radians). Suppose you had data that you
24702believed to represent roughly three oscillations of a sine wave,
24703so that the argument of the sine might go from zero to
24704@texline @math{3\times360}
24705@infoline @mathit{3*360}
24706degrees.
24707The above model would appear to be a good way to determine the
24708true frequency and phase of the sine wave, but in practice it
24709would fail utterly. The righthand side of the actual model
24710@samp{arcsin(y) = a t + b} will grow smoothly with @expr{t}, but
24711the lefthand side will bounce back and forth between @mathit{-90} and 90.
24712No values of @expr{a} and @expr{b} can make the two sides match,
24713even approximately.
24714
24715There is no good solution to this problem at present. You could
24716restrict your data to small enough ranges so that the above problem
24717doesn't occur (i.e., not straddling any peaks in the sine wave).
24718Or, in this case, you could use a totally different method such as
24719Fourier analysis, which is beyond the scope of the @kbd{a F} command.
24720(Unfortunately, Calc does not currently have any facilities for
24721taking Fourier and related transforms.)
24722
24723@node Curve Fitting Details, Interpolation, Standard Nonlinear Models, Curve Fitting
24724@subsection Curve Fitting Details
24725
24726@noindent
24727Calc's internal least-squares fitter can only handle multilinear
24728models. More precisely, it can handle any model of the form
24729@expr{a f(x,y,z) + b g(x,y,z) + c h(x,y,z)}, where @expr{a,b,c}
24730are the parameters and @expr{x,y,z} are the independent variables
24731(of course there can be any number of each, not just three).
24732
24733In a simple multilinear or polynomial fit, it is easy to see how
24734to convert the model into this form. For example, if the model
24735is @expr{a + b x + c x^2}, then @expr{f(x) = 1}, @expr{g(x) = x},
24736and @expr{h(x) = x^2} are suitable functions.
24737
24738For most other models, Calc uses a variety of algebraic manipulations
24739to try to put the problem into the form
24740
24741@smallexample
24742Y(x,y,z) = A(a,b,c) F(x,y,z) + B(a,b,c) G(x,y,z) + C(a,b,c) H(x,y,z)
24743@end smallexample
24744
24745@noindent
24746where @expr{Y,A,B,C,F,G,H} are arbitrary functions. It computes
24747@expr{Y}, @expr{F}, @expr{G}, and @expr{H} for all the data points,
24748does a standard linear fit to find the values of @expr{A}, @expr{B},
24749and @expr{C}, then uses the equation solver to solve for @expr{a,b,c}
24750in terms of @expr{A,B,C}.
24751
24752A remarkable number of models can be cast into this general form.
24753We'll look at two examples here to see how it works. The power-law
24754model @expr{y = a x^b} with two independent variables and two parameters
24755can be rewritten as follows:
24756
24757@example
24758y = a x^b
24759y = a exp(b ln(x))
24760y = exp(ln(a) + b ln(x))
24761ln(y) = ln(a) + b ln(x)
24762@end example
24763
24764@noindent
24765which matches the desired form with
24766@texline @math{Y = \ln(y)},
24767@infoline @expr{Y = ln(y)},
24768@texline @math{A = \ln(a)},
24769@infoline @expr{A = ln(a)},
24770@expr{F = 1}, @expr{B = b}, and
24771@texline @math{G = \ln(x)}.
24772@infoline @expr{G = ln(x)}.
24773Calc thus computes the logarithms of your @expr{y} and @expr{x} values,
24774does a linear fit for @expr{A} and @expr{B}, then solves to get
24775@texline @math{a = \exp(A)}
24776@infoline @expr{a = exp(A)}
24777and @expr{b = B}.
24778
24779Another interesting example is the ``quadratic'' model, which can
24780be handled by expanding according to the distributive law.
24781
24782@example
24783y = a + b*(x - c)^2
24784y = a + b c^2 - 2 b c x + b x^2
24785@end example
24786
24787@noindent
24788which matches with @expr{Y = y}, @expr{A = a + b c^2}, @expr{F = 1},
24789@expr{B = -2 b c}, @expr{G = x} (the @mathit{-2} factor could just as easily
24790have been put into @expr{G} instead of @expr{B}), @expr{C = b}, and
24791@expr{H = x^2}.
24792
24793The Gaussian model looks quite complicated, but a closer examination
24794shows that it's actually similar to the quadratic model but with an
24795exponential that can be brought to the top and moved into @expr{Y}.
24796
24797The logistic models cannot be put into general linear form. For these
24798models, and the Hubbert linearization, Calc computes a rough
24799approximation for the parameters, then uses the Levenberg-Marquardt
24800iterative method to refine the approximations.
24801
24802Another model that cannot be put into general linear
24803form is a Gaussian with a constant background added on, i.e.,
24804@expr{d} + the regular Gaussian formula. If you have a model like
24805this, your best bet is to replace enough of your parameters with
24806constants to make the model linearizable, then adjust the constants
24807manually by doing a series of fits. You can compare the fits by
24808graphing them, by examining the goodness-of-fit measures returned by
24809@kbd{I a F}, or by some other method suitable to your application.
24810Note that some models can be linearized in several ways. The
24811Gaussian-plus-@var{d} model can be linearized by setting @expr{d}
24812(the background) to a constant, or by setting @expr{b} (the standard
24813deviation) and @expr{c} (the mean) to constants.
24814
24815To fit a model with constants substituted for some parameters, just
24816store suitable values in those parameter variables, then omit them
24817from the list of parameters when you answer the variables prompt.
24818
24819@tex
24820\bigskip
24821@end tex
24822
24823A last desperate step would be to use the general-purpose
24824@code{minimize} function rather than @code{fit}. After all, both
24825functions solve the problem of minimizing an expression (the
24826@texline @math{\chi^2}
24827@infoline @expr{chi^2}
24828sum) by adjusting certain parameters in the expression. The @kbd{a F}
24829command is able to use a vastly more efficient algorithm due to its
24830special knowledge about linear chi-square sums, but the @kbd{a N}
24831command can do the same thing by brute force.
24832
24833A compromise would be to pick out a few parameters without which the
24834fit is linearizable, and use @code{minimize} on a call to @code{fit}
24835which efficiently takes care of the rest of the parameters. The thing
24836to be minimized would be the value of
24837@texline @math{\chi^2}
24838@infoline @expr{chi^2}
24839returned as the fifth result of the @code{xfit} function:
24840
24841@smallexample
24842minimize(xfit(gaus(a,b,c,d,x), x, [a,b,c], data)_5, d, guess)
24843@end smallexample
24844
24845@noindent
24846where @code{gaus} represents the Gaussian model with background,
24847@code{data} represents the data matrix, and @code{guess} represents
24848the initial guess for @expr{d} that @code{minimize} requires.
24849This operation will only be, shall we say, extraordinarily slow
24850rather than astronomically slow (as would be the case if @code{minimize}
24851were used by itself to solve the problem).
24852
24853@tex
24854\bigskip
24855@end tex
24856
24857The @kbd{I a F} [@code{xfit}] command is somewhat trickier when
24858nonlinear models are used. The second item in the result is the
24859vector of ``raw'' parameters @expr{A}, @expr{B}, @expr{C}. The
24860covariance matrix is written in terms of those raw parameters.
24861The fifth item is a vector of @dfn{filter} expressions. This
24862is the empty vector @samp{[]} if the raw parameters were the same
24863as the requested parameters, i.e., if @expr{A = a}, @expr{B = b},
24864and so on (which is always true if the model is already linear
24865in the parameters as written, e.g., for polynomial fits). If the
24866parameters had to be rearranged, the fifth item is instead a vector
24867of one formula per parameter in the original model. The raw
24868parameters are expressed in these ``filter'' formulas as
24869@samp{fitdummy(1)} for @expr{A}, @samp{fitdummy(2)} for @expr{B},
24870and so on.
24871
24872When Calc needs to modify the model to return the result, it replaces
24873@samp{fitdummy(1)} in all the filters with the first item in the raw
24874parameters list, and so on for the other raw parameters, then
24875evaluates the resulting filter formulas to get the actual parameter
24876values to be substituted into the original model. In the case of
24877@kbd{H a F} and @kbd{I a F} where the parameters must be error forms,
24878Calc uses the square roots of the diagonal entries of the covariance
24879matrix as error values for the raw parameters, then lets Calc's
24880standard error-form arithmetic take it from there.
24881
24882If you use @kbd{I a F} with a nonlinear model, be sure to remember
24883that the covariance matrix is in terms of the raw parameters,
24884@emph{not} the actual requested parameters. It's up to you to
24885figure out how to interpret the covariances in the presence of
24886nontrivial filter functions.
24887
24888Things are also complicated when the input contains error forms.
24889Suppose there are three independent and dependent variables, @expr{x},
24890@expr{y}, and @expr{z}, one or more of which are error forms in the
24891data. Calc combines all the error values by taking the square root
24892of the sum of the squares of the errors. It then changes @expr{x}
24893and @expr{y} to be plain numbers, and makes @expr{z} into an error
24894form with this combined error. The @expr{Y(x,y,z)} part of the
24895linearized model is evaluated, and the result should be an error
24896form. The error part of that result is used for
24897@texline @math{\sigma_i}
24898@infoline @expr{sigma_i}
24899for the data point. If for some reason @expr{Y(x,y,z)} does not return
24900an error form, the combined error from @expr{z} is used directly for
24901@texline @math{\sigma_i}.
24902@infoline @expr{sigma_i}.
24903Finally, @expr{z} is also stripped of its error
24904for use in computing @expr{F(x,y,z)}, @expr{G(x,y,z)} and so on;
24905the righthand side of the linearized model is computed in regular
24906arithmetic with no error forms.
24907
24908(While these rules may seem complicated, they are designed to do
24909the most reasonable thing in the typical case that @expr{Y(x,y,z)}
24910depends only on the dependent variable @expr{z}, and in fact is
24911often simply equal to @expr{z}. For common cases like polynomials
24912and multilinear models, the combined error is simply used as the
24913@texline @math{\sigma}
24914@infoline @expr{sigma}
24915for the data point with no further ado.)
24916
24917@tex
24918\bigskip
24919@end tex
24920
24921@vindex FitRules
24922It may be the case that the model you wish to use is linearizable,
24923but Calc's built-in rules are unable to figure it out. Calc uses
24924its algebraic rewrite mechanism to linearize a model. The rewrite
24925rules are kept in the variable @code{FitRules}. You can edit this
24926variable using the @kbd{s e FitRules} command; in fact, there is
24927a special @kbd{s F} command just for editing @code{FitRules}.
24928@xref{Operations on Variables}.
24929
24930@xref{Rewrite Rules}, for a discussion of rewrite rules.
24931
24932@ignore
24933@starindex
24934@end ignore
24935@tindex fitvar
24936@ignore
24937@starindex
24938@end ignore
24939@ignore
24940@mindex @idots
24941@end ignore
24942@tindex fitparam
24943@ignore
24944@starindex
24945@end ignore
24946@ignore
24947@mindex @null
24948@end ignore
24949@tindex fitmodel
24950@ignore
24951@starindex
24952@end ignore
24953@ignore
24954@mindex @null
24955@end ignore
24956@tindex fitsystem
24957@ignore
24958@starindex
24959@end ignore
24960@ignore
24961@mindex @null
24962@end ignore
24963@tindex fitdummy
24964Calc uses @code{FitRules} as follows. First, it converts the model
24965to an equation if necessary and encloses the model equation in a
24966call to the function @code{fitmodel} (which is not actually a defined
24967function in Calc; it is only used as a placeholder by the rewrite rules).
24968Parameter variables are renamed to function calls @samp{fitparam(1)},
24969@samp{fitparam(2)}, and so on, and independent variables are renamed
24970to @samp{fitvar(1)}, @samp{fitvar(2)}, etc. The dependent variable
24971is the highest-numbered @code{fitvar}. For example, the power law
24972model @expr{a x^b} is converted to @expr{y = a x^b}, then to
24973
24974@smallexample
24975@group
24976fitmodel(fitvar(2) = fitparam(1) fitvar(1)^fitparam(2))
24977@end group
24978@end smallexample
24979
24980Calc then applies the rewrites as if by @samp{C-u 0 a r FitRules}.
24981(The zero prefix means that rewriting should continue until no further
24982changes are possible.)
24983
24984When rewriting is complete, the @code{fitmodel} call should have
24985been replaced by a @code{fitsystem} call that looks like this:
24986
24987@example
24988fitsystem(@var{Y}, @var{FGH}, @var{abc})
24989@end example
24990
24991@noindent
24992where @var{Y} is a formula that describes the function @expr{Y(x,y,z)},
24993@var{FGH} is the vector of formulas @expr{[F(x,y,z), G(x,y,z), H(x,y,z)]},
24994and @var{abc} is the vector of parameter filters which refer to the
24995raw parameters as @samp{fitdummy(1)} for @expr{A}, @samp{fitdummy(2)}
24996for @expr{B}, etc. While the number of raw parameters (the length of
24997the @var{FGH} vector) is usually the same as the number of original
24998parameters (the length of the @var{abc} vector), this is not required.
24999
25000The power law model eventually boils down to
25001
25002@smallexample
25003@group
25004fitsystem(ln(fitvar(2)),
25005 [1, ln(fitvar(1))],
25006 [exp(fitdummy(1)), fitdummy(2)])
25007@end group
25008@end smallexample
25009
25010The actual implementation of @code{FitRules} is complicated; it
25011proceeds in four phases. First, common rearrangements are done
25012to try to bring linear terms together and to isolate functions like
25013@code{exp} and @code{ln} either all the way ``out'' (so that they
25014can be put into @var{Y}) or all the way ``in'' (so that they can
25015be put into @var{abc} or @var{FGH}). In particular, all
25016non-constant powers are converted to logs-and-exponentials form,
25017and the distributive law is used to expand products of sums.
25018Quotients are rewritten to use the @samp{fitinv} function, where
25019@samp{fitinv(x)} represents @expr{1/x} while the @code{FitRules}
25020are operating. (The use of @code{fitinv} makes recognition of
25021linear-looking forms easier.) If you modify @code{FitRules}, you
25022will probably only need to modify the rules for this phase.
25023
25024Phase two, whose rules can actually also apply during phases one
25025and three, first rewrites @code{fitmodel} to a two-argument
25026form @samp{fitmodel(@var{Y}, @var{model})}, where @var{Y} is
25027initially zero and @var{model} has been changed from @expr{a=b}
25028to @expr{a-b} form. It then tries to peel off invertible functions
25029from the outside of @var{model} and put them into @var{Y} instead,
25030calling the equation solver to invert the functions. Finally, when
25031this is no longer possible, the @code{fitmodel} is changed to a
25032four-argument @code{fitsystem}, where the fourth argument is
25033@var{model} and the @var{FGH} and @var{abc} vectors are initially
25034empty. (The last vector is really @var{ABC}, corresponding to
25035raw parameters, for now.)
25036
25037Phase three converts a sum of items in the @var{model} to a sum
25038of @samp{fitpart(@var{a}, @var{b}, @var{c})} terms which represent
25039terms @samp{@var{a}*@var{b}*@var{c}} of the sum, where @var{a}
25040is all factors that do not involve any variables, @var{b} is all
25041factors that involve only parameters, and @var{c} is the factors
25042that involve only independent variables. (If this decomposition
25043is not possible, the rule set will not complete and Calc will
25044complain that the model is too complex.) Then @code{fitpart}s
25045with equal @var{b} or @var{c} components are merged back together
25046using the distributive law in order to minimize the number of
25047raw parameters needed.
25048
25049Phase four moves the @code{fitpart} terms into the @var{FGH} and
25050@var{ABC} vectors. Also, some of the algebraic expansions that
25051were done in phase 1 are undone now to make the formulas more
25052computationally efficient. Finally, it calls the solver one more
25053time to convert the @var{ABC} vector to an @var{abc} vector, and
25054removes the fourth @var{model} argument (which by now will be zero)
25055to obtain the three-argument @code{fitsystem} that the linear
25056least-squares solver wants to see.
25057
25058@ignore
25059@starindex
25060@end ignore
25061@ignore
25062@mindex hasfit@idots
25063@end ignore
25064@tindex hasfitparams
25065@ignore
25066@starindex
25067@end ignore
25068@ignore
25069@mindex @null
25070@end ignore
25071@tindex hasfitvars
25072Two functions which are useful in connection with @code{FitRules}
25073are @samp{hasfitparams(x)} and @samp{hasfitvars(x)}, which check
25074whether @expr{x} refers to any parameters or independent variables,
25075respectively. Specifically, these functions return ``true'' if the
25076argument contains any @code{fitparam} (or @code{fitvar}) function
25077calls, and ``false'' otherwise. (Recall that ``true'' means a
25078nonzero number, and ``false'' means zero. The actual nonzero number
25079returned is the largest @var{n} from all the @samp{fitparam(@var{n})}s
25080or @samp{fitvar(@var{n})}s, respectively, that appear in the formula.)
25081
25082@tex
25083\bigskip
25084@end tex
25085
25086The @code{fit} function in algebraic notation normally takes four
25087arguments, @samp{fit(@var{model}, @var{vars}, @var{params}, @var{data})},
25088where @var{model} is the model formula as it would be typed after
25089@kbd{a F '}, @var{vars} is the independent variable or a vector of
25090independent variables, @var{params} likewise gives the parameter(s),
25091and @var{data} is the data matrix. Note that the length of @var{vars}
25092must be equal to the number of rows in @var{data} if @var{model} is
25093an equation, or one less than the number of rows if @var{model} is
25094a plain formula. (Actually, a name for the dependent variable is
25095allowed but will be ignored in the plain-formula case.)
25096
25097If @var{params} is omitted, the parameters are all variables in
25098@var{model} except those that appear in @var{vars}. If @var{vars}
25099is also omitted, Calc sorts all the variables that appear in
25100@var{model} alphabetically and uses the higher ones for @var{vars}
25101and the lower ones for @var{params}.
25102
25103Alternatively, @samp{fit(@var{modelvec}, @var{data})} is allowed
25104where @var{modelvec} is a 2- or 3-vector describing the model
25105and variables, as discussed previously.
25106
25107If Calc is unable to do the fit, the @code{fit} function is left
25108in symbolic form, ordinarily with an explanatory message. The
25109message will be ``Model expression is too complex'' if the
25110linearizer was unable to put the model into the required form.
25111
25112The @code{efit} (corresponding to @kbd{H a F}) and @code{xfit}
25113(for @kbd{I a F}) functions are completely analogous.
25114
25115@node Interpolation, , Curve Fitting Details, Curve Fitting
25116@subsection Polynomial Interpolation
25117
25118@kindex a p
25119@pindex calc-poly-interp
25120@tindex polint
25121The @kbd{a p} (@code{calc-poly-interp}) [@code{polint}] command does
25122a polynomial interpolation at a particular @expr{x} value. It takes
25123two arguments from the stack: A data matrix of the sort used by
25124@kbd{a F}, and a single number which represents the desired @expr{x}
25125value. Calc effectively does an exact polynomial fit as if by @kbd{a F i},
25126then substitutes the @expr{x} value into the result in order to get an
25127approximate @expr{y} value based on the fit. (Calc does not actually
25128use @kbd{a F i}, however; it uses a direct method which is both more
25129efficient and more numerically stable.)
25130
25131The result of @kbd{a p} is actually a vector of two values: The @expr{y}
25132value approximation, and an error measure @expr{dy} that reflects Calc's
25133estimation of the probable error of the approximation at that value of
25134@expr{x}. If the input @expr{x} is equal to any of the @expr{x} values
25135in the data matrix, the output @expr{y} will be the corresponding @expr{y}
25136value from the matrix, and the output @expr{dy} will be exactly zero.
25137
25138A prefix argument of 2 causes @kbd{a p} to take separate x- and
25139y-vectors from the stack instead of one data matrix.
25140
25141If @expr{x} is a vector of numbers, @kbd{a p} will return a matrix of
25142interpolated results for each of those @expr{x} values. (The matrix will
25143have two columns, the @expr{y} values and the @expr{dy} values.)
25144If @expr{x} is a formula instead of a number, the @code{polint} function
25145remains in symbolic form; use the @kbd{a "} command to expand it out to
25146a formula that describes the fit in symbolic terms.
25147
25148In all cases, the @kbd{a p} command leaves the data vectors or matrix
25149on the stack. Only the @expr{x} value is replaced by the result.
25150
25151@kindex H a p
25152@tindex ratint
25153The @kbd{H a p} [@code{ratint}] command does a rational function
25154interpolation. It is used exactly like @kbd{a p}, except that it
25155uses as its model the quotient of two polynomials. If there are
25156@expr{N} data points, the numerator and denominator polynomials will
25157each have degree @expr{N/2} (if @expr{N} is odd, the denominator will
25158have degree one higher than the numerator).
25159
25160Rational approximations have the advantage that they can accurately
25161describe functions that have poles (points at which the function's value
25162goes to infinity, so that the denominator polynomial of the approximation
25163goes to zero). If @expr{x} corresponds to a pole of the fitted rational
25164function, then the result will be a division by zero. If Infinite mode
25165is enabled, the result will be @samp{[uinf, uinf]}.
25166
25167There is no way to get the actual coefficients of the rational function
25168used by @kbd{H a p}. (The algorithm never generates these coefficients
25169explicitly, and quotients of polynomials are beyond @w{@kbd{a F}}'s
25170capabilities to fit.)
25171
25172@node Summations, Logical Operations, Curve Fitting, Algebra
25173@section Summations
25174
25175@noindent
25176@cindex Summation of a series
25177@kindex a +
25178@pindex calc-summation
25179@tindex sum
25180The @kbd{a +} (@code{calc-summation}) [@code{sum}] command computes
25181the sum of a formula over a certain range of index values. The formula
25182is taken from the top of the stack; the command prompts for the
25183name of the summation index variable, the lower limit of the
25184sum (any formula), and the upper limit of the sum. If you
25185enter a blank line at any of these prompts, that prompt and
25186any later ones are answered by reading additional elements from
25187the stack. Thus, @kbd{' k^2 @key{RET} ' k @key{RET} 1 @key{RET} 5 @key{RET} a + @key{RET}}
25188produces the result 55.
25189@tex
25190\turnoffactive
25191$$ \sum_{k=1}^5 k^2 = 55 $$
25192@end tex
25193
25194The choice of index variable is arbitrary, but it's best not to
25195use a variable with a stored value. In particular, while
25196@code{i} is often a favorite index variable, it should be avoided
25197in Calc because @code{i} has the imaginary constant @expr{(0, 1)}
25198as a value. If you pressed @kbd{=} on a sum over @code{i}, it would
25199be changed to a nonsensical sum over the ``variable'' @expr{(0, 1)}!
25200If you really want to use @code{i} as an index variable, use
25201@w{@kbd{s u i @key{RET}}} first to ``unstore'' this variable.
25202(@xref{Storing Variables}.)
25203
25204A numeric prefix argument steps the index by that amount rather
25205than by one. Thus @kbd{' a_k @key{RET} C-u -2 a + k @key{RET} 10 @key{RET} 0 @key{RET}}
25206yields @samp{a_10 + a_8 + a_6 + a_4 + a_2 + a_0}. A prefix
25207argument of plain @kbd{C-u} causes @kbd{a +} to prompt for the
25208step value, in which case you can enter any formula or enter
25209a blank line to take the step value from the stack. With the
25210@kbd{C-u} prefix, @kbd{a +} can take up to five arguments from
25211the stack: The formula, the variable, the lower limit, the
25212upper limit, and (at the top of the stack), the step value.
25213
25214Calc knows how to do certain sums in closed form. For example,
25215@samp{sum(6 k^2, k, 1, n) = @w{2 n^3} + 3 n^2 + n}. In particular,
25216this is possible if the formula being summed is polynomial or
25217exponential in the index variable. Sums of logarithms are
25218transformed into logarithms of products. Sums of trigonometric
25219and hyperbolic functions are transformed to sums of exponentials
25220and then done in closed form. Also, of course, sums in which the
25221lower and upper limits are both numbers can always be evaluated
25222just by grinding them out, although Calc will use closed forms
25223whenever it can for the sake of efficiency.
25224
25225The notation for sums in algebraic formulas is
25226@samp{sum(@var{expr}, @var{var}, @var{low}, @var{high}, @var{step})}.
25227If @var{step} is omitted, it defaults to one. If @var{high} is
25228omitted, @var{low} is actually the upper limit and the lower limit
25229is one. If @var{low} is also omitted, the limits are @samp{-inf}
25230and @samp{inf}, respectively.
25231
25232Infinite sums can sometimes be evaluated: @samp{sum(.5^k, k, 1, inf)}
25233returns @expr{1}. This is done by evaluating the sum in closed
25234form (to @samp{1. - 0.5^n} in this case), then evaluating this
25235formula with @code{n} set to @code{inf}. Calc's usual rules
25236for ``infinite'' arithmetic can find the answer from there. If
25237infinite arithmetic yields a @samp{nan}, or if the sum cannot be
25238solved in closed form, Calc leaves the @code{sum} function in
25239symbolic form. @xref{Infinities}.
25240
25241As a special feature, if the limits are infinite (or omitted, as
25242described above) but the formula includes vectors subscripted by
25243expressions that involve the iteration variable, Calc narrows
25244the limits to include only the range of integers which result in
25245valid subscripts for the vector. For example, the sum
25246@samp{sum(k [a,b,c,d,e,f,g]_(2k),k)} evaluates to @samp{b + 2 d + 3 f}.
25247
25248The limits of a sum do not need to be integers. For example,
25249@samp{sum(a_k, k, 0, 2 n, n)} produces @samp{a_0 + a_n + a_(2 n)}.
25250Calc computes the number of iterations using the formula
25251@samp{1 + (@var{high} - @var{low}) / @var{step}}, which must,
25252after simplification as if by @kbd{a s}, evaluate to an integer.
25253
25254If the number of iterations according to the above formula does
25255not come out to an integer, the sum is invalid and will be left
25256in symbolic form. However, closed forms are still supplied, and
25257you are on your honor not to misuse the resulting formulas by
25258substituting mismatched bounds into them. For example,
25259@samp{sum(k, k, 1, 10, 2)} is invalid, but Calc will go ahead and
25260evaluate the closed form solution for the limits 1 and 10 to get
25261the rather dubious answer, 29.25.
25262
25263If the lower limit is greater than the upper limit (assuming a
25264positive step size), the result is generally zero. However,
25265Calc only guarantees a zero result when the upper limit is
25266exactly one step less than the lower limit, i.e., if the number
25267of iterations is @mathit{-1}. Thus @samp{sum(f(k), k, n, n-1)} is zero
25268but the sum from @samp{n} to @samp{n-2} may report a nonzero value
25269if Calc used a closed form solution.
25270
25271Calc's logical predicates like @expr{a < b} return 1 for ``true''
25272and 0 for ``false.'' @xref{Logical Operations}. This can be
25273used to advantage for building conditional sums. For example,
25274@samp{sum(prime(k)*k^2, k, 1, 20)} is the sum of the squares of all
25275prime numbers from 1 to 20; the @code{prime} predicate returns 1 if
25276its argument is prime and 0 otherwise. You can read this expression
25277as ``the sum of @expr{k^2}, where @expr{k} is prime.'' Indeed,
25278@samp{sum(prime(k)*k^2, k)} would represent the sum of @emph{all} primes
25279squared, since the limits default to plus and minus infinity, but
25280there are no such sums that Calc's built-in rules can do in
25281closed form.
25282
25283As another example, @samp{sum((k != k_0) * f(k), k, 1, n)} is the
25284sum of @expr{f(k)} for all @expr{k} from 1 to @expr{n}, excluding
25285one value @expr{k_0}. Slightly more tricky is the summand
25286@samp{(k != k_0) / (k - k_0)}, which is an attempt to describe
25287the sum of all @expr{1/(k-k_0)} except at @expr{k = k_0}, where
25288this would be a division by zero. But at @expr{k = k_0}, this
25289formula works out to the indeterminate form @expr{0 / 0}, which
25290Calc will not assume is zero. Better would be to use
25291@samp{(k != k_0) ? 1/(k-k_0) : 0}; the @samp{? :} operator does
25292an ``if-then-else'' test: This expression says, ``if
25293@texline @math{k \ne k_0},
25294@infoline @expr{k != k_0},
25295then @expr{1/(k-k_0)}, else zero.'' Now the formula @expr{1/(k-k_0)}
25296will not even be evaluated by Calc when @expr{k = k_0}.
25297
25298@cindex Alternating sums
25299@kindex a -
25300@pindex calc-alt-summation
25301@tindex asum
25302The @kbd{a -} (@code{calc-alt-summation}) [@code{asum}] command
25303computes an alternating sum. Successive terms of the sequence
25304are given alternating signs, with the first term (corresponding
25305to the lower index value) being positive. Alternating sums
25306are converted to normal sums with an extra term of the form
25307@samp{(-1)^(k-@var{low})}. This formula is adjusted appropriately
25308if the step value is other than one. For example, the Taylor
25309series for the sine function is @samp{asum(x^k / k!, k, 1, inf, 2)}.
25310(Calc cannot evaluate this infinite series, but it can approximate
25311it if you replace @code{inf} with any particular odd number.)
25312Calc converts this series to a regular sum with a step of one,
25313namely @samp{sum((-1)^k x^(2k+1) / (2k+1)!, k, 0, inf)}.
25314
25315@cindex Product of a sequence
25316@kindex a *
25317@pindex calc-product
25318@tindex prod
25319The @kbd{a *} (@code{calc-product}) [@code{prod}] command is
25320the analogous way to take a product of many terms. Calc also knows
25321some closed forms for products, such as @samp{prod(k, k, 1, n) = n!}.
25322Conditional products can be written @samp{prod(k^prime(k), k, 1, n)}
25323or @samp{prod(prime(k) ? k : 1, k, 1, n)}.
25324
25325@kindex a T
25326@pindex calc-tabulate
25327@tindex table
25328The @kbd{a T} (@code{calc-tabulate}) [@code{table}] command
25329evaluates a formula at a series of iterated index values, just
25330like @code{sum} and @code{prod}, but its result is simply a
25331vector of the results. For example, @samp{table(a_i, i, 1, 7, 2)}
25332produces @samp{[a_1, a_3, a_5, a_7]}.
25333
25334@node Logical Operations, Rewrite Rules, Summations, Algebra
25335@section Logical Operations
25336
25337@noindent
25338The following commands and algebraic functions return true/false values,
25339where 1 represents ``true'' and 0 represents ``false.'' In cases where
25340a truth value is required (such as for the condition part of a rewrite
25341rule, or as the condition for a @w{@kbd{Z [ Z ]}} control structure), any
25342nonzero value is accepted to mean ``true.'' (Specifically, anything
25343for which @code{dnonzero} returns 1 is ``true,'' and anything for
25344which @code{dnonzero} returns 0 or cannot decide is assumed ``false.''
25345Note that this means that @w{@kbd{Z [ Z ]}} will execute the ``then''
25346portion if its condition is provably true, but it will execute the
25347``else'' portion for any condition like @expr{a = b} that is not
25348provably true, even if it might be true. Algebraic functions that
25349have conditions as arguments, like @code{? :} and @code{&&}, remain
25350unevaluated if the condition is neither provably true nor provably
25351false. @xref{Declarations}.)
25352
25353@kindex a =
25354@pindex calc-equal-to
25355@tindex eq
25356@tindex =
25357@tindex ==
25358The @kbd{a =} (@code{calc-equal-to}) command, or @samp{eq(a,b)} function
25359(which can also be written @samp{a = b} or @samp{a == b} in an algebraic
25360formula) is true if @expr{a} and @expr{b} are equal, either because they
25361are identical expressions, or because they are numbers which are
25362numerically equal. (Thus the integer 1 is considered equal to the float
253631.0.) If the equality of @expr{a} and @expr{b} cannot be determined,
25364the comparison is left in symbolic form. Note that as a command, this
25365operation pops two values from the stack and pushes back either a 1 or
25366a 0, or a formula @samp{a = b} if the values' equality cannot be determined.
25367
25368Many Calc commands use @samp{=} formulas to represent @dfn{equations}.
25369For example, the @kbd{a S} (@code{calc-solve-for}) command rearranges
25370an equation to solve for a given variable. The @kbd{a M}
25371(@code{calc-map-equation}) command can be used to apply any
25372function to both sides of an equation; for example, @kbd{2 a M *}
25373multiplies both sides of the equation by two. Note that just
25374@kbd{2 *} would not do the same thing; it would produce the formula
25375@samp{2 (a = b)} which represents 2 if the equality is true or
25376zero if not.
25377
25378The @code{eq} function with more than two arguments (e.g., @kbd{C-u 3 a =}
25379or @samp{a = b = c}) tests if all of its arguments are equal. In
25380algebraic notation, the @samp{=} operator is unusual in that it is
25381neither left- nor right-associative: @samp{a = b = c} is not the
25382same as @samp{(a = b) = c} or @samp{a = (b = c)} (which each compare
25383one variable with the 1 or 0 that results from comparing two other
25384variables).
25385
25386@kindex a #
25387@pindex calc-not-equal-to
25388@tindex neq
25389@tindex !=
25390The @kbd{a #} (@code{calc-not-equal-to}) command, or @samp{neq(a,b)} or
25391@samp{a != b} function, is true if @expr{a} and @expr{b} are not equal.
25392This also works with more than two arguments; @samp{a != b != c != d}
25393tests that all four of @expr{a}, @expr{b}, @expr{c}, and @expr{d} are
25394distinct numbers.
25395
25396@kindex a <
25397@tindex lt
25398@ignore
25399@mindex @idots
25400@end ignore
25401@kindex a >
25402@ignore
25403@mindex @null
25404@end ignore
25405@kindex a [
25406@ignore
25407@mindex @null
25408@end ignore
25409@kindex a ]
25410@pindex calc-less-than
25411@pindex calc-greater-than
25412@pindex calc-less-equal
25413@pindex calc-greater-equal
25414@ignore
25415@mindex @null
25416@end ignore
25417@tindex gt
25418@ignore
25419@mindex @null
25420@end ignore
25421@tindex leq
25422@ignore
25423@mindex @null
25424@end ignore
25425@tindex geq
25426@ignore
25427@mindex @null
25428@end ignore
25429@tindex <
25430@ignore
25431@mindex @null
25432@end ignore
25433@tindex >
25434@ignore
25435@mindex @null
25436@end ignore
25437@tindex <=
25438@ignore
25439@mindex @null
25440@end ignore
25441@tindex >=
25442The @kbd{a <} (@code{calc-less-than}) [@samp{lt(a,b)} or @samp{a < b}]
25443operation is true if @expr{a} is less than @expr{b}. Similar functions
25444are @kbd{a >} (@code{calc-greater-than}) [@samp{gt(a,b)} or @samp{a > b}],
25445@kbd{a [} (@code{calc-less-equal}) [@samp{leq(a,b)} or @samp{a <= b}], and
25446@kbd{a ]} (@code{calc-greater-equal}) [@samp{geq(a,b)} or @samp{a >= b}].
25447
25448While the inequality functions like @code{lt} do not accept more
25449than two arguments, the syntax @w{@samp{a <= b < c}} is translated to an
25450equivalent expression involving intervals: @samp{b in [a .. c)}.
25451(See the description of @code{in} below.) All four combinations
25452of @samp{<} and @samp{<=} are allowed, or any of the four combinations
25453of @samp{>} and @samp{>=}. Four-argument constructions like
25454@samp{a < b < c < d}, and mixtures like @w{@samp{a < b = c}} that
25455involve both equalities and inequalities, are not allowed.
25456
25457@kindex a .
25458@pindex calc-remove-equal
25459@tindex rmeq
25460The @kbd{a .} (@code{calc-remove-equal}) [@code{rmeq}] command extracts
25461the righthand side of the equation or inequality on the top of the
25462stack. It also works elementwise on vectors. For example, if
25463@samp{[x = 2.34, y = z / 2]} is on the stack, then @kbd{a .} produces
25464@samp{[2.34, z / 2]}. As a special case, if the righthand side is a
25465variable and the lefthand side is a number (as in @samp{2.34 = x}), then
25466Calc keeps the lefthand side instead. Finally, this command works with
25467assignments @samp{x := 2.34} as well as equations, always taking the
25468righthand side, and for @samp{=>} (evaluates-to) operators, always
25469taking the lefthand side.
25470
25471@kindex a &
25472@pindex calc-logical-and
25473@tindex land
25474@tindex &&
25475The @kbd{a &} (@code{calc-logical-and}) [@samp{land(a,b)} or @samp{a && b}]
25476function is true if both of its arguments are true, i.e., are
25477non-zero numbers. In this case, the result will be either @expr{a} or
25478@expr{b}, chosen arbitrarily. If either argument is zero, the result is
25479zero. Otherwise, the formula is left in symbolic form.
25480
25481@kindex a |
25482@pindex calc-logical-or
25483@tindex lor
25484@tindex ||
25485The @kbd{a |} (@code{calc-logical-or}) [@samp{lor(a,b)} or @samp{a || b}]
25486function is true if either or both of its arguments are true (nonzero).
25487The result is whichever argument was nonzero, choosing arbitrarily if both
25488are nonzero. If both @expr{a} and @expr{b} are zero, the result is
25489zero.
25490
25491@kindex a !
25492@pindex calc-logical-not
25493@tindex lnot
25494@tindex !
25495The @kbd{a !} (@code{calc-logical-not}) [@samp{lnot(a)} or @samp{!@: a}]
25496function is true if @expr{a} is false (zero), or false if @expr{a} is
25497true (nonzero). It is left in symbolic form if @expr{a} is not a
25498number.
25499
25500@kindex a :
25501@pindex calc-logical-if
25502@tindex if
25503@ignore
25504@mindex ? :
25505@end ignore
25506@tindex ?
25507@ignore
25508@mindex @null
25509@end ignore
25510@tindex :
25511@cindex Arguments, not evaluated
25512The @kbd{a :} (@code{calc-logical-if}) [@samp{if(a,b,c)} or @samp{a ? b :@: c}]
25513function is equal to either @expr{b} or @expr{c} if @expr{a} is a nonzero
25514number or zero, respectively. If @expr{a} is not a number, the test is
25515left in symbolic form and neither @expr{b} nor @expr{c} is evaluated in
25516any way. In algebraic formulas, this is one of the few Calc functions
25517whose arguments are not automatically evaluated when the function itself
25518is evaluated. The others are @code{lambda}, @code{quote}, and
25519@code{condition}.
25520
25521One minor surprise to watch out for is that the formula @samp{a?3:4}
25522will not work because the @samp{3:4} is parsed as a fraction instead of
25523as three separate symbols. Type something like @samp{a ? 3 : 4} or
25524@samp{a?(3):4} instead.
25525
25526As a special case, if @expr{a} evaluates to a vector, then both @expr{b}
25527and @expr{c} are evaluated; the result is a vector of the same length
25528as @expr{a} whose elements are chosen from corresponding elements of
25529@expr{b} and @expr{c} according to whether each element of @expr{a}
25530is zero or nonzero. Each of @expr{b} and @expr{c} must be either a
25531vector of the same length as @expr{a}, or a non-vector which is matched
25532with all elements of @expr{a}.
25533
25534@kindex a @{
25535@pindex calc-in-set
25536@tindex in
25537The @kbd{a @{} (@code{calc-in-set}) [@samp{in(a,b)}] function is true if
25538the number @expr{a} is in the set of numbers represented by @expr{b}.
25539If @expr{b} is an interval form, @expr{a} must be one of the values
25540encompassed by the interval. If @expr{b} is a vector, @expr{a} must be
25541equal to one of the elements of the vector. (If any vector elements are
25542intervals, @expr{a} must be in any of the intervals.) If @expr{b} is a
25543plain number, @expr{a} must be numerically equal to @expr{b}.
25544@xref{Set Operations}, for a group of commands that manipulate sets
25545of this sort.
25546
25547@ignore
25548@starindex
25549@end ignore
25550@tindex typeof
25551The @samp{typeof(a)} function produces an integer or variable which
25552characterizes @expr{a}. If @expr{a} is a number, vector, or variable,
25553the result will be one of the following numbers:
25554
25555@example
25556 1 Integer
25557 2 Fraction
25558 3 Floating-point number
25559 4 HMS form
25560 5 Rectangular complex number
25561 6 Polar complex number
25562 7 Error form
25563 8 Interval form
25564 9 Modulo form
2556510 Date-only form
2556611 Date/time form
2556712 Infinity (inf, uinf, or nan)
25568100 Variable
25569101 Vector (but not a matrix)
25570102 Matrix
25571@end example
25572
25573Otherwise, @expr{a} is a formula, and the result is a variable which
25574represents the name of the top-level function call.
25575
25576@ignore
25577@starindex
25578@end ignore
25579@tindex integer
25580@ignore
25581@starindex
25582@end ignore
25583@tindex real
25584@ignore
25585@starindex
25586@end ignore
25587@tindex constant
25588The @samp{integer(a)} function returns true if @expr{a} is an integer.
25589The @samp{real(a)} function
25590is true if @expr{a} is a real number, either integer, fraction, or
25591float. The @samp{constant(a)} function returns true if @expr{a} is
25592any of the objects for which @code{typeof} would produce an integer
25593code result except for variables, and provided that the components of
25594an object like a vector or error form are themselves constant.
25595Note that infinities do not satisfy any of these tests, nor do
25596special constants like @code{pi} and @code{e}.
25597
25598@xref{Declarations}, for a set of similar functions that recognize
25599formulas as well as actual numbers. For example, @samp{dint(floor(x))}
25600is true because @samp{floor(x)} is provably integer-valued, but
25601@samp{integer(floor(x))} does not because @samp{floor(x)} is not
25602literally an integer constant.
25603
25604@ignore
25605@starindex
25606@end ignore
25607@tindex refers
25608The @samp{refers(a,b)} function is true if the variable (or sub-expression)
25609@expr{b} appears in @expr{a}, or false otherwise. Unlike the other
25610tests described here, this function returns a definite ``no'' answer
25611even if its arguments are still in symbolic form. The only case where
25612@code{refers} will be left unevaluated is if @expr{a} is a plain
25613variable (different from @expr{b}).
25614
25615@ignore
25616@starindex
25617@end ignore
25618@tindex negative
25619The @samp{negative(a)} function returns true if @expr{a} ``looks'' negative,
25620because it is a negative number, because it is of the form @expr{-x},
25621or because it is a product or quotient with a term that looks negative.
25622This is most useful in rewrite rules. Beware that @samp{negative(a)}
25623evaluates to 1 or 0 for @emph{any} argument @expr{a}, so it can only
25624be stored in a formula if the default simplifications are turned off
25625first with @kbd{m O} (or if it appears in an unevaluated context such
25626as a rewrite rule condition).
25627
25628@ignore
25629@starindex
25630@end ignore
25631@tindex variable
25632The @samp{variable(a)} function is true if @expr{a} is a variable,
25633or false if not. If @expr{a} is a function call, this test is left
25634in symbolic form. Built-in variables like @code{pi} and @code{inf}
25635are considered variables like any others by this test.
25636
25637@ignore
25638@starindex
25639@end ignore
25640@tindex nonvar
25641The @samp{nonvar(a)} function is true if @expr{a} is a non-variable.
25642If its argument is a variable it is left unsimplified; it never
25643actually returns zero. However, since Calc's condition-testing
25644commands consider ``false'' anything not provably true, this is
25645often good enough.
25646
25647@ignore
25648@starindex
25649@end ignore
25650@tindex lin
25651@ignore
25652@starindex
25653@end ignore
25654@tindex linnt
25655@ignore
25656@starindex
25657@end ignore
25658@tindex islin
25659@ignore
25660@starindex
25661@end ignore
25662@tindex islinnt
25663@cindex Linearity testing
25664The functions @code{lin}, @code{linnt}, @code{islin}, and @code{islinnt}
25665check if an expression is ``linear,'' i.e., can be written in the form
25666@expr{a + b x} for some constants @expr{a} and @expr{b}, and some
25667variable or subformula @expr{x}. The function @samp{islin(f,x)} checks
25668if formula @expr{f} is linear in @expr{x}, returning 1 if so. For
25669example, @samp{islin(x,x)}, @samp{islin(-x,x)}, @samp{islin(3,x)}, and
25670@samp{islin(x y / 3 - 2, x)} all return 1. The @samp{lin(f,x)} function
25671is similar, except that instead of returning 1 it returns the vector
25672@expr{[a, b, x]}. For the above examples, this vector would be
25673@expr{[0, 1, x]}, @expr{[0, -1, x]}, @expr{[3, 0, x]}, and
25674@expr{[-2, y/3, x]}, respectively. Both @code{lin} and @code{islin}
25675generally remain unevaluated for expressions which are not linear,
25676e.g., @samp{lin(2 x^2, x)} and @samp{lin(sin(x), x)}. The second
25677argument can also be a formula; @samp{islin(2 + 3 sin(x), sin(x))}
25678returns true.
25679
25680The @code{linnt} and @code{islinnt} functions perform a similar check,
25681but require a ``non-trivial'' linear form, which means that the
25682@expr{b} coefficient must be non-zero. For example, @samp{lin(2,x)}
25683returns @expr{[2, 0, x]} and @samp{lin(y,x)} returns @expr{[y, 0, x]},
25684but @samp{linnt(2,x)} and @samp{linnt(y,x)} are left unevaluated
25685(in other words, these formulas are considered to be only ``trivially''
25686linear in @expr{x}).
25687
25688All four linearity-testing functions allow you to omit the second
25689argument, in which case the input may be linear in any non-constant
25690formula. Here, the @expr{a=0}, @expr{b=1} case is also considered
25691trivial, and only constant values for @expr{a} and @expr{b} are
25692recognized. Thus, @samp{lin(2 x y)} returns @expr{[0, 2, x y]},
25693@samp{lin(2 - x y)} returns @expr{[2, -1, x y]}, and @samp{lin(x y)}
25694returns @expr{[0, 1, x y]}. The @code{linnt} function would allow the
25695first two cases but not the third. Also, neither @code{lin} nor
25696@code{linnt} accept plain constants as linear in the one-argument
25697case: @samp{islin(2,x)} is true, but @samp{islin(2)} is false.
25698
25699@ignore
25700@starindex
25701@end ignore
25702@tindex istrue
25703The @samp{istrue(a)} function returns 1 if @expr{a} is a nonzero
25704number or provably nonzero formula, or 0 if @expr{a} is anything else.
25705Calls to @code{istrue} can only be manipulated if @kbd{m O} mode is
25706used to make sure they are not evaluated prematurely. (Note that
25707declarations are used when deciding whether a formula is true;
25708@code{istrue} returns 1 when @code{dnonzero} would return 1, and
25709it returns 0 when @code{dnonzero} would return 0 or leave itself
25710in symbolic form.)
25711
25712@node Rewrite Rules, , Logical Operations, Algebra
25713@section Rewrite Rules
25714
25715@noindent
25716@cindex Rewrite rules
25717@cindex Transformations
25718@cindex Pattern matching
25719@kindex a r
25720@pindex calc-rewrite
25721@tindex rewrite
25722The @kbd{a r} (@code{calc-rewrite}) [@code{rewrite}] command makes
25723substitutions in a formula according to a specified pattern or patterns
25724known as @dfn{rewrite rules}. Whereas @kbd{a b} (@code{calc-substitute})
25725matches literally, so that substituting @samp{sin(x)} with @samp{cos(x)}
25726matches only the @code{sin} function applied to the variable @code{x},
25727rewrite rules match general kinds of formulas; rewriting using the rule
25728@samp{sin(x) := cos(x)} matches @code{sin} of any argument and replaces
25729it with @code{cos} of that same argument. The only significance of the
25730name @code{x} is that the same name is used on both sides of the rule.
25731
25732Rewrite rules rearrange formulas already in Calc's memory.
25733@xref{Syntax Tables}, to read about @dfn{syntax rules}, which are
25734similar to algebraic rewrite rules but operate when new algebraic
25735entries are being parsed, converting strings of characters into
25736Calc formulas.
25737
25738@menu
25739* Entering Rewrite Rules::
25740* Basic Rewrite Rules::
25741* Conditional Rewrite Rules::
25742* Algebraic Properties of Rewrite Rules::
25743* Other Features of Rewrite Rules::
25744* Composing Patterns in Rewrite Rules::
25745* Nested Formulas with Rewrite Rules::
25746* Multi-Phase Rewrite Rules::
25747* Selections with Rewrite Rules::
25748* Matching Commands::
25749* Automatic Rewrites::
25750* Debugging Rewrites::
25751* Examples of Rewrite Rules::
25752@end menu
25753
25754@node Entering Rewrite Rules, Basic Rewrite Rules, Rewrite Rules, Rewrite Rules
25755@subsection Entering Rewrite Rules
25756
25757@noindent
25758Rewrite rules normally use the ``assignment'' operator
25759@samp{@var{old} := @var{new}}.
25760This operator is equivalent to the function call @samp{assign(old, new)}.
25761The @code{assign} function is undefined by itself in Calc, so an
25762assignment formula such as a rewrite rule will be left alone by ordinary
25763Calc commands. But certain commands, like the rewrite system, interpret
25764assignments in special ways.
25765
25766For example, the rule @samp{sin(x)^2 := 1-cos(x)^2} says to replace
25767every occurrence of the sine of something, squared, with one minus the
25768square of the cosine of that same thing. All by itself as a formula
25769on the stack it does nothing, but when given to the @kbd{a r} command
25770it turns that command into a sine-squared-to-cosine-squared converter.
25771
25772To specify a set of rules to be applied all at once, make a vector of
25773rules.
25774
25775When @kbd{a r} prompts you to enter the rewrite rules, you can answer
25776in several ways:
25777
25778@enumerate
25779@item
25780With a rule: @kbd{f(x) := g(x) @key{RET}}.
25781@item
25782With a vector of rules: @kbd{[f1(x) := g1(x), f2(x) := g2(x)] @key{RET}}.
25783(You can omit the enclosing square brackets if you wish.)
25784@item
25785With the name of a variable that contains the rule or rules vector:
25786@kbd{myrules @key{RET}}.
25787@item
25788With any formula except a rule, a vector, or a variable name; this
25789will be interpreted as the @var{old} half of a rewrite rule,
25790and you will be prompted a second time for the @var{new} half:
25791@kbd{f(x) @key{RET} g(x) @key{RET}}.
25792@item
25793With a blank line, in which case the rule, rules vector, or variable
25794will be taken from the top of the stack (and the formula to be
25795rewritten will come from the second-to-top position).
25796@end enumerate
25797
25798If you enter the rules directly (as opposed to using rules stored
25799in a variable), those rules will be put into the Trail so that you
25800can retrieve them later. @xref{Trail Commands}.
25801
25802It is most convenient to store rules you use often in a variable and
25803invoke them by giving the variable name. The @kbd{s e}
25804(@code{calc-edit-variable}) command is an easy way to create or edit a
25805rule set stored in a variable. You may also wish to use @kbd{s p}
25806(@code{calc-permanent-variable}) to save your rules permanently;
25807@pxref{Operations on Variables}.
25808
25809Rewrite rules are compiled into a special internal form for faster
25810matching. If you enter a rule set directly it must be recompiled
25811every time. If you store the rules in a variable and refer to them
25812through that variable, they will be compiled once and saved away
25813along with the variable for later reference. This is another good
25814reason to store your rules in a variable.
25815
25816Calc also accepts an obsolete notation for rules, as vectors
25817@samp{[@var{old}, @var{new}]}. But because it is easily confused with a
25818vector of two rules, the use of this notation is no longer recommended.
25819
25820@node Basic Rewrite Rules, Conditional Rewrite Rules, Entering Rewrite Rules, Rewrite Rules
25821@subsection Basic Rewrite Rules
25822
25823@noindent
25824To match a particular formula @expr{x} with a particular rewrite rule
25825@samp{@var{old} := @var{new}}, Calc compares the structure of @expr{x} with
25826the structure of @var{old}. Variables that appear in @var{old} are
25827treated as @dfn{meta-variables}; the corresponding positions in @expr{x}
25828may contain any sub-formulas. For example, the pattern @samp{f(x,y)}
25829would match the expression @samp{f(12, a+1)} with the meta-variable
25830@samp{x} corresponding to 12 and with @samp{y} corresponding to
25831@samp{a+1}. However, this pattern would not match @samp{f(12)} or
25832@samp{g(12, a+1)}, since there is no assignment of the meta-variables
25833that will make the pattern match these expressions. Notice that if
25834the pattern is a single meta-variable, it will match any expression.
25835
25836If a given meta-variable appears more than once in @var{old}, the
25837corresponding sub-formulas of @expr{x} must be identical. Thus
25838the pattern @samp{f(x,x)} would match @samp{f(12, 12)} and
25839@samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(a+b, b+a)}.
25840(@xref{Conditional Rewrite Rules}, for a way to match the latter.)
25841
25842Things other than variables must match exactly between the pattern
25843and the target formula. To match a particular variable exactly, use
25844the pseudo-function @samp{quote(v)} in the pattern. For example, the
25845pattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or
25846@samp{sin(a)+y}.
25847
25848The special variable names @samp{e}, @samp{pi}, @samp{i}, @samp{phi},
25849@samp{gamma}, @samp{inf}, @samp{uinf}, and @samp{nan} always match
25850literally. Thus the pattern @samp{sin(d + e + f)} acts exactly like
25851@samp{sin(d + quote(e) + f)}.
25852
25853If the @var{old} pattern is found to match a given formula, that
25854formula is replaced by @var{new}, where any occurrences in @var{new}
25855of meta-variables from the pattern are replaced with the sub-formulas
25856that they matched. Thus, applying the rule @samp{f(x,y) := g(y+x,x)}
25857to @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}.
25858
25859The normal @kbd{a r} command applies rewrite rules over and over
25860throughout the target formula until no further changes are possible
25861(up to a limit of 100 times). Use @kbd{C-u 1 a r} to make only one
25862change at a time.
25863
25864@node Conditional Rewrite Rules, Algebraic Properties of Rewrite Rules, Basic Rewrite Rules, Rewrite Rules
25865@subsection Conditional Rewrite Rules
25866
25867@noindent
25868A rewrite rule can also be @dfn{conditional}, written in the form
25869@samp{@var{old} := @var{new} :: @var{cond}}. (There is also the obsolete
25870form @samp{[@var{old}, @var{new}, @var{cond}]}.) If a @var{cond} part
25871is present in the
25872rule, this is an additional condition that must be satisfied before
25873the rule is accepted. Once @var{old} has been successfully matched
25874to the target expression, @var{cond} is evaluated (with all the
25875meta-variables substituted for the values they matched) and simplified
25876with @kbd{a s} (@code{calc-simplify}). If the result is a nonzero
25877number or any other object known to be nonzero (@pxref{Declarations}),
25878the rule is accepted. If the result is zero or if it is a symbolic
25879formula that is not known to be nonzero, the rule is rejected.
25880@xref{Logical Operations}, for a number of functions that return
258811 or 0 according to the results of various tests.
25882
25883For example, the formula @samp{n > 0} simplifies to 1 or 0 if @expr{n}
25884is replaced by a positive or nonpositive number, respectively (or if
25885@expr{n} has been declared to be positive or nonpositive). Thus,
25886the rule @samp{f(x,y) := g(y+x,x) :: x+y > 0} would apply to
25887@samp{f(0, 4)} but not to @samp{f(-3, 2)} or @samp{f(12, a+1)}
25888(assuming no outstanding declarations for @expr{a}). In the case of
25889@samp{f(-3, 2)}, the condition can be shown not to be satisfied; in
25890the case of @samp{f(12, a+1)}, the condition merely cannot be shown
25891to be satisfied, but that is enough to reject the rule.
25892
25893While Calc will use declarations to reason about variables in the
25894formula being rewritten, declarations do not apply to meta-variables.
25895For example, the rule @samp{f(a) := g(a+1)} will match for any values
25896of @samp{a}, such as complex numbers, vectors, or formulas, even if
25897@samp{a} has been declared to be real or scalar. If you want the
25898meta-variable @samp{a} to match only literal real numbers, use
25899@samp{f(a) := g(a+1) :: real(a)}. If you want @samp{a} to match only
25900reals and formulas which are provably real, use @samp{dreal(a)} as
25901the condition.
25902
25903The @samp{::} operator is a shorthand for the @code{condition}
25904function; @samp{@var{old} := @var{new} :: @var{cond}} is equivalent to
25905the formula @samp{condition(assign(@var{old}, @var{new}), @var{cond})}.
25906
25907If you have several conditions, you can use @samp{... :: c1 :: c2 :: c3}
25908or @samp{... :: c1 && c2 && c3}. The two are entirely equivalent.
25909
25910It is also possible to embed conditions inside the pattern:
25911@samp{f(x :: x>0, y) := g(y+x, x)}. This is purely a notational
25912convenience, though; where a condition appears in a rule has no
25913effect on when it is tested. The rewrite-rule compiler automatically
25914decides when it is best to test each condition while a rule is being
25915matched.
25916
25917Certain conditions are handled as special cases by the rewrite rule
25918system and are tested very efficiently: Where @expr{x} is any
25919meta-variable, these conditions are @samp{integer(x)}, @samp{real(x)},
25920@samp{constant(x)}, @samp{negative(x)}, @samp{x >= y} where @expr{y}
25921is either a constant or another meta-variable and @samp{>=} may be
25922replaced by any of the six relational operators, and @samp{x % a = b}
25923where @expr{a} and @expr{b} are constants. Other conditions, like
25924@samp{x >= y+1} or @samp{dreal(x)}, will be less efficient to check
25925since Calc must bring the whole evaluator and simplifier into play.
25926
25927An interesting property of @samp{::} is that neither of its arguments
25928will be touched by Calc's default simplifications. This is important
25929because conditions often are expressions that cannot safely be
25930evaluated early. For example, the @code{typeof} function never
25931remains in symbolic form; entering @samp{typeof(a)} will put the
25932number 100 (the type code for variables like @samp{a}) on the stack.
25933But putting the condition @samp{... :: typeof(a) = 6} on the stack
25934is safe since @samp{::} prevents the @code{typeof} from being
25935evaluated until the condition is actually used by the rewrite system.
25936
25937Since @samp{::} protects its lefthand side, too, you can use a dummy
25938condition to protect a rule that must itself not evaluate early.
25939For example, it's not safe to put @samp{a(f,x) := apply(f, [x])} on
25940the stack because it will immediately evaluate to @samp{a(f,x) := f(x)},
25941where the meta-variable-ness of @code{f} on the righthand side has been
25942lost. But @samp{a(f,x) := apply(f, [x]) :: 1} is safe, and of course
25943the condition @samp{1} is always true (nonzero) so it has no effect on
25944the functioning of the rule. (The rewrite compiler will ensure that
25945it doesn't even impact the speed of matching the rule.)
25946
25947@node Algebraic Properties of Rewrite Rules, Other Features of Rewrite Rules, Conditional Rewrite Rules, Rewrite Rules
25948@subsection Algebraic Properties of Rewrite Rules
25949
25950@noindent
25951The rewrite mechanism understands the algebraic properties of functions
25952like @samp{+} and @samp{*}. In particular, pattern matching takes
25953the associativity and commutativity of the following functions into
25954account:
25955
25956@smallexample
25957+ - * = != && || and or xor vint vunion vxor gcd lcm max min beta
25958@end smallexample
25959
25960For example, the rewrite rule:
25961
25962@example
25963a x + b x := (a + b) x
25964@end example
25965
25966@noindent
25967will match formulas of the form,
25968
25969@example
25970a x + b x, x a + x b, a x + x b, x a + b x
25971@end example
25972
25973Rewrites also understand the relationship between the @samp{+} and @samp{-}
25974operators. The above rewrite rule will also match the formulas,
25975
25976@example
25977a x - b x, x a - x b, a x - x b, x a - b x
25978@end example
25979
25980@noindent
25981by matching @samp{b} in the pattern to @samp{-b} from the formula.
25982
25983Applied to a sum of many terms like @samp{r + a x + s + b x + t}, this
25984pattern will check all pairs of terms for possible matches. The rewrite
25985will take whichever suitable pair it discovers first.
25986
25987In general, a pattern using an associative operator like @samp{a + b}
25988will try @var{2 n} different ways to match a sum of @var{n} terms
25989like @samp{x + y + z - w}. First, @samp{a} is matched against each
25990of @samp{x}, @samp{y}, @samp{z}, and @samp{-w} in turn, with @samp{b}
25991being matched to the remainders @samp{y + z - w}, @samp{x + z - w}, etc.
25992If none of these succeed, then @samp{b} is matched against each of the
25993four terms with @samp{a} matching the remainder. Half-and-half matches,
25994like @samp{(x + y) + (z - w)}, are not tried.
25995
25996Note that @samp{*} is not commutative when applied to matrices, but
25997rewrite rules pretend that it is. If you type @kbd{m v} to enable
25998Matrix mode (@pxref{Matrix Mode}), rewrite rules will match @samp{*}
25999literally, ignoring its usual commutativity property. (In the
26000current implementation, the associativity also vanishes---it is as
26001if the pattern had been enclosed in a @code{plain} marker; see below.)
26002If you are applying rewrites to formulas with matrices, it's best to
26003enable Matrix mode first to prevent algebraically incorrect rewrites
26004from occurring.
26005
26006The pattern @samp{-x} will actually match any expression. For example,
26007the rule
26008
26009@example
26010f(-x) := -f(x)
26011@end example
26012
26013@noindent
26014will rewrite @samp{f(a)} to @samp{-f(-a)}. To avoid this, either use
26015a @code{plain} marker as described below, or add a @samp{negative(x)}
26016condition. The @code{negative} function is true if its argument
26017``looks'' negative, for example, because it is a negative number or
26018because it is a formula like @samp{-x}. The new rule using this
26019condition is:
26020
26021@example
26022f(x) := -f(-x) :: negative(x) @r{or, equivalently,}
26023f(-x) := -f(x) :: negative(-x)
26024@end example
26025
26026In the same way, the pattern @samp{x - y} will match the sum @samp{a + b}
26027by matching @samp{y} to @samp{-b}.
26028
26029The pattern @samp{a b} will also match the formula @samp{x/y} if
26030@samp{y} is a number. Thus the rule @samp{a x + @w{b x} := (a+b) x}
26031will also convert @samp{a x + x / 2} to @samp{(a + 0.5) x} (or
26032@samp{(a + 1:2) x}, depending on the current fraction mode).
26033
26034Calc will @emph{not} take other liberties with @samp{*}, @samp{/}, and
26035@samp{^}. For example, the pattern @samp{f(a b)} will not match
26036@samp{f(x^2)}, and @samp{f(a + b)} will not match @samp{f(2 x)}, even
26037though conceivably these patterns could match with @samp{a = b = x}.
26038Nor will @samp{f(a b)} match @samp{f(x / y)} if @samp{y} is not a
26039constant, even though it could be considered to match with @samp{a = x}
26040and @samp{b = 1/y}. The reasons are partly for efficiency, and partly
26041because while few mathematical operations are substantively different
26042for addition and subtraction, often it is preferable to treat the cases
26043of multiplication, division, and integer powers separately.
26044
26045Even more subtle is the rule set
26046
26047@example
26048[ f(a) + f(b) := f(a + b), -f(a) := f(-a) ]
26049@end example
26050
26051@noindent
26052attempting to match @samp{f(x) - f(y)}. You might think that Calc
26053will view this subtraction as @samp{f(x) + (-f(y))} and then apply
26054the above two rules in turn, but actually this will not work because
26055Calc only does this when considering rules for @samp{+} (like the
26056first rule in this set). So it will see first that @samp{f(x) + (-f(y))}
26057does not match @samp{f(a) + f(b)} for any assignments of the
26058meta-variables, and then it will see that @samp{f(x) - f(y)} does
26059not match @samp{-f(a)} for any assignment of @samp{a}. Because Calc
26060tries only one rule at a time, it will not be able to rewrite
26061@samp{f(x) - f(y)} with this rule set. An explicit @samp{f(a) - f(b)}
26062rule will have to be added.
26063
26064Another thing patterns will @emph{not} do is break up complex numbers.
26065The pattern @samp{myconj(a + @w{b i)} := a - b i} will work for formulas
26066involving the special constant @samp{i} (such as @samp{3 - 4 i}), but
26067it will not match actual complex numbers like @samp{(3, -4)}. A version
26068of the above rule for complex numbers would be
26069
26070@example
26071myconj(a) := re(a) - im(a) (0,1) :: im(a) != 0
26072@end example
26073
26074@noindent
26075(Because the @code{re} and @code{im} functions understand the properties
26076of the special constant @samp{i}, this rule will also work for
26077@samp{3 - 4 i}. In fact, this particular rule would probably be better
26078without the @samp{im(a) != 0} condition, since if @samp{im(a) = 0} the
26079righthand side of the rule will still give the correct answer for the
26080conjugate of a real number.)
26081
26082It is also possible to specify optional arguments in patterns. The rule
26083
26084@example
26085opt(a) x + opt(b) (x^opt(c) + opt(d)) := f(a, b, c, d)
26086@end example
26087
26088@noindent
26089will match the formula
26090
26091@example
260925 (x^2 - 4) + 3 x
26093@end example
26094
26095@noindent
26096in a fairly straightforward manner, but it will also match reduced
26097formulas like
26098
26099@example
26100x + x^2, 2(x + 1) - x, x + x
26101@end example
26102
26103@noindent
26104producing, respectively,
26105
26106@example
26107f(1, 1, 2, 0), f(-1, 2, 1, 1), f(1, 1, 1, 0)
26108@end example
26109
26110(The latter two formulas can be entered only if default simplifications
26111have been turned off with @kbd{m O}.)
26112
26113The default value for a term of a sum is zero. The default value
26114for a part of a product, for a power, or for the denominator of a
26115quotient, is one. Also, @samp{-x} matches the pattern @samp{opt(a) b}
26116with @samp{a = -1}.
26117
26118In particular, the distributive-law rule can be refined to
26119
26120@example
26121opt(a) x + opt(b) x := (a + b) x
26122@end example
26123
26124@noindent
26125so that it will convert, e.g., @samp{a x - x}, to @samp{(a - 1) x}.
26126
26127The pattern @samp{opt(a) + opt(b) x} matches almost any formulas which
26128are linear in @samp{x}. You can also use the @code{lin} and @code{islin}
26129functions with rewrite conditions to test for this; @pxref{Logical
26130Operations}. These functions are not as convenient to use in rewrite
26131rules, but they recognize more kinds of formulas as linear:
26132@samp{x/z} is considered linear with @expr{b = 1/z} by @code{lin},
26133but it will not match the above pattern because that pattern calls
26134for a multiplication, not a division.
26135
26136As another example, the obvious rule to replace @samp{sin(x)^2 + cos(x)^2}
26137by 1,
26138
26139@example
26140sin(x)^2 + cos(x)^2 := 1
26141@end example
26142
26143@noindent
26144misses many cases because the sine and cosine may both be multiplied by
26145an equal factor. Here's a more successful rule:
26146
26147@example
26148opt(a) sin(x)^2 + opt(a) cos(x)^2 := a
26149@end example
26150
26151Note that this rule will @emph{not} match @samp{sin(x)^2 + 6 cos(x)^2}
26152because one @expr{a} would have ``matched'' 1 while the other matched 6.
26153
26154Calc automatically converts a rule like
26155
26156@example
26157f(x-1, x) := g(x)
26158@end example
26159
26160@noindent
26161into the form
26162
26163@example
26164f(temp, x) := g(x) :: temp = x-1
26165@end example
26166
26167@noindent
26168(where @code{temp} stands for a new, invented meta-variable that
26169doesn't actually have a name). This modified rule will successfully
26170match @samp{f(6, 7)}, binding @samp{temp} and @samp{x} to 6 and 7,
26171respectively, then verifying that they differ by one even though
26172@samp{6} does not superficially look like @samp{x-1}.
26173
26174However, Calc does not solve equations to interpret a rule. The
26175following rule,
26176
26177@example
26178f(x-1, x+1) := g(x)
26179@end example
26180
26181@noindent
26182will not work. That is, it will match @samp{f(a - 1 + b, a + 1 + b)}
26183but not @samp{f(6, 8)}. Calc always interprets at least one occurrence
26184of a variable by literal matching. If the variable appears ``isolated''
26185then Calc is smart enough to use it for literal matching. But in this
26186last example, Calc is forced to rewrite the rule to @samp{f(x-1, temp)
26187:= g(x) :: temp = x+1} where the @samp{x-1} term must correspond to an
26188actual ``something-minus-one'' in the target formula.
26189
26190A successful way to write this would be @samp{f(x, x+2) := g(x+1)}.
26191You could make this resemble the original form more closely by using
26192@code{let} notation, which is described in the next section:
26193
26194@example
26195f(xm1, x+1) := g(x) :: let(x := xm1+1)
26196@end example
26197
26198Calc does this rewriting or ``conditionalizing'' for any sub-pattern
26199which involves only the functions in the following list, operating
26200only on constants and meta-variables which have already been matched
26201elsewhere in the pattern. When matching a function call, Calc is
26202careful to match arguments which are plain variables before arguments
26203which are calls to any of the functions below, so that a pattern like
26204@samp{f(x-1, x)} can be conditionalized even though the isolated
26205@samp{x} comes after the @samp{x-1}.
26206
26207@smallexample
26208+ - * / \ % ^ abs sign round rounde roundu trunc floor ceil
26209max min re im conj arg
26210@end smallexample
26211
26212You can suppress all of the special treatments described in this
26213section by surrounding a function call with a @code{plain} marker.
26214This marker causes the function call which is its argument to be
26215matched literally, without regard to commutativity, associativity,
26216negation, or conditionalization. When you use @code{plain}, the
26217``deep structure'' of the formula being matched can show through.
26218For example,
26219
26220@example
26221plain(a - a b) := f(a, b)
26222@end example
26223
26224@noindent
26225will match only literal subtractions. However, the @code{plain}
26226marker does not affect its arguments' arguments. In this case,
26227commutativity and associativity is still considered while matching
26228the @w{@samp{a b}} sub-pattern, so the whole pattern will match
26229@samp{x - y x} as well as @samp{x - x y}. We could go still
26230further and use
26231
26232@example
26233plain(a - plain(a b)) := f(a, b)
26234@end example
26235
26236@noindent
26237which would do a completely strict match for the pattern.
26238
26239By contrast, the @code{quote} marker means that not only the
26240function name but also the arguments must be literally the same.
26241The above pattern will match @samp{x - x y} but
26242
26243@example
26244quote(a - a b) := f(a, b)
26245@end example
26246
26247@noindent
26248will match only the single formula @samp{a - a b}. Also,
26249
26250@example
26251quote(a - quote(a b)) := f(a, b)
26252@end example
26253
26254@noindent
26255will match only @samp{a - quote(a b)}---probably not the desired
26256effect!
26257
26258A certain amount of algebra is also done when substituting the
26259meta-variables on the righthand side of a rule. For example,
26260in the rule
26261
26262@example
26263a + f(b) := f(a + b)
26264@end example
26265
26266@noindent
26267matching @samp{f(x) - y} would produce @samp{f((-y) + x)} if
26268taken literally, but the rewrite mechanism will simplify the
26269righthand side to @samp{f(x - y)} automatically. (Of course,
26270the default simplifications would do this anyway, so this
26271special simplification is only noticeable if you have turned the
26272default simplifications off.) This rewriting is done only when
26273a meta-variable expands to a ``negative-looking'' expression.
26274If this simplification is not desirable, you can use a @code{plain}
26275marker on the righthand side:
26276
26277@example
26278a + f(b) := f(plain(a + b))
26279@end example
26280
26281@noindent
26282In this example, we are still allowing the pattern-matcher to
26283use all the algebra it can muster, but the righthand side will
26284always simplify to a literal addition like @samp{f((-y) + x)}.
26285
26286@node Other Features of Rewrite Rules, Composing Patterns in Rewrite Rules, Algebraic Properties of Rewrite Rules, Rewrite Rules
26287@subsection Other Features of Rewrite Rules
26288
26289@noindent
26290Certain ``function names'' serve as markers in rewrite rules.
26291Here is a complete list of these markers. First are listed the
26292markers that work inside a pattern; then come the markers that
26293work in the righthand side of a rule.
26294
26295@ignore
26296@starindex
26297@end ignore
26298@tindex import
26299One kind of marker, @samp{import(x)}, takes the place of a whole
26300rule. Here @expr{x} is the name of a variable containing another
26301rule set; those rules are ``spliced into'' the rule set that
26302imports them. For example, if @samp{[f(a+b) := f(a) + f(b),
26303f(a b) := a f(b) :: real(a)]} is stored in variable @samp{linearF},
26304then the rule set @samp{[f(0) := 0, import(linearF)]} will apply
26305all three rules. It is possible to modify the imported rules
26306slightly: @samp{import(x, v1, x1, v2, x2, @dots{})} imports
26307the rule set @expr{x} with all occurrences of
26308@texline @math{v_1},
26309@infoline @expr{v1},
26310as either a variable name or a function name, replaced with
26311@texline @math{x_1}
26312@infoline @expr{x1}
26313and so on. (If
26314@texline @math{v_1}
26315@infoline @expr{v1}
26316is used as a function name, then
26317@texline @math{x_1}
26318@infoline @expr{x1}
26319must be either a function name itself or a @w{@samp{< >}} nameless
26320function; @pxref{Specifying Operators}.) For example, @samp{[g(0) := 0,
26321import(linearF, f, g)]} applies the linearity rules to the function
26322@samp{g} instead of @samp{f}. Imports can be nested, but the
26323import-with-renaming feature may fail to rename sub-imports properly.
26324
26325The special functions allowed in patterns are:
26326
26327@table @samp
26328@item quote(x)
26329@ignore
26330@starindex
26331@end ignore
26332@tindex quote
26333This pattern matches exactly @expr{x}; variable names in @expr{x} are
26334not interpreted as meta-variables. The only flexibility is that
26335numbers are compared for numeric equality, so that the pattern
26336@samp{f(quote(12))} will match both @samp{f(12)} and @samp{f(12.0)}.
26337(Numbers are always treated this way by the rewrite mechanism:
26338The rule @samp{f(x,x) := g(x)} will match @samp{f(12, 12.0)}.
26339The rewrite may produce either @samp{g(12)} or @samp{g(12.0)}
26340as a result in this case.)
26341
26342@item plain(x)
26343@ignore
26344@starindex
26345@end ignore
26346@tindex plain
26347Here @expr{x} must be a function call @samp{f(x1,x2,@dots{})}. This
26348pattern matches a call to function @expr{f} with the specified
26349argument patterns. No special knowledge of the properties of the
26350function @expr{f} is used in this case; @samp{+} is not commutative or
26351associative. Unlike @code{quote}, the arguments @samp{x1,x2,@dots{}}
26352are treated as patterns. If you wish them to be treated ``plainly''
26353as well, you must enclose them with more @code{plain} markers:
26354@samp{plain(plain(@w{-a}) + plain(b c))}.
26355
26356@item opt(x,def)
26357@ignore
26358@starindex
26359@end ignore
26360@tindex opt
26361Here @expr{x} must be a variable name. This must appear as an
26362argument to a function or an element of a vector; it specifies that
26363the argument or element is optional.
26364As an argument to @samp{+}, @samp{-}, @samp{*}, @samp{&&}, or @samp{||},
26365or as the second argument to @samp{/} or @samp{^}, the value @var{def}
26366may be omitted. The pattern @samp{x + opt(y)} matches a sum by
26367binding one summand to @expr{x} and the other to @expr{y}, and it
26368matches anything else by binding the whole expression to @expr{x} and
26369zero to @expr{y}. The other operators above work similarly.
26370
26371For general miscellaneous functions, the default value @code{def}
26372must be specified. Optional arguments are dropped starting with
26373the rightmost one during matching. For example, the pattern
26374@samp{f(opt(a,0), b, opt(c,b))} will match @samp{f(b)}, @samp{f(a,b)},
26375or @samp{f(a,b,c)}. Default values of zero and @expr{b} are
26376supplied in this example for the omitted arguments. Note that
26377the literal variable @expr{b} will be the default in the latter
26378case, @emph{not} the value that matched the meta-variable @expr{b}.
26379In other words, the default @var{def} is effectively quoted.
26380
26381@item condition(x,c)
26382@ignore
26383@starindex
26384@end ignore
26385@tindex condition
26386@tindex ::
26387This matches the pattern @expr{x}, with the attached condition
26388@expr{c}. It is the same as @samp{x :: c}.
26389
26390@item pand(x,y)
26391@ignore
26392@starindex
26393@end ignore
26394@tindex pand
26395@tindex &&&
26396This matches anything that matches both pattern @expr{x} and
26397pattern @expr{y}. It is the same as @samp{x &&& y}.
26398@pxref{Composing Patterns in Rewrite Rules}.
26399
26400@item por(x,y)
26401@ignore
26402@starindex
26403@end ignore
26404@tindex por
26405@tindex |||
26406This matches anything that matches either pattern @expr{x} or
26407pattern @expr{y}. It is the same as @w{@samp{x ||| y}}.
26408
26409@item pnot(x)
26410@ignore
26411@starindex
26412@end ignore
26413@tindex pnot
26414@tindex !!!
26415This matches anything that does not match pattern @expr{x}.
26416It is the same as @samp{!!! x}.
26417
26418@item cons(h,t)
26419@ignore
26420@mindex cons
26421@end ignore
26422@tindex cons (rewrites)
26423This matches any vector of one or more elements. The first
26424element is matched to @expr{h}; a vector of the remaining
26425elements is matched to @expr{t}. Note that vectors of fixed
26426length can also be matched as actual vectors: The rule
26427@samp{cons(a,cons(b,[])) := cons(a+b,[])} is equivalent
26428to the rule @samp{[a,b] := [a+b]}.
26429
26430@item rcons(t,h)
26431@ignore
26432@mindex rcons
26433@end ignore
26434@tindex rcons (rewrites)
26435This is like @code{cons}, except that the @emph{last} element
26436is matched to @expr{h}, with the remaining elements matched
26437to @expr{t}.
26438
26439@item apply(f,args)
26440@ignore
26441@mindex apply
26442@end ignore
26443@tindex apply (rewrites)
26444This matches any function call. The name of the function, in
26445the form of a variable, is matched to @expr{f}. The arguments
26446of the function, as a vector of zero or more objects, are
26447matched to @samp{args}. Constants, variables, and vectors
26448do @emph{not} match an @code{apply} pattern. For example,
26449@samp{apply(f,x)} matches any function call, @samp{apply(quote(f),x)}
26450matches any call to the function @samp{f}, @samp{apply(f,[a,b])}
26451matches any function call with exactly two arguments, and
26452@samp{apply(quote(f), cons(a,cons(b,x)))} matches any call
26453to the function @samp{f} with two or more arguments. Another
26454way to implement the latter, if the rest of the rule does not
26455need to refer to the first two arguments of @samp{f} by name,
26456would be @samp{apply(quote(f), x :: vlen(x) >= 2)}.
26457Here's a more interesting sample use of @code{apply}:
26458
26459@example
26460apply(f,[x+n]) := n + apply(f,[x])
26461 :: in(f, [floor,ceil,round,trunc]) :: integer(n)
26462@end example
26463
26464Note, however, that this will be slower to match than a rule
26465set with four separate rules. The reason is that Calc sorts
26466the rules of a rule set according to top-level function name;
26467if the top-level function is @code{apply}, Calc must try the
26468rule for every single formula and sub-formula. If the top-level
26469function in the pattern is, say, @code{floor}, then Calc invokes
26470the rule only for sub-formulas which are calls to @code{floor}.
26471
26472Formulas normally written with operators like @code{+} are still
26473considered function calls: @code{apply(f,x)} matches @samp{a+b}
26474with @samp{f = add}, @samp{x = [a,b]}.
26475
26476You must use @code{apply} for meta-variables with function names
26477on both sides of a rewrite rule: @samp{apply(f, [x]) := f(x+1)}
26478is @emph{not} correct, because it rewrites @samp{spam(6)} into
26479@samp{f(7)}. The righthand side should be @samp{apply(f, [x+1])}.
26480Also note that you will have to use No-Simplify mode (@kbd{m O})
26481when entering this rule so that the @code{apply} isn't
26482evaluated immediately to get the new rule @samp{f(x) := f(x+1)}.
26483Or, use @kbd{s e} to enter the rule without going through the stack,
26484or enter the rule as @samp{apply(f, [x]) := apply(f, [x+1]) @w{:: 1}}.
26485@xref{Conditional Rewrite Rules}.
26486
26487@item select(x)
26488@ignore
26489@starindex
26490@end ignore
26491@tindex select
26492This is used for applying rules to formulas with selections;
26493@pxref{Selections with Rewrite Rules}.
26494@end table
26495
26496Special functions for the righthand sides of rules are:
26497
26498@table @samp
26499@item quote(x)
26500The notation @samp{quote(x)} is changed to @samp{x} when the
26501righthand side is used. As far as the rewrite rule is concerned,
26502@code{quote} is invisible. However, @code{quote} has the special
26503property in Calc that its argument is not evaluated. Thus,
26504while it will not work to put the rule @samp{t(a) := typeof(a)}
26505on the stack because @samp{typeof(a)} is evaluated immediately
26506to produce @samp{t(a) := 100}, you can use @code{quote} to
26507protect the righthand side: @samp{t(a) := quote(typeof(a))}.
26508(@xref{Conditional Rewrite Rules}, for another trick for
26509protecting rules from evaluation.)
26510
26511@item plain(x)
26512Special properties of and simplifications for the function call
26513@expr{x} are not used. One interesting case where @code{plain}
26514is useful is the rule, @samp{q(x) := quote(x)}, trying to expand a
26515shorthand notation for the @code{quote} function. This rule will
26516not work as shown; instead of replacing @samp{q(foo)} with
26517@samp{quote(foo)}, it will replace it with @samp{foo}! The correct
26518rule would be @samp{q(x) := plain(quote(x))}.
26519
26520@item cons(h,t)
26521Where @expr{t} is a vector, this is converted into an expanded
26522vector during rewrite processing. Note that @code{cons} is a regular
26523Calc function which normally does this anyway; the only way @code{cons}
26524is treated specially by rewrites is that @code{cons} on the righthand
26525side of a rule will be evaluated even if default simplifications
26526have been turned off.
26527
26528@item rcons(t,h)
26529Analogous to @code{cons} except putting @expr{h} at the @emph{end} of
26530the vector @expr{t}.
26531
26532@item apply(f,args)
26533Where @expr{f} is a variable and @var{args} is a vector, this
26534is converted to a function call. Once again, note that @code{apply}
26535is also a regular Calc function.
26536
26537@item eval(x)
26538@ignore
26539@starindex
26540@end ignore
26541@tindex eval
26542The formula @expr{x} is handled in the usual way, then the
26543default simplifications are applied to it even if they have
26544been turned off normally. This allows you to treat any function
26545similarly to the way @code{cons} and @code{apply} are always
26546treated. However, there is a slight difference: @samp{cons(2+3, [])}
26547with default simplifications off will be converted to @samp{[2+3]},
26548whereas @samp{eval(cons(2+3, []))} will be converted to @samp{[5]}.
26549
26550@item evalsimp(x)
26551@ignore
26552@starindex
26553@end ignore
26554@tindex evalsimp
26555The formula @expr{x} has meta-variables substituted in the usual
26556way, then algebraically simplified as if by the @kbd{a s} command.
26557
26558@item evalextsimp(x)
26559@ignore
26560@starindex
26561@end ignore
26562@tindex evalextsimp
26563The formula @expr{x} has meta-variables substituted in the normal
26564way, then ``extendedly'' simplified as if by the @kbd{a e} command.
26565
26566@item select(x)
26567@xref{Selections with Rewrite Rules}.
26568@end table
26569
26570There are also some special functions you can use in conditions.
26571
26572@table @samp
26573@item let(v := x)
26574@ignore
26575@starindex
26576@end ignore
26577@tindex let
26578The expression @expr{x} is evaluated with meta-variables substituted.
26579The @kbd{a s} command's simplifications are @emph{not} applied by
26580default, but @expr{x} can include calls to @code{evalsimp} or
26581@code{evalextsimp} as described above to invoke higher levels
26582of simplification. The
26583result of @expr{x} is then bound to the meta-variable @expr{v}. As
26584usual, if this meta-variable has already been matched to something
26585else the two values must be equal; if the meta-variable is new then
26586it is bound to the result of the expression. This variable can then
26587appear in later conditions, and on the righthand side of the rule.
26588In fact, @expr{v} may be any pattern in which case the result of
26589evaluating @expr{x} is matched to that pattern, binding any
26590meta-variables that appear in that pattern. Note that @code{let}
26591can only appear by itself as a condition, or as one term of an
26592@samp{&&} which is a whole condition: It cannot be inside
26593an @samp{||} term or otherwise buried.
26594
26595The alternate, equivalent form @samp{let(v, x)} is also recognized.
26596Note that the use of @samp{:=} by @code{let}, while still being
26597assignment-like in character, is unrelated to the use of @samp{:=}
26598in the main part of a rewrite rule.
26599
26600As an example, @samp{f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)}
26601replaces @samp{f(a)} with @samp{g} of the inverse of @samp{a}, if
26602that inverse exists and is constant. For example, if @samp{a} is a
26603singular matrix the operation @samp{1/a} is left unsimplified and
26604@samp{constant(ia)} fails, but if @samp{a} is an invertible matrix
26605then the rule succeeds. Without @code{let} there would be no way
26606to express this rule that didn't have to invert the matrix twice.
26607Note that, because the meta-variable @samp{ia} is otherwise unbound
26608in this rule, the @code{let} condition itself always ``succeeds''
26609because no matter what @samp{1/a} evaluates to, it can successfully
26610be bound to @code{ia}.
26611
26612Here's another example, for integrating cosines of linear
26613terms: @samp{myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))}.
26614The @code{lin} function returns a 3-vector if its argument is linear,
26615or leaves itself unevaluated if not. But an unevaluated @code{lin}
26616call will not match the 3-vector on the lefthand side of the @code{let},
26617so this @code{let} both verifies that @code{y} is linear, and binds
26618the coefficients @code{a} and @code{b} for use elsewhere in the rule.
26619(It would have been possible to use @samp{sin(a x + b)/b} for the
26620righthand side instead, but using @samp{sin(y)/b} avoids gratuitous
26621rearrangement of the argument of the sine.)
26622
26623@ignore
26624@starindex
26625@end ignore
26626@tindex ierf
26627Similarly, here is a rule that implements an inverse-@code{erf}
26628function. It uses @code{root} to search for a solution. If
26629@code{root} succeeds, it will return a vector of two numbers
26630where the first number is the desired solution. If no solution
26631is found, @code{root} remains in symbolic form. So we use
26632@code{let} to check that the result was indeed a vector.
26633
26634@example
26635ierf(x) := y :: let([y,z] := root(erf(a) = x, a, .5))
26636@end example
26637
26638@item matches(v,p)
26639The meta-variable @var{v}, which must already have been matched
26640to something elsewhere in the rule, is compared against pattern
26641@var{p}. Since @code{matches} is a standard Calc function, it
26642can appear anywhere in a condition. But if it appears alone or
26643as a term of a top-level @samp{&&}, then you get the special
26644extra feature that meta-variables which are bound to things
26645inside @var{p} can be used elsewhere in the surrounding rewrite
26646rule.
26647
26648The only real difference between @samp{let(p := v)} and
26649@samp{matches(v, p)} is that the former evaluates @samp{v} using
26650the default simplifications, while the latter does not.
26651
26652@item remember
26653@vindex remember
26654This is actually a variable, not a function. If @code{remember}
26655appears as a condition in a rule, then when that rule succeeds
26656the original expression and rewritten expression are added to the
26657front of the rule set that contained the rule. If the rule set
26658was not stored in a variable, @code{remember} is ignored. The
26659lefthand side is enclosed in @code{quote} in the added rule if it
26660contains any variables.
26661
26662For example, the rule @samp{f(n) := n f(n-1) :: remember} applied
26663to @samp{f(7)} will add the rule @samp{f(7) := 7 f(6)} to the front
26664of the rule set. The rule set @code{EvalRules} works slightly
26665differently: There, the evaluation of @samp{f(6)} will complete before
26666the result is added to the rule set, in this case as @samp{f(7) := 5040}.
26667Thus @code{remember} is most useful inside @code{EvalRules}.
26668
26669It is up to you to ensure that the optimization performed by
26670@code{remember} is safe. For example, the rule @samp{foo(n) := n
26671:: evalv(eatfoo) > 0 :: remember} is a bad idea (@code{evalv} is
26672the function equivalent of the @kbd{=} command); if the variable
26673@code{eatfoo} ever contains 1, rules like @samp{foo(7) := 7} will
26674be added to the rule set and will continue to operate even if
26675@code{eatfoo} is later changed to 0.
26676
26677@item remember(c)
26678@ignore
26679@starindex
26680@end ignore
26681@tindex remember
26682Remember the match as described above, but only if condition @expr{c}
26683is true. For example, @samp{remember(n % 4 = 0)} in the above factorial
26684rule remembers only every fourth result. Note that @samp{remember(1)}
26685is equivalent to @samp{remember}, and @samp{remember(0)} has no effect.
26686@end table
26687
26688@node Composing Patterns in Rewrite Rules, Nested Formulas with Rewrite Rules, Other Features of Rewrite Rules, Rewrite Rules
26689@subsection Composing Patterns in Rewrite Rules
26690
26691@noindent
26692There are three operators, @samp{&&&}, @samp{|||}, and @samp{!!!},
26693that combine rewrite patterns to make larger patterns. The
26694combinations are ``and,'' ``or,'' and ``not,'' respectively, and
26695these operators are the pattern equivalents of @samp{&&}, @samp{||}
26696and @samp{!} (which operate on zero-or-nonzero logical values).
26697
26698Note that @samp{&&&}, @samp{|||}, and @samp{!!!} are left in symbolic
26699form by all regular Calc features; they have special meaning only in
26700the context of rewrite rule patterns.
26701
26702The pattern @samp{@var{p1} &&& @var{p2}} matches anything that
26703matches both @var{p1} and @var{p2}. One especially useful case is
26704when one of @var{p1} or @var{p2} is a meta-variable. For example,
26705here is a rule that operates on error forms:
26706
26707@example
26708f(x &&& a +/- b, x) := g(x)
26709@end example
26710
26711This does the same thing, but is arguably simpler than, the rule
26712
26713@example
26714f(a +/- b, a +/- b) := g(a +/- b)
26715@end example
26716
26717@ignore
26718@starindex
26719@end ignore
26720@tindex ends
26721Here's another interesting example:
26722
26723@example
26724ends(cons(a, x) &&& rcons(y, b)) := [a, b]
26725@end example
26726
26727@noindent
26728which effectively clips out the middle of a vector leaving just
26729the first and last elements. This rule will change a one-element
26730vector @samp{[a]} to @samp{[a, a]}. The similar rule
26731
26732@example
26733ends(cons(a, rcons(y, b))) := [a, b]
26734@end example
26735
26736@noindent
26737would do the same thing except that it would fail to match a
26738one-element vector.
26739
26740@tex
26741\bigskip
26742@end tex
26743
26744The pattern @samp{@var{p1} ||| @var{p2}} matches anything that
26745matches either @var{p1} or @var{p2}. Calc first tries matching
26746against @var{p1}; if that fails, it goes on to try @var{p2}.
26747
26748@ignore
26749@starindex
26750@end ignore
26751@tindex curve
26752A simple example of @samp{|||} is
26753
26754@example
26755curve(inf ||| -inf) := 0
26756@end example
26757
26758@noindent
26759which converts both @samp{curve(inf)} and @samp{curve(-inf)} to zero.
26760
26761Here is a larger example:
26762
26763@example
26764log(a, b) ||| (ln(a) :: let(b := e)) := mylog(a, b)
26765@end example
26766
26767This matches both generalized and natural logarithms in a single rule.
26768Note that the @samp{::} term must be enclosed in parentheses because
26769that operator has lower precedence than @samp{|||} or @samp{:=}.
26770
26771(In practice this rule would probably include a third alternative,
26772omitted here for brevity, to take care of @code{log10}.)
26773
26774While Calc generally treats interior conditions exactly the same as
26775conditions on the outside of a rule, it does guarantee that if all the
26776variables in the condition are special names like @code{e}, or already
26777bound in the pattern to which the condition is attached (say, if
26778@samp{a} had appeared in this condition), then Calc will process this
26779condition right after matching the pattern to the left of the @samp{::}.
26780Thus, we know that @samp{b} will be bound to @samp{e} only if the
26781@code{ln} branch of the @samp{|||} was taken.
26782
26783Note that this rule was careful to bind the same set of meta-variables
26784on both sides of the @samp{|||}. Calc does not check this, but if
26785you bind a certain meta-variable only in one branch and then use that
26786meta-variable elsewhere in the rule, results are unpredictable:
26787
26788@example
26789f(a,b) ||| g(b) := h(a,b)
26790@end example
26791
26792Here if the pattern matches @samp{g(17)}, Calc makes no promises about
26793the value that will be substituted for @samp{a} on the righthand side.
26794
26795@tex
26796\bigskip
26797@end tex
26798
26799The pattern @samp{!!! @var{pat}} matches anything that does not
26800match @var{pat}. Any meta-variables that are bound while matching
26801@var{pat} remain unbound outside of @var{pat}.
26802
26803For example,
26804
26805@example
26806f(x &&& !!! a +/- b, !!![]) := g(x)
26807@end example
26808
26809@noindent
26810converts @code{f} whose first argument is anything @emph{except} an
26811error form, and whose second argument is not the empty vector, into
26812a similar call to @code{g} (but without the second argument).
26813
26814If we know that the second argument will be a vector (empty or not),
26815then an equivalent rule would be:
26816
26817@example
26818f(x, y) := g(x) :: typeof(x) != 7 :: vlen(y) > 0
26819@end example
26820
26821@noindent
26822where of course 7 is the @code{typeof} code for error forms.
26823Another final condition, that works for any kind of @samp{y},
26824would be @samp{!istrue(y == [])}. (The @code{istrue} function
26825returns an explicit 0 if its argument was left in symbolic form;
26826plain @samp{!(y == [])} or @samp{y != []} would not work to replace
26827@samp{!!![]} since these would be left unsimplified, and thus cause
26828the rule to fail, if @samp{y} was something like a variable name.)
26829
26830It is possible for a @samp{!!!} to refer to meta-variables bound
26831elsewhere in the pattern. For example,
26832
26833@example
26834f(a, !!!a) := g(a)
26835@end example
26836
26837@noindent
26838matches any call to @code{f} with different arguments, changing
26839this to @code{g} with only the first argument.
26840
26841If a function call is to be matched and one of the argument patterns
26842contains a @samp{!!!} somewhere inside it, that argument will be
26843matched last. Thus
26844
26845@example
26846f(!!!a, a) := g(a)
26847@end example
26848
26849@noindent
26850will be careful to bind @samp{a} to the second argument of @code{f}
26851before testing the first argument. If Calc had tried to match the
26852first argument of @code{f} first, the results would have been
26853disastrous: since @code{a} was unbound so far, the pattern @samp{a}
26854would have matched anything at all, and the pattern @samp{!!!a}
26855therefore would @emph{not} have matched anything at all!
26856
26857@node Nested Formulas with Rewrite Rules, Multi-Phase Rewrite Rules, Composing Patterns in Rewrite Rules, Rewrite Rules
26858@subsection Nested Formulas with Rewrite Rules
26859
26860@noindent
26861When @kbd{a r} (@code{calc-rewrite}) is used, it takes an expression from
26862the top of the stack and attempts to match any of the specified rules
26863to any part of the expression, starting with the whole expression
26864and then, if that fails, trying deeper and deeper sub-expressions.
26865For each part of the expression, the rules are tried in the order
26866they appear in the rules vector. The first rule to match the first
26867sub-expression wins; it replaces the matched sub-expression according
26868to the @var{new} part of the rule.
26869
26870Often, the rule set will match and change the formula several times.
26871The top-level formula is first matched and substituted repeatedly until
26872it no longer matches the pattern; then, sub-formulas are tried, and
26873so on. Once every part of the formula has gotten its chance, the
26874rewrite mechanism starts over again with the top-level formula
26875(in case a substitution of one of its arguments has caused it again
26876to match). This continues until no further matches can be made
26877anywhere in the formula.
26878
26879It is possible for a rule set to get into an infinite loop. The
26880most obvious case, replacing a formula with itself, is not a problem
26881because a rule is not considered to ``succeed'' unless the righthand
26882side actually comes out to something different than the original
26883formula or sub-formula that was matched. But if you accidentally
26884had both @samp{ln(a b) := ln(a) + ln(b)} and the reverse
26885@samp{ln(a) + ln(b) := ln(a b)} in your rule set, Calc would
26886run forever switching a formula back and forth between the two
26887forms.
26888
26889To avoid disaster, Calc normally stops after 100 changes have been
26890made to the formula. This will be enough for most multiple rewrites,
26891but it will keep an endless loop of rewrites from locking up the
26892computer forever. (On most systems, you can also type @kbd{C-g} to
26893halt any Emacs command prematurely.)
26894
26895To change this limit, give a positive numeric prefix argument.
26896In particular, @kbd{M-1 a r} applies only one rewrite at a time,
26897useful when you are first testing your rule (or just if repeated
26898rewriting is not what is called for by your application).
26899
26900@ignore
26901@starindex
26902@end ignore
26903@ignore
26904@mindex iter@idots
26905@end ignore
26906@tindex iterations
26907You can also put a ``function call'' @samp{iterations(@var{n})}
26908in place of a rule anywhere in your rules vector (but usually at
26909the top). Then, @var{n} will be used instead of 100 as the default
26910number of iterations for this rule set. You can use
26911@samp{iterations(inf)} if you want no iteration limit by default.
26912A prefix argument will override the @code{iterations} limit in the
26913rule set.
26914
26915@example
26916[ iterations(1),
26917 f(x) := f(x+1) ]
26918@end example
26919
26920More precisely, the limit controls the number of ``iterations,''
26921where each iteration is a successful matching of a rule pattern whose
26922righthand side, after substituting meta-variables and applying the
26923default simplifications, is different from the original sub-formula
26924that was matched.
26925
26926A prefix argument of zero sets the limit to infinity. Use with caution!
26927
26928Given a negative numeric prefix argument, @kbd{a r} will match and
26929substitute the top-level expression up to that many times, but
26930will not attempt to match the rules to any sub-expressions.
26931
26932In a formula, @code{rewrite(@var{expr}, @var{rules}, @var{n})}
26933does a rewriting operation. Here @var{expr} is the expression
26934being rewritten, @var{rules} is the rule, vector of rules, or
26935variable containing the rules, and @var{n} is the optional
26936iteration limit, which may be a positive integer, a negative
26937integer, or @samp{inf} or @samp{-inf}. If @var{n} is omitted
26938the @code{iterations} value from the rule set is used; if both
26939are omitted, 100 is used.
26940
26941@node Multi-Phase Rewrite Rules, Selections with Rewrite Rules, Nested Formulas with Rewrite Rules, Rewrite Rules
26942@subsection Multi-Phase Rewrite Rules
26943
26944@noindent
26945It is possible to separate a rewrite rule set into several @dfn{phases}.
26946During each phase, certain rules will be enabled while certain others
26947will be disabled. A @dfn{phase schedule} controls the order in which
26948phases occur during the rewriting process.
26949
26950@ignore
26951@starindex
26952@end ignore
26953@tindex phase
26954@vindex all
26955If a call to the marker function @code{phase} appears in the rules
26956vector in place of a rule, all rules following that point will be
26957members of the phase(s) identified in the arguments to @code{phase}.
26958Phases are given integer numbers. The markers @samp{phase()} and
26959@samp{phase(all)} both mean the following rules belong to all phases;
26960this is the default at the start of the rule set.
26961
26962If you do not explicitly schedule the phases, Calc sorts all phase
26963numbers that appear in the rule set and executes the phases in
26964ascending order. For example, the rule set
26965
26966@example
26967@group
26968[ f0(x) := g0(x),
26969 phase(1),
26970 f1(x) := g1(x),
26971 phase(2),
26972 f2(x) := g2(x),
26973 phase(3),
26974 f3(x) := g3(x),
26975 phase(1,2),
26976 f4(x) := g4(x) ]
26977@end group
26978@end example
26979
26980@noindent
26981has three phases, 1 through 3. Phase 1 consists of the @code{f0},
26982@code{f1}, and @code{f4} rules (in that order). Phase 2 consists of
26983@code{f0}, @code{f2}, and @code{f4}. Phase 3 consists of @code{f0}
26984and @code{f3}.
26985
26986When Calc rewrites a formula using this rule set, it first rewrites
26987the formula using only the phase 1 rules until no further changes are
26988possible. Then it switches to the phase 2 rule set and continues
26989until no further changes occur, then finally rewrites with phase 3.
26990When no more phase 3 rules apply, rewriting finishes. (This is
26991assuming @kbd{a r} with a large enough prefix argument to allow the
26992rewriting to run to completion; the sequence just described stops
26993early if the number of iterations specified in the prefix argument,
26994100 by default, is reached.)
26995
26996During each phase, Calc descends through the nested levels of the
26997formula as described previously. (@xref{Nested Formulas with Rewrite
26998Rules}.) Rewriting starts at the top of the formula, then works its
26999way down to the parts, then goes back to the top and works down again.
27000The phase 2 rules do not begin until no phase 1 rules apply anywhere
27001in the formula.
27002
27003@ignore
27004@starindex
27005@end ignore
27006@tindex schedule
27007A @code{schedule} marker appearing in the rule set (anywhere, but
27008conventionally at the top) changes the default schedule of phases.
27009In the simplest case, @code{schedule} has a sequence of phase numbers
27010for arguments; each phase number is invoked in turn until the
27011arguments to @code{schedule} are exhausted. Thus adding
27012@samp{schedule(3,2,1)} at the top of the above rule set would
27013reverse the order of the phases; @samp{schedule(1,2,3)} would have
27014no effect since this is the default schedule; and @samp{schedule(1,2,1,3)}
27015would give phase 1 a second chance after phase 2 has completed, before
27016moving on to phase 3.
27017
27018Any argument to @code{schedule} can instead be a vector of phase
27019numbers (or even of sub-vectors). Then the sub-sequence of phases
27020described by the vector are tried repeatedly until no change occurs
27021in any phase in the sequence. For example, @samp{schedule([1, 2], 3)}
27022tries phase 1, then phase 2, then, if either phase made any changes
27023to the formula, repeats these two phases until they can make no
27024further progress. Finally, it goes on to phase 3 for finishing
27025touches.
27026
27027Also, items in @code{schedule} can be variable names as well as
27028numbers. A variable name is interpreted as the name of a function
27029to call on the whole formula. For example, @samp{schedule(1, simplify)}
27030says to apply the phase-1 rules (presumably, all of them), then to
27031call @code{simplify} which is the function name equivalent of @kbd{a s}.
27032Likewise, @samp{schedule([1, simplify])} says to alternate between
27033phase 1 and @kbd{a s} until no further changes occur.
27034
27035Phases can be used purely to improve efficiency; if it is known that
27036a certain group of rules will apply only at the beginning of rewriting,
27037and a certain other group will apply only at the end, then rewriting
27038will be faster if these groups are identified as separate phases.
27039Once the phase 1 rules are done, Calc can put them aside and no longer
27040spend any time on them while it works on phase 2.
27041
27042There are also some problems that can only be solved with several
27043rewrite phases. For a real-world example of a multi-phase rule set,
27044examine the set @code{FitRules}, which is used by the curve-fitting
27045command to convert a model expression to linear form.
27046@xref{Curve Fitting Details}. This set is divided into four phases.
27047The first phase rewrites certain kinds of expressions to be more
27048easily linearizable, but less computationally efficient. After the
27049linear components have been picked out, the final phase includes the
27050opposite rewrites to put each component back into an efficient form.
27051If both sets of rules were included in one big phase, Calc could get
27052into an infinite loop going back and forth between the two forms.
27053
27054Elsewhere in @code{FitRules}, the components are first isolated,
27055then recombined where possible to reduce the complexity of the linear
27056fit, then finally packaged one component at a time into vectors.
27057If the packaging rules were allowed to begin before the recombining
27058rules were finished, some components might be put away into vectors
27059before they had a chance to recombine. By putting these rules in
27060two separate phases, this problem is neatly avoided.
27061
27062@node Selections with Rewrite Rules, Matching Commands, Multi-Phase Rewrite Rules, Rewrite Rules
27063@subsection Selections with Rewrite Rules
27064
27065@noindent
27066If a sub-formula of the current formula is selected (as by @kbd{j s};
27067@pxref{Selecting Subformulas}), the @kbd{a r} (@code{calc-rewrite})
27068command applies only to that sub-formula. Together with a negative
27069prefix argument, you can use this fact to apply a rewrite to one
27070specific part of a formula without affecting any other parts.
27071
27072@kindex j r
27073@pindex calc-rewrite-selection
27074The @kbd{j r} (@code{calc-rewrite-selection}) command allows more
27075sophisticated operations on selections. This command prompts for
27076the rules in the same way as @kbd{a r}, but it then applies those
27077rules to the whole formula in question even though a sub-formula
27078of it has been selected. However, the selected sub-formula will
27079first have been surrounded by a @samp{select( )} function call.
27080(Calc's evaluator does not understand the function name @code{select};
27081this is only a tag used by the @kbd{j r} command.)
27082
27083For example, suppose the formula on the stack is @samp{2 (a + b)^2}
27084and the sub-formula @samp{a + b} is selected. This formula will
27085be rewritten to @samp{2 select(a + b)^2} and then the rewrite
27086rules will be applied in the usual way. The rewrite rules can
27087include references to @code{select} to tell where in the pattern
27088the selected sub-formula should appear.
27089
27090If there is still exactly one @samp{select( )} function call in
27091the formula after rewriting is done, it indicates which part of
27092the formula should be selected afterwards. Otherwise, the
27093formula will be unselected.
27094
27095You can make @kbd{j r} act much like @kbd{a r} by enclosing both parts
27096of the rewrite rule with @samp{select()}. However, @kbd{j r}
27097allows you to use the current selection in more flexible ways.
27098Suppose you wished to make a rule which removed the exponent from
27099the selected term; the rule @samp{select(a)^x := select(a)} would
27100work. In the above example, it would rewrite @samp{2 select(a + b)^2}
27101to @samp{2 select(a + b)}. This would then be returned to the
27102stack as @samp{2 (a + b)} with the @samp{a + b} selected.
27103
27104The @kbd{j r} command uses one iteration by default, unlike
27105@kbd{a r} which defaults to 100 iterations. A numeric prefix
27106argument affects @kbd{j r} in the same way as @kbd{a r}.
27107@xref{Nested Formulas with Rewrite Rules}.
27108
27109As with other selection commands, @kbd{j r} operates on the stack
27110entry that contains the cursor. (If the cursor is on the top-of-stack
27111@samp{.} marker, it works as if the cursor were on the formula
27112at stack level 1.)
27113
27114If you don't specify a set of rules, the rules are taken from the
27115top of the stack, just as with @kbd{a r}. In this case, the
27116cursor must indicate stack entry 2 or above as the formula to be
27117rewritten (otherwise the same formula would be used as both the
27118target and the rewrite rules).
27119
27120If the indicated formula has no selection, the cursor position within
27121the formula temporarily selects a sub-formula for the purposes of this
27122command. If the cursor is not on any sub-formula (e.g., it is in
27123the line-number area to the left of the formula), the @samp{select( )}
27124markers are ignored by the rewrite mechanism and the rules are allowed
27125to apply anywhere in the formula.
27126
27127As a special feature, the normal @kbd{a r} command also ignores
27128@samp{select( )} calls in rewrite rules. For example, if you used the
27129above rule @samp{select(a)^x := select(a)} with @kbd{a r}, it would apply
27130the rule as if it were @samp{a^x := a}. Thus, you can write general
27131purpose rules with @samp{select( )} hints inside them so that they
27132will ``do the right thing'' in both @kbd{a r} and @kbd{j r},
27133both with and without selections.
27134
27135@node Matching Commands, Automatic Rewrites, Selections with Rewrite Rules, Rewrite Rules
27136@subsection Matching Commands
27137
27138@noindent
27139@kindex a m
27140@pindex calc-match
27141@tindex match
27142The @kbd{a m} (@code{calc-match}) [@code{match}] function takes a
27143vector of formulas and a rewrite-rule-style pattern, and produces
27144a vector of all formulas which match the pattern. The command
27145prompts you to enter the pattern; as for @kbd{a r}, you can enter
27146a single pattern (i.e., a formula with meta-variables), or a
27147vector of patterns, or a variable which contains patterns, or
27148you can give a blank response in which case the patterns are taken
27149from the top of the stack. The pattern set will be compiled once
27150and saved if it is stored in a variable. If there are several
27151patterns in the set, vector elements are kept if they match any
27152of the patterns.
27153
27154For example, @samp{match(a+b, [x, x+y, x-y, 7, x+y+z])}
27155will return @samp{[x+y, x-y, x+y+z]}.
27156
27157The @code{import} mechanism is not available for pattern sets.
27158
27159The @kbd{a m} command can also be used to extract all vector elements
27160which satisfy any condition: The pattern @samp{x :: x>0} will select
27161all the positive vector elements.
27162
27163@kindex I a m
27164@tindex matchnot
27165With the Inverse flag [@code{matchnot}], this command extracts all
27166vector elements which do @emph{not} match the given pattern.
27167
27168@ignore
27169@starindex
27170@end ignore
27171@tindex matches
27172There is also a function @samp{matches(@var{x}, @var{p})} which
27173evaluates to 1 if expression @var{x} matches pattern @var{p}, or
27174to 0 otherwise. This is sometimes useful for including into the
27175conditional clauses of other rewrite rules.
27176
27177@ignore
27178@starindex
27179@end ignore
27180@tindex vmatches
27181The function @code{vmatches} is just like @code{matches}, except
27182that if the match succeeds it returns a vector of assignments to
27183the meta-variables instead of the number 1. For example,
27184@samp{vmatches(f(1,2), f(a,b))} returns @samp{[a := 1, b := 2]}.
27185If the match fails, the function returns the number 0.
27186
27187@node Automatic Rewrites, Debugging Rewrites, Matching Commands, Rewrite Rules
27188@subsection Automatic Rewrites
27189
27190@noindent
27191@cindex @code{EvalRules} variable
27192@vindex EvalRules
27193It is possible to get Calc to apply a set of rewrite rules on all
27194results, effectively adding to the built-in set of default
27195simplifications. To do this, simply store your rule set in the
27196variable @code{EvalRules}. There is a convenient @kbd{s E} command
27197for editing @code{EvalRules}; @pxref{Operations on Variables}.
27198
27199For example, suppose you want @samp{sin(a + b)} to be expanded out
27200to @samp{sin(b) cos(a) + cos(b) sin(a)} wherever it appears, and
27201similarly for @samp{cos(a + b)}. The corresponding rewrite rule
27202set would be,
27203
27204@smallexample
27205@group
27206[ sin(a + b) := cos(a) sin(b) + sin(a) cos(b),
27207 cos(a + b) := cos(a) cos(b) - sin(a) sin(b) ]
27208@end group
27209@end smallexample
27210
27211To apply these manually, you could put them in a variable called
27212@code{trigexp} and then use @kbd{a r trigexp} every time you wanted
27213to expand trig functions. But if instead you store them in the
27214variable @code{EvalRules}, they will automatically be applied to all
27215sines and cosines of sums. Then, with @samp{2 x} and @samp{45} on
27216the stack, typing @kbd{+ S} will (assuming Degrees mode) result in
27217@samp{0.7071 sin(2 x) + 0.7071 cos(2 x)} automatically.
27218
27219As each level of a formula is evaluated, the rules from
27220@code{EvalRules} are applied before the default simplifications.
27221Rewriting continues until no further @code{EvalRules} apply.
27222Note that this is different from the usual order of application of
27223rewrite rules: @code{EvalRules} works from the bottom up, simplifying
27224the arguments to a function before the function itself, while @kbd{a r}
27225applies rules from the top down.
27226
27227Because the @code{EvalRules} are tried first, you can use them to
27228override the normal behavior of any built-in Calc function.
27229
27230It is important not to write a rule that will get into an infinite
27231loop. For example, the rule set @samp{[f(0) := 1, f(n) := n f(n-1)]}
27232appears to be a good definition of a factorial function, but it is
27233unsafe. Imagine what happens if @samp{f(2.5)} is simplified. Calc
27234will continue to subtract 1 from this argument forever without reaching
27235zero. A safer second rule would be @samp{f(n) := n f(n-1) :: n>0}.
27236Another dangerous rule is @samp{g(x, y) := g(y, x)}. Rewriting
27237@samp{g(2, 4)}, this would bounce back and forth between that and
27238@samp{g(4, 2)} forever. If an infinite loop in @code{EvalRules}
27239occurs, Emacs will eventually stop with a ``Computation got stuck
27240or ran too long'' message.
27241
27242Another subtle difference between @code{EvalRules} and regular rewrites
27243concerns rules that rewrite a formula into an identical formula. For
27244example, @samp{f(n) := f(floor(n))} ``fails to match'' when @expr{n} is
27245already an integer. But in @code{EvalRules} this case is detected only
27246if the righthand side literally becomes the original formula before any
27247further simplification. This means that @samp{f(n) := f(floor(n))} will
27248get into an infinite loop if it occurs in @code{EvalRules}. Calc will
27249replace @samp{f(6)} with @samp{f(floor(6))}, which is different from
27250@samp{f(6)}, so it will consider the rule to have matched and will
27251continue simplifying that formula; first the argument is simplified
27252to get @samp{f(6)}, then the rule matches again to get @samp{f(floor(6))}
27253again, ad infinitum. A much safer rule would check its argument first,
27254say, with @samp{f(n) := f(floor(n)) :: !dint(n)}.
27255
27256(What really happens is that the rewrite mechanism substitutes the
27257meta-variables in the righthand side of a rule, compares to see if the
27258result is the same as the original formula and fails if so, then uses
27259the default simplifications to simplify the result and compares again
27260(and again fails if the formula has simplified back to its original
27261form). The only special wrinkle for the @code{EvalRules} is that the
27262same rules will come back into play when the default simplifications
27263are used. What Calc wants to do is build @samp{f(floor(6))}, see that
27264this is different from the original formula, simplify to @samp{f(6)},
27265see that this is the same as the original formula, and thus halt the
27266rewriting. But while simplifying, @samp{f(6)} will again trigger
27267the same @code{EvalRules} rule and Calc will get into a loop inside
27268the rewrite mechanism itself.)
27269
27270The @code{phase}, @code{schedule}, and @code{iterations} markers do
27271not work in @code{EvalRules}. If the rule set is divided into phases,
27272only the phase 1 rules are applied, and the schedule is ignored.
27273The rules are always repeated as many times as possible.
27274
27275The @code{EvalRules} are applied to all function calls in a formula,
27276but not to numbers (and other number-like objects like error forms),
27277nor to vectors or individual variable names. (Though they will apply
27278to @emph{components} of vectors and error forms when appropriate.) You
27279might try to make a variable @code{phihat} which automatically expands
27280to its definition without the need to press @kbd{=} by writing the
27281rule @samp{quote(phihat) := (1-sqrt(5))/2}, but unfortunately this rule
27282will not work as part of @code{EvalRules}.
27283
27284Finally, another limitation is that Calc sometimes calls its built-in
27285functions directly rather than going through the default simplifications.
27286When it does this, @code{EvalRules} will not be able to override those
27287functions. For example, when you take the absolute value of the complex
27288number @expr{(2, 3)}, Calc computes @samp{sqrt(2*2 + 3*3)} by calling
27289the multiplication, addition, and square root functions directly rather
27290than applying the default simplifications to this formula. So an
27291@code{EvalRules} rule that (perversely) rewrites @samp{sqrt(13) := 6}
27292would not apply. (However, if you put Calc into Symbolic mode so that
27293@samp{sqrt(13)} will be left in symbolic form by the built-in square
27294root function, your rule will be able to apply. But if the complex
27295number were @expr{(3,4)}, so that @samp{sqrt(25)} must be calculated,
27296then Symbolic mode will not help because @samp{sqrt(25)} can be
27297evaluated exactly to 5.)
27298
27299One subtle restriction that normally only manifests itself with
27300@code{EvalRules} is that while a given rewrite rule is in the process
27301of being checked, that same rule cannot be recursively applied. Calc
27302effectively removes the rule from its rule set while checking the rule,
27303then puts it back once the match succeeds or fails. (The technical
27304reason for this is that compiled pattern programs are not reentrant.)
27305For example, consider the rule @samp{foo(x) := x :: foo(x/2) > 0}
27306attempting to match @samp{foo(8)}. This rule will be inactive while
27307the condition @samp{foo(4) > 0} is checked, even though it might be
27308an integral part of evaluating that condition. Note that this is not
27309a problem for the more usual recursive type of rule, such as
27310@samp{foo(x) := foo(x/2)}, because there the rule has succeeded and
27311been reactivated by the time the righthand side is evaluated.
27312
27313If @code{EvalRules} has no stored value (its default state), or if
27314anything but a vector is stored in it, then it is ignored.
27315
27316Even though Calc's rewrite mechanism is designed to compare rewrite
27317rules to formulas as quickly as possible, storing rules in
27318@code{EvalRules} may make Calc run substantially slower. This is
27319particularly true of rules where the top-level call is a commonly used
27320function, or is not fixed. The rule @samp{f(n) := n f(n-1) :: n>0} will
27321only activate the rewrite mechanism for calls to the function @code{f},
27322but @samp{lg(n) + lg(m) := lg(n m)} will check every @samp{+} operator.
27323
27324@smallexample
27325apply(f, [a*b]) := apply(f, [a]) + apply(f, [b]) :: in(f, [ln, log10])
27326@end smallexample
27327
27328@noindent
27329may seem more ``efficient'' than two separate rules for @code{ln} and
27330@code{log10}, but actually it is vastly less efficient because rules
27331with @code{apply} as the top-level pattern must be tested against
27332@emph{every} function call that is simplified.
27333
27334@cindex @code{AlgSimpRules} variable
27335@vindex AlgSimpRules
27336Suppose you want @samp{sin(a + b)} to be expanded out not all the time,
27337but only when @kbd{a s} is used to simplify the formula. The variable
27338@code{AlgSimpRules} holds rules for this purpose. The @kbd{a s} command
27339will apply @code{EvalRules} and @code{AlgSimpRules} to the formula, as
27340well as all of its built-in simplifications.
27341
27342Most of the special limitations for @code{EvalRules} don't apply to
27343@code{AlgSimpRules}. Calc simply does an @kbd{a r AlgSimpRules}
27344command with an infinite repeat count as the first step of @kbd{a s}.
27345It then applies its own built-in simplifications throughout the
27346formula, and then repeats these two steps (along with applying the
27347default simplifications) until no further changes are possible.
27348
27349@cindex @code{ExtSimpRules} variable
27350@cindex @code{UnitSimpRules} variable
27351@vindex ExtSimpRules
27352@vindex UnitSimpRules
27353There are also @code{ExtSimpRules} and @code{UnitSimpRules} variables
27354that are used by @kbd{a e} and @kbd{u s}, respectively; these commands
27355also apply @code{EvalRules} and @code{AlgSimpRules}. The variable
27356@code{IntegSimpRules} contains simplification rules that are used
27357only during integration by @kbd{a i}.
27358
27359@node Debugging Rewrites, Examples of Rewrite Rules, Automatic Rewrites, Rewrite Rules
27360@subsection Debugging Rewrites
27361
27362@noindent
27363If a buffer named @samp{*Trace*} exists, the rewrite mechanism will
27364record some useful information there as it operates. The original
27365formula is written there, as is the result of each successful rewrite,
27366and the final result of the rewriting. All phase changes are also
27367noted.
27368
27369Calc always appends to @samp{*Trace*}. You must empty this buffer
27370yourself periodically if it is in danger of growing unwieldy.
27371
27372Note that the rewriting mechanism is substantially slower when the
27373@samp{*Trace*} buffer exists, even if the buffer is not visible on
27374the screen. Once you are done, you will probably want to kill this
27375buffer (with @kbd{C-x k *Trace* @key{RET}}). If you leave it in
27376existence and forget about it, all your future rewrite commands will
27377be needlessly slow.
27378
27379@node Examples of Rewrite Rules, , Debugging Rewrites, Rewrite Rules
27380@subsection Examples of Rewrite Rules
27381
27382@noindent
27383Returning to the example of substituting the pattern
27384@samp{sin(x)^2 + cos(x)^2} with 1, we saw that the rule
27385@samp{opt(a) sin(x)^2 + opt(a) cos(x)^2 := a} does a good job of
27386finding suitable cases. Another solution would be to use the rule
27387@samp{cos(x)^2 := 1 - sin(x)^2}, followed by algebraic simplification
27388if necessary. This rule will be the most effective way to do the job,
27389but at the expense of making some changes that you might not desire.
27390
27391Another algebraic rewrite rule is @samp{exp(x+y) := exp(x) exp(y)}.
27392To make this work with the @w{@kbd{j r}} command so that it can be
27393easily targeted to a particular exponential in a large formula,
27394you might wish to write the rule as @samp{select(exp(x+y)) :=
27395select(exp(x) exp(y))}. The @samp{select} markers will be
27396ignored by the regular @kbd{a r} command
27397(@pxref{Selections with Rewrite Rules}).
27398
27399A surprisingly useful rewrite rule is @samp{a/(b-c) := a*(b+c)/(b^2-c^2)}.
27400This will simplify the formula whenever @expr{b} and/or @expr{c} can
27401be made simpler by squaring. For example, applying this rule to
27402@samp{2 / (sqrt(2) + 3)} yields @samp{6:7 - 2:7 sqrt(2)} (assuming
27403Symbolic mode has been enabled to keep the square root from being
27404evaluated to a floating-point approximation). This rule is also
27405useful when working with symbolic complex numbers, e.g.,
27406@samp{(a + b i) / (c + d i)}.
27407
27408As another example, we could define our own ``triangular numbers'' function
27409with the rules @samp{[tri(0) := 0, tri(n) := n + tri(n-1) :: n>0]}. Enter
27410this vector and store it in a variable: @kbd{@w{s t} trirules}. Now, given
27411a suitable formula like @samp{tri(5)} on the stack, type @samp{a r trirules}
27412to apply these rules repeatedly. After six applications, @kbd{a r} will
27413stop with 15 on the stack. Once these rules are debugged, it would probably
27414be most useful to add them to @code{EvalRules} so that Calc will evaluate
27415the new @code{tri} function automatically. We could then use @kbd{Z K} on
27416the keyboard macro @kbd{' tri($) @key{RET}} to make a command that applies
27417@code{tri} to the value on the top of the stack. @xref{Programming}.
27418
27419@cindex Quaternions
27420The following rule set, contributed by
27421@texline Fran\c cois
27422@infoline Francois
27423Pinard, implements @dfn{quaternions}, a generalization of the concept of
27424complex numbers. Quaternions have four components, and are here
27425represented by function calls @samp{quat(@var{w}, [@var{x}, @var{y},
27426@var{z}])} with ``real part'' @var{w} and the three ``imaginary'' parts
27427collected into a vector. Various arithmetical operations on quaternions
27428are supported. To use these rules, either add them to @code{EvalRules},
27429or create a command based on @kbd{a r} for simplifying quaternion
27430formulas. A convenient way to enter quaternions would be a command
27431defined by a keyboard macro containing: @kbd{' quat($$$$, [$$$, $$, $])
27432@key{RET}}.
27433
27434@smallexample
27435[ quat(w, x, y, z) := quat(w, [x, y, z]),
27436 quat(w, [0, 0, 0]) := w,
27437 abs(quat(w, v)) := hypot(w, v),
27438 -quat(w, v) := quat(-w, -v),
27439 r + quat(w, v) := quat(r + w, v) :: real(r),
27440 r - quat(w, v) := quat(r - w, -v) :: real(r),
27441 quat(w1, v1) + quat(w2, v2) := quat(w1 + w2, v1 + v2),
27442 r * quat(w, v) := quat(r * w, r * v) :: real(r),
27443 plain(quat(w1, v1) * quat(w2, v2))
27444 := quat(w1 * w2 - v1 * v2, w1 * v2 + w2 * v1 + cross(v1, v2)),
27445 quat(w1, v1) / r := quat(w1 / r, v1 / r) :: real(r),
27446 z / quat(w, v) := z * quatinv(quat(w, v)),
27447 quatinv(quat(w, v)) := quat(w, -v) / (w^2 + v^2),
27448 quatsqr(quat(w, v)) := quat(w^2 - v^2, 2 * w * v),
27449 quat(w, v)^k := quatsqr(quat(w, v)^(k / 2))
27450 :: integer(k) :: k > 0 :: k % 2 = 0,
27451 quat(w, v)^k := quatsqr(quat(w, v)^((k - 1) / 2)) * quat(w, v)
27452 :: integer(k) :: k > 2,
27453 quat(w, v)^-k := quatinv(quat(w, v)^k) :: integer(k) :: k > 0 ]
27454@end smallexample
27455
27456Quaternions, like matrices, have non-commutative multiplication.
27457In other words, @expr{q1 * q2 = q2 * q1} is not necessarily true if
27458@expr{q1} and @expr{q2} are @code{quat} forms. The @samp{quat*quat}
27459rule above uses @code{plain} to prevent Calc from rearranging the
27460product. It may also be wise to add the line @samp{[quat(), matrix]}
27461to the @code{Decls} matrix, to ensure that Calc's other algebraic
27462operations will not rearrange a quaternion product. @xref{Declarations}.
27463
27464These rules also accept a four-argument @code{quat} form, converting
27465it to the preferred form in the first rule. If you would rather see
27466results in the four-argument form, just append the two items
27467@samp{phase(2), quat(w, [x, y, z]) := quat(w, x, y, z)} to the end
27468of the rule set. (But remember that multi-phase rule sets don't work
27469in @code{EvalRules}.)
27470
27471@node Units, Store and Recall, Algebra, Top
27472@chapter Operating on Units
27473
27474@noindent
27475One special interpretation of algebraic formulas is as numbers with units.
27476For example, the formula @samp{5 m / s^2} can be read ``five meters
27477per second squared.'' The commands in this chapter help you
27478manipulate units expressions in this form. Units-related commands
27479begin with the @kbd{u} prefix key.
27480
27481@menu
27482* Basic Operations on Units::
27483* The Units Table::
27484* Predefined Units::
27485* User-Defined Units::
27486@end menu
27487
27488@node Basic Operations on Units, The Units Table, Units, Units
27489@section Basic Operations on Units
27490
27491@noindent
27492A @dfn{units expression} is a formula which is basically a number
27493multiplied and/or divided by one or more @dfn{unit names}, which may
27494optionally be raised to integer powers. Actually, the value part need not
27495be a number; any product or quotient involving unit names is a units
27496expression. Many of the units commands will also accept any formula,
27497where the command applies to all units expressions which appear in the
27498formula.
27499
27500A unit name is a variable whose name appears in the @dfn{unit table},
27501or a variable whose name is a prefix character like @samp{k} (for ``kilo'')
27502or @samp{u} (for ``micro'') followed by a name in the unit table.
27503A substantial table of built-in units is provided with Calc;
27504@pxref{Predefined Units}. You can also define your own unit names;
27505@pxref{User-Defined Units}.
27506
27507Note that if the value part of a units expression is exactly @samp{1},
27508it will be removed by the Calculator's automatic algebra routines: The
27509formula @samp{1 mm} is ``simplified'' to @samp{mm}. This is only a
27510display anomaly, however; @samp{mm} will work just fine as a
27511representation of one millimeter.
27512
27513You may find that Algebraic mode (@pxref{Algebraic Entry}) makes working
27514with units expressions easier. Otherwise, you will have to remember
27515to hit the apostrophe key every time you wish to enter units.
27516
27517@kindex u s
27518@pindex calc-simplify-units
27519@ignore
27520@mindex usimpl@idots
27521@end ignore
27522@tindex usimplify
27523The @kbd{u s} (@code{calc-simplify-units}) [@code{usimplify}] command
27524simplifies a units
27525expression. It uses @kbd{a s} (@code{calc-simplify}) to simplify the
27526expression first as a regular algebraic formula; it then looks for
27527features that can be further simplified by converting one object's units
27528to be compatible with another's. For example, @samp{5 m + 23 mm} will
27529simplify to @samp{5.023 m}. When different but compatible units are
27530added, the righthand term's units are converted to match those of the
27531lefthand term. @xref{Simplification Modes}, for a way to have this done
27532automatically at all times.
27533
27534Units simplification also handles quotients of two units with the same
27535dimensionality, as in @w{@samp{2 in s/L cm}} to @samp{5.08 s/L}; fractional
27536powers of unit expressions, as in @samp{sqrt(9 mm^2)} to @samp{3 mm} and
27537@samp{sqrt(9 acre)} to a quantity in meters; and @code{floor},
27538@code{ceil}, @code{round}, @code{rounde}, @code{roundu}, @code{trunc},
27539@code{float}, @code{frac}, @code{abs}, and @code{clean}
27540applied to units expressions, in which case
27541the operation in question is applied only to the numeric part of the
27542expression. Finally, trigonometric functions of quantities with units
27543of angle are evaluated, regardless of the current angular mode.
27544
27545@kindex u c
27546@pindex calc-convert-units
27547The @kbd{u c} (@code{calc-convert-units}) command converts a units
27548expression to new, compatible units. For example, given the units
27549expression @samp{55 mph}, typing @kbd{u c m/s @key{RET}} produces
27550@samp{24.5872 m/s}. If you have previously converted a units expression
27551with the same type of units (in this case, distance over time), you will
27552be offered the previous choice of new units as a default. Continuing
27553the above example, entering the units expression @samp{100 km/hr} and
27554typing @kbd{u c @key{RET}} (without specifying new units) produces
27555@samp{27.7777777778 m/s}.
27556
27557While many of Calc's conversion factors are exact, some are necessarily
27558approximate. If Calc is in fraction mode (@pxref{Fraction Mode}), then
27559unit conversions will try to give exact, rational conversions, but it
27560isn't always possible. Given @samp{55 mph} in fraction mode, typing
27561@kbd{u c m/s @key{RET}} produces @samp{15367:625 m/s}, for example,
27562while typing @kbd{u c au/yr @key{RET}} produces
27563@samp{5.18665819999e-3 au/yr}.
27564
27565If the units you request are inconsistent with the original units, the
27566number will be converted into your units times whatever ``remainder''
27567units are left over. For example, converting @samp{55 mph} into acres
27568produces @samp{6.08e-3 acre / m s}. (Recall that multiplication binds
27569more strongly than division in Calc formulas, so the units here are
27570acres per meter-second.) Remainder units are expressed in terms of
27571``fundamental'' units like @samp{m} and @samp{s}, regardless of the
27572input units.
27573
27574One special exception is that if you specify a single unit name, and
27575a compatible unit appears somewhere in the units expression, then
27576that compatible unit will be converted to the new unit and the
27577remaining units in the expression will be left alone. For example,
27578given the input @samp{980 cm/s^2}, the command @kbd{u c ms} will
27579change the @samp{s} to @samp{ms} to get @samp{9.8e-4 cm/ms^2}.
27580The ``remainder unit'' @samp{cm} is left alone rather than being
27581changed to the base unit @samp{m}.
27582
27583You can use explicit unit conversion instead of the @kbd{u s} command
27584to gain more control over the units of the result of an expression.
27585For example, given @samp{5 m + 23 mm}, you can type @kbd{u c m} or
27586@kbd{u c mm} to express the result in either meters or millimeters.
27587(For that matter, you could type @kbd{u c fath} to express the result
27588in fathoms, if you preferred!)
27589
27590In place of a specific set of units, you can also enter one of the
27591units system names @code{si}, @code{mks} (equivalent), or @code{cgs}.
27592For example, @kbd{u c si @key{RET}} converts the expression into
27593International System of Units (SI) base units. Also, @kbd{u c base}
27594converts to Calc's base units, which are the same as @code{si} units
27595except that @code{base} uses @samp{g} as the fundamental unit of mass
27596whereas @code{si} uses @samp{kg}.
27597
27598@cindex Composite units
27599The @kbd{u c} command also accepts @dfn{composite units}, which
27600are expressed as the sum of several compatible unit names. For
27601example, converting @samp{30.5 in} to units @samp{mi+ft+in} (miles,
27602feet, and inches) produces @samp{2 ft + 6.5 in}. Calc first
27603sorts the unit names into order of decreasing relative size.
27604It then accounts for as much of the input quantity as it can
27605using an integer number times the largest unit, then moves on
27606to the next smaller unit, and so on. Only the smallest unit
27607may have a non-integer amount attached in the result. A few
27608standard unit names exist for common combinations, such as
27609@code{mfi} for @samp{mi+ft+in}, and @code{tpo} for @samp{ton+lb+oz}.
27610Composite units are expanded as if by @kbd{a x}, so that
27611@samp{(ft+in)/hr} is first converted to @samp{ft/hr+in/hr}.
27612
27613If the value on the stack does not contain any units, @kbd{u c} will
27614prompt first for the old units which this value should be considered
27615to have, then for the new units. Assuming the old and new units you
27616give are consistent with each other, the result also will not contain
285f0d3a
JB
27617any units. For example, @kbd{@w{u c} cm @key{RET} in @key{RET}}
27618converts the number 2 on the stack to 5.08.
4009494e
GM
27619
27620@kindex u b
27621@pindex calc-base-units
27622The @kbd{u b} (@code{calc-base-units}) command is shorthand for
27623@kbd{u c base}; it converts the units expression on the top of the
27624stack into @code{base} units. If @kbd{u s} does not simplify a
27625units expression as far as you would like, try @kbd{u b}.
27626
27627The @kbd{u c} and @kbd{u b} commands treat temperature units (like
27628@samp{degC} and @samp{K}) as relative temperatures. For example,
27629@kbd{u c} converts @samp{10 degC} to @samp{18 degF}: A change of 10
27630degrees Celsius corresponds to a change of 18 degrees Fahrenheit.
27631
27632@kindex u t
27633@pindex calc-convert-temperature
27634@cindex Temperature conversion
27635The @kbd{u t} (@code{calc-convert-temperature}) command converts
27636absolute temperatures. The value on the stack must be a simple units
27637expression with units of temperature only. This command would convert
27638@samp{10 degC} to @samp{50 degF}, the equivalent temperature on the
27639Fahrenheit scale.
27640
27641@kindex u r
27642@pindex calc-remove-units
27643@kindex u x
27644@pindex calc-extract-units
27645The @kbd{u r} (@code{calc-remove-units}) command removes units from the
27646formula at the top of the stack. The @kbd{u x}
27647(@code{calc-extract-units}) command extracts only the units portion of a
27648formula. These commands essentially replace every term of the formula
27649that does or doesn't (respectively) look like a unit name by the
27650constant 1, then resimplify the formula.
27651
27652@kindex u a
27653@pindex calc-autorange-units
27654The @kbd{u a} (@code{calc-autorange-units}) command turns on and off a
27655mode in which unit prefixes like @code{k} (``kilo'') are automatically
27656applied to keep the numeric part of a units expression in a reasonable
27657range. This mode affects @kbd{u s} and all units conversion commands
27658except @kbd{u b}. For example, with autoranging on, @samp{12345 Hz}
27659will be simplified to @samp{12.345 kHz}. Autoranging is useful for
27660some kinds of units (like @code{Hz} and @code{m}), but is probably
27661undesirable for non-metric units like @code{ft} and @code{tbsp}.
27662(Composite units are more appropriate for those; see above.)
27663
27664Autoranging always applies the prefix to the leftmost unit name.
27665Calc chooses the largest prefix that causes the number to be greater
27666than or equal to 1.0. Thus an increasing sequence of adjusted times
27667would be @samp{1 ms, 10 ms, 100 ms, 1 s, 10 s, 100 s, 1 ks}.
27668Generally the rule of thumb is that the number will be adjusted
27669to be in the interval @samp{[1 .. 1000)}, although there are several
27670exceptions to this rule. First, if the unit has a power then this
27671is not possible; @samp{0.1 s^2} simplifies to @samp{100000 ms^2}.
27672Second, the ``centi-'' prefix is allowed to form @code{cm} (centimeters),
27673but will not apply to other units. The ``deci-,'' ``deka-,'' and
27674``hecto-'' prefixes are never used. Thus the allowable interval is
27675@samp{[1 .. 10)} for millimeters and @samp{[1 .. 100)} for centimeters.
27676Finally, a prefix will not be added to a unit if the resulting name
27677is also the actual name of another unit; @samp{1e-15 t} would normally
27678be considered a ``femto-ton,'' but it is written as @samp{1000 at}
27679(1000 atto-tons) instead because @code{ft} would be confused with feet.
27680
27681@node The Units Table, Predefined Units, Basic Operations on Units, Units
27682@section The Units Table
27683
27684@noindent
27685@kindex u v
27686@pindex calc-enter-units-table
27687The @kbd{u v} (@code{calc-enter-units-table}) command displays the units table
27688in another buffer called @code{*Units Table*}. Each entry in this table
27689gives the unit name as it would appear in an expression, the definition
27690of the unit in terms of simpler units, and a full name or description of
27691the unit. Fundamental units are defined as themselves; these are the
27692units produced by the @kbd{u b} command. The fundamental units are
27693meters, seconds, grams, kelvins, amperes, candelas, moles, radians,
27694and steradians.
27695
27696The Units Table buffer also displays the Unit Prefix Table. Note that
27697two prefixes, ``kilo'' and ``hecto,'' accept either upper- or lower-case
27698prefix letters. @samp{Meg} is also accepted as a synonym for the @samp{M}
27699prefix. Whenever a unit name can be interpreted as either a built-in name
27700or a prefix followed by another built-in name, the former interpretation
27701wins. For example, @samp{2 pt} means two pints, not two pico-tons.
27702
27703The Units Table buffer, once created, is not rebuilt unless you define
27704new units. To force the buffer to be rebuilt, give any numeric prefix
27705argument to @kbd{u v}.
27706
27707@kindex u V
27708@pindex calc-view-units-table
27709The @kbd{u V} (@code{calc-view-units-table}) command is like @kbd{u v} except
27710that the cursor is not moved into the Units Table buffer. You can
27711type @kbd{u V} again to remove the Units Table from the display. To
27712return from the Units Table buffer after a @kbd{u v}, type @kbd{C-x * c}
27713again or use the regular Emacs @w{@kbd{C-x o}} (@code{other-window})
27714command. You can also kill the buffer with @kbd{C-x k} if you wish;
27715the actual units table is safely stored inside the Calculator.
27716
27717@kindex u g
27718@pindex calc-get-unit-definition
27719The @kbd{u g} (@code{calc-get-unit-definition}) command retrieves a unit's
27720defining expression and pushes it onto the Calculator stack. For example,
27721@kbd{u g in} will produce the expression @samp{2.54 cm}. This is the
27722same definition for the unit that would appear in the Units Table buffer.
27723Note that this command works only for actual unit names; @kbd{u g km}
27724will report that no such unit exists, for example, because @code{km} is
27725really the unit @code{m} with a @code{k} (``kilo'') prefix. To see a
27726definition of a unit in terms of base units, it is easier to push the
27727unit name on the stack and then reduce it to base units with @kbd{u b}.
27728
27729@kindex u e
27730@pindex calc-explain-units
27731The @kbd{u e} (@code{calc-explain-units}) command displays an English
27732description of the units of the expression on the stack. For example,
27733for the expression @samp{62 km^2 g / s^2 mol K}, the description is
27734``Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin).'' This
27735command uses the English descriptions that appear in the righthand
27736column of the Units Table.
27737
27738@node Predefined Units, User-Defined Units, The Units Table, Units
27739@section Predefined Units
27740
27741@noindent
285f0d3a
JB
27742The definitions of many units have changed over the years. For example,
27743the meter was originally defined in 1791 as one ten-millionth of the
27744distance from the equator to the north pole. In order to be more
27745precise, the definition was adjusted several times, and now a meter is
27746defined as the distance that light will travel in a vacuum in
277471/299792458 of a second; consequently, the speed of light in a
27748vacuum is exactly 299792458 m/s. Many other units have been
27749redefined in terms of fundamental physical processes; a second, for
27750example, is currently defined as 9192631770 periods of a certain
27751radiation related to the cesium-133 atom. The only SI unit that is not
27752based on a fundamental physical process (although there are efforts to
27753change this) is the kilogram, which was originally defined as the mass
27754of one liter of water, but is now defined as the mass of the
27755International Prototype Kilogram (IPK), a cylinder of platinum-iridium
27756kept at the Bureau International des Poids et Mesures in S@`evres,
27757France. (There are several copies of the IPK throughout the world.)
27758The British imperial units, once defined in terms of physical objects,
27759were redefined in 1963 in terms of SI units. The US customary units,
27760which were the same as British units until the British imperial system
27761was created in 1824, were also defined in terms of the SI units in 1893.
27762Because of these redefinitions, conversions between metric, British
27763Imperial, and US customary units can often be done precisely.
27764
4009494e
GM
27765Since the exact definitions of many kinds of units have evolved over the
27766years, and since certain countries sometimes have local differences in
27767their definitions, it is a good idea to examine Calc's definition of a
27768unit before depending on its exact value. For example, there are three
27769different units for gallons, corresponding to the US (@code{gal}),
27770Canadian (@code{galC}), and British (@code{galUK}) definitions. Also,
27771note that @code{oz} is a standard ounce of mass, @code{ozt} is a Troy
27772ounce, and @code{ozfl} is a fluid ounce.
27773
27774The temperature units corresponding to degrees Kelvin and Centigrade
27775(Celsius) are the same in this table, since most units commands treat
27776temperatures as being relative. The @code{calc-convert-temperature}
27777command has special rules for handling the different absolute magnitudes
27778of the various temperature scales.
27779
27780The unit of volume ``liters'' can be referred to by either the lower-case
27781@code{l} or the upper-case @code{L}.
27782
27783The unit @code{A} stands for Amperes; the name @code{Ang} is used
27784@tex
27785for \AA ngstroms.
27786@end tex
27787@ifnottex
27788for Angstroms.
27789@end ifnottex
27790
27791The unit @code{pt} stands for pints; the name @code{point} stands for
27792a typographical point, defined by @samp{72 point = 1 in}. This is
27793slightly different than the point defined by the American Typefounder's
27794Association in 1886, but the point used by Calc has become standard
27795largely due to its use by the PostScript page description language.
27796There is also @code{texpt}, which stands for a printer's point as
27797defined by the @TeX{} typesetting system: @samp{72.27 texpt = 1 in}.
27798Other units used by @TeX{} are available; they are @code{texpc} (a pica),
27799@code{texbp} (a ``big point'', equal to a standard point which is larger
27800than the point used by @TeX{}), @code{texdd} (a Didot point),
27801@code{texcc} (a Cicero) and @code{texsp} (a scaled @TeX{} point,
27802all dimensions representable in @TeX{} are multiples of this value).
27803
27804The unit @code{e} stands for the elementary (electron) unit of charge;
27805because algebra command could mistake this for the special constant
27806@expr{e}, Calc provides the alternate unit name @code{ech} which is
27807preferable to @code{e}.
27808
27809The name @code{g} stands for one gram of mass; there is also @code{gf},
27810one gram of force. (Likewise for @kbd{lb}, pounds, and @kbd{lbf}.)
27811Meanwhile, one ``@expr{g}'' of acceleration is denoted @code{ga}.
27812
27813The unit @code{ton} is a U.S. ton of @samp{2000 lb}, and @code{t} is
27814a metric ton of @samp{1000 kg}.
27815
27816The names @code{s} (or @code{sec}) and @code{min} refer to units of
27817time; @code{arcsec} and @code{arcmin} are units of angle.
27818
27819Some ``units'' are really physical constants; for example, @code{c}
27820represents the speed of light, and @code{h} represents Planck's
27821constant. You can use these just like other units: converting
27822@samp{.5 c} to @samp{m/s} expresses one-half the speed of light in
27823meters per second. You can also use this merely as a handy reference;
27824the @kbd{u g} command gets the definition of one of these constants
27825in its normal terms, and @kbd{u b} expresses the definition in base
27826units.
27827
27828Two units, @code{pi} and @code{alpha} (the fine structure constant,
27829approximately @mathit{1/137}) are dimensionless. The units simplification
27830commands simply treat these names as equivalent to their corresponding
27831values. However you can, for example, use @kbd{u c} to convert a pure
27832number into multiples of the fine structure constant, or @kbd{u b} to
27833convert this back into a pure number. (When @kbd{u c} prompts for the
27834``old units,'' just enter a blank line to signify that the value
27835really is unitless.)
27836
27837@c Describe angular units, luminosity vs. steradians problem.
27838
27839@node User-Defined Units, , Predefined Units, Units
27840@section User-Defined Units
27841
27842@noindent
27843Calc provides ways to get quick access to your selected ``favorite''
27844units, as well as ways to define your own new units.
27845
27846@kindex u 0-9
27847@pindex calc-quick-units
27848@vindex Units
27849@cindex @code{Units} variable
27850@cindex Quick units
27851To select your favorite units, store a vector of unit names or
27852expressions in the Calc variable @code{Units}. The @kbd{u 1}
27853through @kbd{u 9} commands (@code{calc-quick-units}) provide access
27854to these units. If the value on the top of the stack is a plain
27855number (with no units attached), then @kbd{u 1} gives it the
27856specified units. (Basically, it multiplies the number by the
27857first item in the @code{Units} vector.) If the number on the
27858stack @emph{does} have units, then @kbd{u 1} converts that number
27859to the new units. For example, suppose the vector @samp{[in, ft]}
27860is stored in @code{Units}. Then @kbd{30 u 1} will create the
27861expression @samp{30 in}, and @kbd{u 2} will convert that expression
27862to @samp{2.5 ft}.
27863
27864The @kbd{u 0} command accesses the tenth element of @code{Units}.
27865Only ten quick units may be defined at a time. If the @code{Units}
27866variable has no stored value (the default), or if its value is not
27867a vector, then the quick-units commands will not function. The
27868@kbd{s U} command is a convenient way to edit the @code{Units}
27869variable; @pxref{Operations on Variables}.
27870
27871@kindex u d
27872@pindex calc-define-unit
27873@cindex User-defined units
27874The @kbd{u d} (@code{calc-define-unit}) command records the units
27875expression on the top of the stack as the definition for a new,
27876user-defined unit. For example, putting @samp{16.5 ft} on the stack and
27877typing @kbd{u d rod} defines the new unit @samp{rod} to be equivalent to
2787816.5 feet. The unit conversion and simplification commands will now
27879treat @code{rod} just like any other unit of length. You will also be
27880prompted for an optional English description of the unit, which will
27881appear in the Units Table.
27882
27883@kindex u u
27884@pindex calc-undefine-unit
27885The @kbd{u u} (@code{calc-undefine-unit}) command removes a user-defined
27886unit. It is not possible to remove one of the predefined units,
27887however.
27888
27889If you define a unit with an existing unit name, your new definition
27890will replace the original definition of that unit. If the unit was a
27891predefined unit, the old definition will not be replaced, only
27892``shadowed.'' The built-in definition will reappear if you later use
27893@kbd{u u} to remove the shadowing definition.
27894
27895To create a new fundamental unit, use either 1 or the unit name itself
27896as the defining expression. Otherwise the expression can involve any
27897other units that you like (except for composite units like @samp{mfi}).
27898You can create a new composite unit with a sum of other units as the
27899defining expression. The next unit operation like @kbd{u c} or @kbd{u v}
27900will rebuild the internal unit table incorporating your modifications.
27901Note that erroneous definitions (such as two units defined in terms of
27902each other) will not be detected until the unit table is next rebuilt;
27903@kbd{u v} is a convenient way to force this to happen.
27904
27905Temperature units are treated specially inside the Calculator; it is not
27906possible to create user-defined temperature units.
27907
27908@kindex u p
27909@pindex calc-permanent-units
27910@cindex Calc init file, user-defined units
27911The @kbd{u p} (@code{calc-permanent-units}) command stores the user-defined
27912units in your Calc init file (the file given by the variable
27913@code{calc-settings-file}, typically @file{~/.calc.el}), so that the
27914units will still be available in subsequent Emacs sessions. If there
27915was already a set of user-defined units in your Calc init file, it
27916is replaced by the new set. (@xref{General Mode Commands}, for a way to
27917tell Calc to use a different file for the Calc init file.)
27918
27919@node Store and Recall, Graphics, Units, Top
27920@chapter Storing and Recalling
27921
27922@noindent
27923Calculator variables are really just Lisp variables that contain numbers
27924or formulas in a form that Calc can understand. The commands in this
27925section allow you to manipulate variables conveniently. Commands related
27926to variables use the @kbd{s} prefix key.
27927
27928@menu
27929* Storing Variables::
27930* Recalling Variables::
27931* Operations on Variables::
27932* Let Command::
27933* Evaluates-To Operator::
27934@end menu
27935
27936@node Storing Variables, Recalling Variables, Store and Recall, Store and Recall
27937@section Storing Variables
27938
27939@noindent
27940@kindex s s
27941@pindex calc-store
27942@cindex Storing variables
27943@cindex Quick variables
27944@vindex q0
27945@vindex q9
27946The @kbd{s s} (@code{calc-store}) command stores the value at the top of
27947the stack into a specified variable. It prompts you to enter the
27948name of the variable. If you press a single digit, the value is stored
27949immediately in one of the ``quick'' variables @code{q0} through
27950@code{q9}. Or you can enter any variable name.
27951
27952@kindex s t
27953@pindex calc-store-into
27954The @kbd{s s} command leaves the stored value on the stack. There is
27955also an @kbd{s t} (@code{calc-store-into}) command, which removes a
27956value from the stack and stores it in a variable.
27957
27958If the top of stack value is an equation @samp{a = 7} or assignment
27959@samp{a := 7} with a variable on the lefthand side, then Calc will
27960assign that variable with that value by default, i.e., if you type
27961@kbd{s s @key{RET}} or @kbd{s t @key{RET}}. In this example, the
27962value 7 would be stored in the variable @samp{a}. (If you do type
27963a variable name at the prompt, the top-of-stack value is stored in
27964its entirety, even if it is an equation: @samp{s s b @key{RET}}
27965with @samp{a := 7} on the stack stores @samp{a := 7} in @code{b}.)
27966
27967In fact, the top of stack value can be a vector of equations or
27968assignments with different variables on their lefthand sides; the
27969default will be to store all the variables with their corresponding
27970righthand sides simultaneously.
27971
27972It is also possible to type an equation or assignment directly at
27973the prompt for the @kbd{s s} or @kbd{s t} command: @kbd{s s foo = 7}.
27974In this case the expression to the right of the @kbd{=} or @kbd{:=}
27975symbol is evaluated as if by the @kbd{=} command, and that value is
27976stored in the variable. No value is taken from the stack; @kbd{s s}
27977and @kbd{s t} are equivalent when used in this way.
27978
27979@kindex s 0-9
27980@kindex t 0-9
27981The prefix keys @kbd{s} and @kbd{t} may be followed immediately by a
27982digit; @kbd{s 9} is equivalent to @kbd{s s 9}, and @kbd{t 9} is
27983equivalent to @kbd{s t 9}. (The @kbd{t} prefix is otherwise used
27984for trail and time/date commands.)
27985
27986@kindex s +
27987@kindex s -
27988@ignore
27989@mindex @idots
27990@end ignore
27991@kindex s *
27992@ignore
27993@mindex @null
27994@end ignore
27995@kindex s /
27996@ignore
27997@mindex @null
27998@end ignore
27999@kindex s ^
28000@ignore
28001@mindex @null
28002@end ignore
28003@kindex s |
28004@ignore
28005@mindex @null
28006@end ignore
28007@kindex s n
28008@ignore
28009@mindex @null
28010@end ignore
28011@kindex s &
28012@ignore
28013@mindex @null
28014@end ignore
28015@kindex s [
28016@ignore
28017@mindex @null
28018@end ignore
28019@kindex s ]
28020@pindex calc-store-plus
28021@pindex calc-store-minus
28022@pindex calc-store-times
28023@pindex calc-store-div
28024@pindex calc-store-power
28025@pindex calc-store-concat
28026@pindex calc-store-neg
28027@pindex calc-store-inv
28028@pindex calc-store-decr
28029@pindex calc-store-incr
28030There are also several ``arithmetic store'' commands. For example,
28031@kbd{s +} removes a value from the stack and adds it to the specified
28032variable. The other arithmetic stores are @kbd{s -}, @kbd{s *}, @kbd{s /},
28033@kbd{s ^}, and @w{@kbd{s |}} (vector concatenation), plus @kbd{s n} and
28034@kbd{s &} which negate or invert the value in a variable, and @w{@kbd{s [}}
28035and @kbd{s ]} which decrease or increase a variable by one.
28036
28037All the arithmetic stores accept the Inverse prefix to reverse the
28038order of the operands. If @expr{v} represents the contents of the
28039variable, and @expr{a} is the value drawn from the stack, then regular
28040@w{@kbd{s -}} assigns
28041@texline @math{v \coloneq v - a},
28042@infoline @expr{v := v - a},
28043but @kbd{I s -} assigns
28044@texline @math{v \coloneq a - v}.
28045@infoline @expr{v := a - v}.
28046While @kbd{I s *} might seem pointless, it is
28047useful if matrix multiplication is involved. Actually, all the
28048arithmetic stores use formulas designed to behave usefully both
28049forwards and backwards:
28050
28051@example
28052@group
28053s + v := v + a v := a + v
28054s - v := v - a v := a - v
28055s * v := v * a v := a * v
28056s / v := v / a v := a / v
28057s ^ v := v ^ a v := a ^ v
28058s | v := v | a v := a | v
28059s n v := v / (-1) v := (-1) / v
28060s & v := v ^ (-1) v := (-1) ^ v
28061s [ v := v - 1 v := 1 - v
28062s ] v := v - (-1) v := (-1) - v
28063@end group
28064@end example
28065
28066In the last four cases, a numeric prefix argument will be used in
28067place of the number one. (For example, @kbd{M-2 s ]} increases
28068a variable by 2, and @kbd{M-2 I s ]} replaces a variable by
28069minus-two minus the variable.
28070
28071The first six arithmetic stores can also be typed @kbd{s t +}, @kbd{s t -},
28072etc. The commands @kbd{s s +}, @kbd{s s -}, and so on are analogous
28073arithmetic stores that don't remove the value @expr{a} from the stack.
28074
28075All arithmetic stores report the new value of the variable in the
28076Trail for your information. They signal an error if the variable
28077previously had no stored value. If default simplifications have been
28078turned off, the arithmetic stores temporarily turn them on for numeric
28079arguments only (i.e., they temporarily do an @kbd{m N} command).
28080@xref{Simplification Modes}. Large vectors put in the trail by
28081these commands always use abbreviated (@kbd{t .}) mode.
28082
28083@kindex s m
28084@pindex calc-store-map
28085The @kbd{s m} command is a general way to adjust a variable's value
28086using any Calc function. It is a ``mapping'' command analogous to
28087@kbd{V M}, @kbd{V R}, etc. @xref{Reducing and Mapping}, to see
28088how to specify a function for a mapping command. Basically,
28089all you do is type the Calc command key that would invoke that
28090function normally. For example, @kbd{s m n} applies the @kbd{n}
28091key to negate the contents of the variable, so @kbd{s m n} is
28092equivalent to @kbd{s n}. Also, @kbd{s m Q} takes the square root
28093of the value stored in a variable, @kbd{s m v v} uses @kbd{v v} to
28094reverse the vector stored in the variable, and @kbd{s m H I S}
28095takes the hyperbolic arcsine of the variable contents.
28096
28097If the mapping function takes two or more arguments, the additional
28098arguments are taken from the stack; the old value of the variable
28099is provided as the first argument. Thus @kbd{s m -} with @expr{a}
28100on the stack computes @expr{v - a}, just like @kbd{s -}. With the
28101Inverse prefix, the variable's original value becomes the @emph{last}
28102argument instead of the first. Thus @kbd{I s m -} is also
28103equivalent to @kbd{I s -}.
28104
28105@kindex s x
28106@pindex calc-store-exchange
28107The @kbd{s x} (@code{calc-store-exchange}) command exchanges the value
28108of a variable with the value on the top of the stack. Naturally, the
28109variable must already have a stored value for this to work.
28110
28111You can type an equation or assignment at the @kbd{s x} prompt. The
28112command @kbd{s x a=6} takes no values from the stack; instead, it
28113pushes the old value of @samp{a} on the stack and stores @samp{a = 6}.
28114
28115@kindex s u
28116@pindex calc-unstore
28117@cindex Void variables
28118@cindex Un-storing variables
28119Until you store something in them, most variables are ``void,'' that is,
28120they contain no value at all. If they appear in an algebraic formula
28121they will be left alone even if you press @kbd{=} (@code{calc-evaluate}).
28122The @kbd{s u} (@code{calc-unstore}) command returns a variable to the
28123void state.
28124
28125@kindex s c
28126@pindex calc-copy-variable
28127The @kbd{s c} (@code{calc-copy-variable}) command copies the stored
28128value of one variable to another. One way it differs from a simple
28129@kbd{s r} followed by an @kbd{s t} (aside from saving keystrokes) is
28130that the value never goes on the stack and thus is never rounded,
28131evaluated, or simplified in any way; it is not even rounded down to the
28132current precision.
28133
28134The only variables with predefined values are the ``special constants''
28135@code{pi}, @code{e}, @code{i}, @code{phi}, and @code{gamma}. You are free
28136to unstore these variables or to store new values into them if you like,
28137although some of the algebraic-manipulation functions may assume these
28138variables represent their standard values. Calc displays a warning if
28139you change the value of one of these variables, or of one of the other
28140special variables @code{inf}, @code{uinf}, and @code{nan} (which are
28141normally void).
28142
28143Note that @code{pi} doesn't actually have 3.14159265359 stored in it,
28144but rather a special magic value that evaluates to @cpi{} at the current
28145precision. Likewise @code{e}, @code{i}, and @code{phi} evaluate
28146according to the current precision or polar mode. If you recall a value
28147from @code{pi} and store it back, this magic property will be lost. The
28148magic property is preserved, however, when a variable is copied with
28149@kbd{s c}.
28150
28151@kindex s k
28152@pindex calc-copy-special-constant
28153If one of the ``special constants'' is redefined (or undefined) so that
28154it no longer has its magic property, the property can be restored with
28155@kbd{s k} (@code{calc-copy-special-constant}). This command will prompt
28156for a special constant and a variable to store it in, and so a special
28157constant can be stored in any variable. Here, the special constant that
28158you enter doesn't depend on the value of the corresponding variable;
28159@code{pi} will represent 3.14159@dots{} regardless of what is currently
28160stored in the Calc variable @code{pi}. If one of the other special
28161variables, @code{inf}, @code{uinf} or @code{nan}, is given a value, its
28162original behavior can be restored by voiding it with @kbd{s u}.
28163
28164@node Recalling Variables, Operations on Variables, Storing Variables, Store and Recall
28165@section Recalling Variables
28166
28167@noindent
28168@kindex s r
28169@pindex calc-recall
28170@cindex Recalling variables
28171The most straightforward way to extract the stored value from a variable
28172is to use the @kbd{s r} (@code{calc-recall}) command. This command prompts
28173for a variable name (similarly to @code{calc-store}), looks up the value
28174of the specified variable, and pushes that value onto the stack. It is
28175an error to try to recall a void variable.
28176
28177It is also possible to recall the value from a variable by evaluating a
28178formula containing that variable. For example, @kbd{' a @key{RET} =} is
28179the same as @kbd{s r a @key{RET}} except that if the variable is void, the
28180former will simply leave the formula @samp{a} on the stack whereas the
28181latter will produce an error message.
28182
28183@kindex r 0-9
28184The @kbd{r} prefix may be followed by a digit, so that @kbd{r 9} is
538c2573 28185equivalent to @kbd{s r 9}.
4009494e
GM
28186
28187@node Operations on Variables, Let Command, Recalling Variables, Store and Recall
28188@section Other Operations on Variables
28189
28190@noindent
28191@kindex s e
28192@pindex calc-edit-variable
28193The @kbd{s e} (@code{calc-edit-variable}) command edits the stored
28194value of a variable without ever putting that value on the stack
28195or simplifying or evaluating the value. It prompts for the name of
28196the variable to edit. If the variable has no stored value, the
28197editing buffer will start out empty. If the editing buffer is
28198empty when you press @kbd{C-c C-c} to finish, the variable will
28199be made void. @xref{Editing Stack Entries}, for a general
28200description of editing.
28201
28202The @kbd{s e} command is especially useful for creating and editing
28203rewrite rules which are stored in variables. Sometimes these rules
28204contain formulas which must not be evaluated until the rules are
28205actually used. (For example, they may refer to @samp{deriv(x,y)},
28206where @code{x} will someday become some expression involving @code{y};
28207if you let Calc evaluate the rule while you are defining it, Calc will
28208replace @samp{deriv(x,y)} with 0 because the formula @code{x} does
28209not itself refer to @code{y}.) By contrast, recalling the variable,
28210editing with @kbd{`}, and storing will evaluate the variable's value
28211as a side effect of putting the value on the stack.
28212
28213@kindex s A
28214@kindex s D
28215@ignore
28216@mindex @idots
28217@end ignore
28218@kindex s E
28219@ignore
28220@mindex @null
28221@end ignore
28222@kindex s F
28223@ignore
28224@mindex @null
28225@end ignore
28226@kindex s G
28227@ignore
28228@mindex @null
28229@end ignore
28230@kindex s H
28231@ignore
28232@mindex @null
28233@end ignore
28234@kindex s I
28235@ignore
28236@mindex @null
28237@end ignore
28238@kindex s L
28239@ignore
28240@mindex @null
28241@end ignore
28242@kindex s P
28243@ignore
28244@mindex @null
28245@end ignore
28246@kindex s R
28247@ignore
28248@mindex @null
28249@end ignore
28250@kindex s T
28251@ignore
28252@mindex @null
28253@end ignore
28254@kindex s U
28255@ignore
28256@mindex @null
28257@end ignore
28258@kindex s X
28259@pindex calc-store-AlgSimpRules
28260@pindex calc-store-Decls
28261@pindex calc-store-EvalRules
28262@pindex calc-store-FitRules
28263@pindex calc-store-GenCount
28264@pindex calc-store-Holidays
28265@pindex calc-store-IntegLimit
28266@pindex calc-store-LineStyles
28267@pindex calc-store-PointStyles
28268@pindex calc-store-PlotRejects
28269@pindex calc-store-TimeZone
28270@pindex calc-store-Units
28271@pindex calc-store-ExtSimpRules
28272There are several special-purpose variable-editing commands that
28273use the @kbd{s} prefix followed by a shifted letter:
28274
28275@table @kbd
28276@item s A
28277Edit @code{AlgSimpRules}. @xref{Algebraic Simplifications}.
28278@item s D
28279Edit @code{Decls}. @xref{Declarations}.
28280@item s E
28281Edit @code{EvalRules}. @xref{Default Simplifications}.
28282@item s F
28283Edit @code{FitRules}. @xref{Curve Fitting}.
28284@item s G
28285Edit @code{GenCount}. @xref{Solving Equations}.
28286@item s H
28287Edit @code{Holidays}. @xref{Business Days}.
28288@item s I
28289Edit @code{IntegLimit}. @xref{Calculus}.
28290@item s L
28291Edit @code{LineStyles}. @xref{Graphics}.
28292@item s P
28293Edit @code{PointStyles}. @xref{Graphics}.
28294@item s R
28295Edit @code{PlotRejects}. @xref{Graphics}.
28296@item s T
28297Edit @code{TimeZone}. @xref{Time Zones}.
28298@item s U
28299Edit @code{Units}. @xref{User-Defined Units}.
28300@item s X
28301Edit @code{ExtSimpRules}. @xref{Unsafe Simplifications}.
28302@end table
28303
28304These commands are just versions of @kbd{s e} that use fixed variable
28305names rather than prompting for the variable name.
28306
28307@kindex s p
28308@pindex calc-permanent-variable
28309@cindex Storing variables
28310@cindex Permanent variables
28311@cindex Calc init file, variables
28312The @kbd{s p} (@code{calc-permanent-variable}) command saves a
28313variable's value permanently in your Calc init file (the file given by
28314the variable @code{calc-settings-file}, typically @file{~/.calc.el}), so
28315that its value will still be available in future Emacs sessions. You
28316can re-execute @w{@kbd{s p}} later on to update the saved value, but the
28317only way to remove a saved variable is to edit your calc init file
28318by hand. (@xref{General Mode Commands}, for a way to tell Calc to
28319use a different file for the Calc init file.)
28320
28321If you do not specify the name of a variable to save (i.e.,
28322@kbd{s p @key{RET}}), all Calc variables with defined values
28323are saved except for the special constants @code{pi}, @code{e},
28324@code{i}, @code{phi}, and @code{gamma}; the variables @code{TimeZone}
28325and @code{PlotRejects};
28326@code{FitRules}, @code{DistribRules}, and other built-in rewrite
28327rules; and @code{PlotData@var{n}} variables generated
28328by the graphics commands. (You can still save these variables by
28329explicitly naming them in an @kbd{s p} command.)
28330
28331@kindex s i
28332@pindex calc-insert-variables
28333The @kbd{s i} (@code{calc-insert-variables}) command writes
28334the values of all Calc variables into a specified buffer.
28335The variables are written with the prefix @code{var-} in the form of
28336Lisp @code{setq} commands
28337which store the values in string form. You can place these commands
28338in your Calc init file (or @file{.emacs}) if you wish, though in this case it
28339would be easier to use @kbd{s p @key{RET}}. (Note that @kbd{s i}
28340omits the same set of variables as @w{@kbd{s p @key{RET}}}; the difference
28341is that @kbd{s i} will store the variables in any buffer, and it also
28342stores in a more human-readable format.)
28343
28344@node Let Command, Evaluates-To Operator, Operations on Variables, Store and Recall
28345@section The Let Command
28346
28347@noindent
28348@kindex s l
28349@pindex calc-let
28350@cindex Variables, temporary assignment
28351@cindex Temporary assignment to variables
28352If you have an expression like @samp{a+b^2} on the stack and you wish to
28353compute its value where @expr{b=3}, you can simply store 3 in @expr{b} and
28354then press @kbd{=} to reevaluate the formula. This has the side-effect
28355of leaving the stored value of 3 in @expr{b} for future operations.
28356
28357The @kbd{s l} (@code{calc-let}) command evaluates a formula under a
28358@emph{temporary} assignment of a variable. It stores the value on the
28359top of the stack into the specified variable, then evaluates the
28360second-to-top stack entry, then restores the original value (or lack of one)
28361in the variable. Thus after @kbd{'@w{ }a+b^2 @key{RET} 3 s l b @key{RET}},
28362the stack will contain the formula @samp{a + 9}. The subsequent command
28363@kbd{@w{5 s l a} @key{RET}} will replace this formula with the number 14.
28364The variables @samp{a} and @samp{b} are not permanently affected in any way
28365by these commands.
28366
28367The value on the top of the stack may be an equation or assignment, or
28368a vector of equations or assignments, in which case the default will be
28369analogous to the case of @kbd{s t @key{RET}}. @xref{Storing Variables}.
28370
28371Also, you can answer the variable-name prompt with an equation or
28372assignment: @kbd{s l b=3 @key{RET}} is the same as storing 3 on the stack
28373and typing @kbd{s l b @key{RET}}.
28374
28375The @kbd{a b} (@code{calc-substitute}) command is another way to substitute
28376a variable with a value in a formula. It does an actual substitution
28377rather than temporarily assigning the variable and evaluating. For
28378example, letting @expr{n=2} in @samp{f(n pi)} with @kbd{a b} will
28379produce @samp{f(2 pi)}, whereas @kbd{s l} would give @samp{f(6.28)}
28380since the evaluation step will also evaluate @code{pi}.
28381
28382@node Evaluates-To Operator, , Let Command, Store and Recall
28383@section The Evaluates-To Operator
28384
28385@noindent
28386@tindex evalto
28387@tindex =>
28388@cindex Evaluates-to operator
28389@cindex @samp{=>} operator
28390The special algebraic symbol @samp{=>} is known as the @dfn{evaluates-to
28391operator}. (It will show up as an @code{evalto} function call in
28392other language modes like Pascal and La@TeX{}.) This is a binary
28393operator, that is, it has a lefthand and a righthand argument,
28394although it can be entered with the righthand argument omitted.
28395
28396A formula like @samp{@var{a} => @var{b}} is evaluated by Calc as
28397follows: First, @var{a} is not simplified or modified in any
28398way. The previous value of argument @var{b} is thrown away; the
28399formula @var{a} is then copied and evaluated as if by the @kbd{=}
28400command according to all current modes and stored variable values,
28401and the result is installed as the new value of @var{b}.
28402
28403For example, suppose you enter the algebraic formula @samp{2 + 3 => 17}.
28404The number 17 is ignored, and the lefthand argument is left in its
28405unevaluated form; the result is the formula @samp{2 + 3 => 5}.
28406
28407@kindex s =
28408@pindex calc-evalto
28409You can enter an @samp{=>} formula either directly using algebraic
28410entry (in which case the righthand side may be omitted since it is
28411going to be replaced right away anyhow), or by using the @kbd{s =}
28412(@code{calc-evalto}) command, which takes @var{a} from the stack
28413and replaces it with @samp{@var{a} => @var{b}}.
28414
28415Calc keeps track of all @samp{=>} operators on the stack, and
28416recomputes them whenever anything changes that might affect their
28417values, i.e., a mode setting or variable value. This occurs only
28418if the @samp{=>} operator is at the top level of the formula, or
28419if it is part of a top-level vector. In other words, pushing
28420@samp{2 + (a => 17)} will change the 17 to the actual value of
28421@samp{a} when you enter the formula, but the result will not be
28422dynamically updated when @samp{a} is changed later because the
28423@samp{=>} operator is buried inside a sum. However, a vector
28424of @samp{=>} operators will be recomputed, since it is convenient
28425to push a vector like @samp{[a =>, b =>, c =>]} on the stack to
28426make a concise display of all the variables in your problem.
28427(Another way to do this would be to use @samp{[a, b, c] =>},
28428which provides a slightly different format of display. You
28429can use whichever you find easiest to read.)
28430
28431@kindex m C
28432@pindex calc-auto-recompute
28433The @kbd{m C} (@code{calc-auto-recompute}) command allows you to
28434turn this automatic recomputation on or off. If you turn
28435recomputation off, you must explicitly recompute an @samp{=>}
28436operator on the stack in one of the usual ways, such as by
28437pressing @kbd{=}. Turning recomputation off temporarily can save
28438a lot of time if you will be changing several modes or variables
28439before you look at the @samp{=>} entries again.
28440
28441Most commands are not especially useful with @samp{=>} operators
28442as arguments. For example, given @samp{x + 2 => 17}, it won't
28443work to type @kbd{1 +} to get @samp{x + 3 => 18}. If you want
28444to operate on the lefthand side of the @samp{=>} operator on
28445the top of the stack, type @kbd{j 1} (that's the digit ``one'')
28446to select the lefthand side, execute your commands, then type
28447@kbd{j u} to unselect.
28448
28449All current modes apply when an @samp{=>} operator is computed,
28450including the current simplification mode. Recall that the
28451formula @samp{x + y + x} is not handled by Calc's default
28452simplifications, but the @kbd{a s} command will reduce it to
28453the simpler form @samp{y + 2 x}. You can also type @kbd{m A}
28454to enable an Algebraic Simplification mode in which the
28455equivalent of @kbd{a s} is used on all of Calc's results.
28456If you enter @samp{x + y + x =>} normally, the result will
28457be @samp{x + y + x => x + y + x}. If you change to
28458Algebraic Simplification mode, the result will be
28459@samp{x + y + x => y + 2 x}. However, just pressing @kbd{a s}
28460once will have no effect on @samp{x + y + x => x + y + x},
28461because the righthand side depends only on the lefthand side
28462and the current mode settings, and the lefthand side is not
28463affected by commands like @kbd{a s}.
28464
28465The ``let'' command (@kbd{s l}) has an interesting interaction
28466with the @samp{=>} operator. The @kbd{s l} command evaluates the
28467second-to-top stack entry with the top stack entry supplying
28468a temporary value for a given variable. As you might expect,
28469if that stack entry is an @samp{=>} operator its righthand
28470side will temporarily show this value for the variable. In
28471fact, all @samp{=>}s on the stack will be updated if they refer
28472to that variable. But this change is temporary in the sense
28473that the next command that causes Calc to look at those stack
28474entries will make them revert to the old variable value.
28475
28476@smallexample
28477@group
284782: a => a 2: a => 17 2: a => a
284791: a + 1 => a + 1 1: a + 1 => 18 1: a + 1 => a + 1
28480 . . .
28481
28482 17 s l a @key{RET} p 8 @key{RET}
28483@end group
28484@end smallexample
28485
28486Here the @kbd{p 8} command changes the current precision,
28487thus causing the @samp{=>} forms to be recomputed after the
28488influence of the ``let'' is gone. The @kbd{d @key{SPC}} command
28489(@code{calc-refresh}) is a handy way to force the @samp{=>}
28490operators on the stack to be recomputed without any other
28491side effects.
28492
28493@kindex s :
28494@pindex calc-assign
28495@tindex assign
28496@tindex :=
28497Embedded mode also uses @samp{=>} operators. In Embedded mode,
28498the lefthand side of an @samp{=>} operator can refer to variables
28499assigned elsewhere in the file by @samp{:=} operators. The
28500assignment operator @samp{a := 17} does not actually do anything
28501by itself. But Embedded mode recognizes it and marks it as a sort
28502of file-local definition of the variable. You can enter @samp{:=}
28503operators in Algebraic mode, or by using the @kbd{s :}
28504(@code{calc-assign}) [@code{assign}] command which takes a variable
28505and value from the stack and replaces them with an assignment.
28506
28507@xref{TeX and LaTeX Language Modes}, for the way @samp{=>} appears in
28508@TeX{} language output. The @dfn{eqn} mode gives similar
28509treatment to @samp{=>}.
28510
28511@node Graphics, Kill and Yank, Store and Recall, Top
28512@chapter Graphics
28513
28514@noindent
28515The commands for graphing data begin with the @kbd{g} prefix key. Calc
28516uses GNUPLOT 2.0 or later to do graphics. These commands will only work
28517if GNUPLOT is available on your system. (While GNUPLOT sounds like
28518a relative of GNU Emacs, it is actually completely unrelated.
28519However, it is free software. It can be obtained from
28520@samp{http://www.gnuplot.info}.)
28521
28522@vindex calc-gnuplot-name
28523If you have GNUPLOT installed on your system but Calc is unable to
28524find it, you may need to set the @code{calc-gnuplot-name} variable
28525in your Calc init file or @file{.emacs}. You may also need to set some Lisp
28526variables to show Calc how to run GNUPLOT on your system; these
28527are described under @kbd{g D} and @kbd{g O} below. If you are
28528using the X window system, Calc will configure GNUPLOT for you
28529automatically. If you have GNUPLOT 3.0 or later and you are not using X,
28530Calc will configure GNUPLOT to display graphs using simple character
28531graphics that will work on any terminal.
28532
28533@menu
28534* Basic Graphics::
28535* Three Dimensional Graphics::
28536* Managing Curves::
28537* Graphics Options::
28538* Devices::
28539@end menu
28540
28541@node Basic Graphics, Three Dimensional Graphics, Graphics, Graphics
28542@section Basic Graphics
28543
28544@noindent
28545@kindex g f
28546@pindex calc-graph-fast
28547The easiest graphics command is @kbd{g f} (@code{calc-graph-fast}).
28548This command takes two vectors of equal length from the stack.
28549The vector at the top of the stack represents the ``y'' values of
28550the various data points. The vector in the second-to-top position
28551represents the corresponding ``x'' values. This command runs
28552GNUPLOT (if it has not already been started by previous graphing
28553commands) and displays the set of data points. The points will
28554be connected by lines, and there will also be some kind of symbol
28555to indicate the points themselves.
28556
28557The ``x'' entry may instead be an interval form, in which case suitable
28558``x'' values are interpolated between the minimum and maximum values of
28559the interval (whether the interval is open or closed is ignored).
28560
28561The ``x'' entry may also be a number, in which case Calc uses the
28562sequence of ``x'' values @expr{x}, @expr{x+1}, @expr{x+2}, etc.
28563(Generally the number 0 or 1 would be used for @expr{x} in this case.)
28564
28565The ``y'' entry may be any formula instead of a vector. Calc effectively
28566uses @kbd{N} (@code{calc-eval-num}) to evaluate variables in the formula;
28567the result of this must be a formula in a single (unassigned) variable.
28568The formula is plotted with this variable taking on the various ``x''
28569values. Graphs of formulas by default use lines without symbols at the
28570computed data points. Note that if neither ``x'' nor ``y'' is a vector,
28571Calc guesses at a reasonable number of data points to use. See the
28572@kbd{g N} command below. (The ``x'' values must be either a vector
28573or an interval if ``y'' is a formula.)
28574
28575@ignore
28576@starindex
28577@end ignore
28578@tindex xy
28579If ``y'' is (or evaluates to) a formula of the form
28580@samp{xy(@var{x}, @var{y})} then the result is a
28581parametric plot. The two arguments of the fictitious @code{xy} function
28582are used as the ``x'' and ``y'' coordinates of the curve, respectively.
28583In this case the ``x'' vector or interval you specified is not directly
28584visible in the graph. For example, if ``x'' is the interval @samp{[0..360]}
28585and ``y'' is the formula @samp{xy(sin(t), cos(t))}, the resulting graph
28586will be a circle.
28587
28588Also, ``x'' and ``y'' may each be variable names, in which case Calc
28589looks for suitable vectors, intervals, or formulas stored in those
28590variables.
28591
28592The ``x'' and ``y'' values for the data points (as pulled from the vectors,
28593calculated from the formulas, or interpolated from the intervals) should
28594be real numbers (integers, fractions, or floats). One exception to this
28595is that the ``y'' entry can consist of a vector of numbers combined with
28596error forms, in which case the points will be plotted with the
28597appropriate error bars. Other than this, if either the ``x''
28598value or the ``y'' value of a given data point is not a real number, that
28599data point will be omitted from the graph. The points on either side
28600of the invalid point will @emph{not} be connected by a line.
28601
28602See the documentation for @kbd{g a} below for a description of the way
28603numeric prefix arguments affect @kbd{g f}.
28604
28605@cindex @code{PlotRejects} variable
28606@vindex PlotRejects
28607If you store an empty vector in the variable @code{PlotRejects}
28608(i.e., @kbd{[ ] s t PlotRejects}), Calc will append information to
28609this vector for every data point which was rejected because its
28610``x'' or ``y'' values were not real numbers. The result will be
28611a matrix where each row holds the curve number, data point number,
28612``x'' value, and ``y'' value for a rejected data point.
28613@xref{Evaluates-To Operator}, for a handy way to keep tabs on the
28614current value of @code{PlotRejects}. @xref{Operations on Variables},
28615for the @kbd{s R} command which is another easy way to examine
28616@code{PlotRejects}.
28617
28618@kindex g c
28619@pindex calc-graph-clear
28620To clear the graphics display, type @kbd{g c} (@code{calc-graph-clear}).
28621If the GNUPLOT output device is an X window, the window will go away.
28622Effects on other kinds of output devices will vary. You don't need
28623to use @kbd{g c} if you don't want to---if you give another @kbd{g f}
28624or @kbd{g p} command later on, it will reuse the existing graphics
28625window if there is one.
28626
28627@node Three Dimensional Graphics, Managing Curves, Basic Graphics, Graphics
28628@section Three-Dimensional Graphics
28629
28630@kindex g F
28631@pindex calc-graph-fast-3d
28632The @kbd{g F} (@code{calc-graph-fast-3d}) command makes a three-dimensional
28633graph. It works only if you have GNUPLOT 3.0 or later; with GNUPLOT 2.0,
28634you will see a GNUPLOT error message if you try this command.
28635
28636The @kbd{g F} command takes three values from the stack, called ``x'',
28637``y'', and ``z'', respectively. As was the case for 2D graphs, there
28638are several options for these values.
28639
28640In the first case, ``x'' and ``y'' are each vectors (not necessarily of
28641the same length); either or both may instead be interval forms. The
28642``z'' value must be a matrix with the same number of rows as elements
28643in ``x'', and the same number of columns as elements in ``y''. The
28644result is a surface plot where
28645@texline @math{z_{ij}}
28646@infoline @expr{z_ij}
28647is the height of the point
28648at coordinate @expr{(x_i, y_j)} on the surface. The 3D graph will
28649be displayed from a certain default viewpoint; you can change this
28650viewpoint by adding a @samp{set view} to the @samp{*Gnuplot Commands*}
28651buffer as described later. See the GNUPLOT documentation for a
28652description of the @samp{set view} command.
28653
28654Each point in the matrix will be displayed as a dot in the graph,
28655and these points will be connected by a grid of lines (@dfn{isolines}).
28656
28657In the second case, ``x'', ``y'', and ``z'' are all vectors of equal
28658length. The resulting graph displays a 3D line instead of a surface,
28659where the coordinates of points along the line are successive triplets
28660of values from the input vectors.
28661
28662In the third case, ``x'' and ``y'' are vectors or interval forms, and
28663``z'' is any formula involving two variables (not counting variables
28664with assigned values). These variables are sorted into alphabetical
28665order; the first takes on values from ``x'' and the second takes on
28666values from ``y'' to form a matrix of results that are graphed as a
286673D surface.
28668
28669@ignore
28670@starindex
28671@end ignore
28672@tindex xyz
28673If the ``z'' formula evaluates to a call to the fictitious function
28674@samp{xyz(@var{x}, @var{y}, @var{z})}, then the result is a
28675``parametric surface.'' In this case, the axes of the graph are
28676taken from the @var{x} and @var{y} values in these calls, and the
28677``x'' and ``y'' values from the input vectors or intervals are used only
28678to specify the range of inputs to the formula. For example, plotting
28679@samp{[0..360], [0..180], xyz(sin(x)*sin(y), cos(x)*sin(y), cos(y))}
28680will draw a sphere. (Since the default resolution for 3D plots is
286815 steps in each of ``x'' and ``y'', this will draw a very crude
28682sphere. You could use the @kbd{g N} command, described below, to
28683increase this resolution, or specify the ``x'' and ``y'' values as
28684vectors with more than 5 elements.
28685
28686It is also possible to have a function in a regular @kbd{g f} plot
28687evaluate to an @code{xyz} call. Since @kbd{g f} plots a line, not
28688a surface, the result will be a 3D parametric line. For example,
28689@samp{[[0..720], xyz(sin(x), cos(x), x)]} will plot two turns of a
28690helix (a three-dimensional spiral).
28691
28692As for @kbd{g f}, each of ``x'', ``y'', and ``z'' may instead be
28693variables containing the relevant data.
28694
28695@node Managing Curves, Graphics Options, Three Dimensional Graphics, Graphics
28696@section Managing Curves
28697
28698@noindent
28699The @kbd{g f} command is really shorthand for the following commands:
28700@kbd{C-u g d g a g p}. Likewise, @w{@kbd{g F}} is shorthand for
28701@kbd{C-u g d g A g p}. You can gain more control over your graph
28702by using these commands directly.
28703
28704@kindex g a
28705@pindex calc-graph-add
28706The @kbd{g a} (@code{calc-graph-add}) command adds the ``curve''
28707represented by the two values on the top of the stack to the current
28708graph. You can have any number of curves in the same graph. When
28709you give the @kbd{g p} command, all the curves will be drawn superimposed
28710on the same axes.
28711
28712The @kbd{g a} command (and many others that affect the current graph)
28713will cause a special buffer, @samp{*Gnuplot Commands*}, to be displayed
28714in another window. This buffer is a template of the commands that will
28715be sent to GNUPLOT when it is time to draw the graph. The first
28716@kbd{g a} command adds a @code{plot} command to this buffer. Succeeding
28717@kbd{g a} commands add extra curves onto that @code{plot} command.
28718Other graph-related commands put other GNUPLOT commands into this
28719buffer. In normal usage you never need to work with this buffer
28720directly, but you can if you wish. The only constraint is that there
28721must be only one @code{plot} command, and it must be the last command
28722in the buffer. If you want to save and later restore a complete graph
28723configuration, you can use regular Emacs commands to save and restore
28724the contents of the @samp{*Gnuplot Commands*} buffer.
28725
28726@vindex PlotData1
28727@vindex PlotData2
28728If the values on the stack are not variable names, @kbd{g a} will invent
28729variable names for them (of the form @samp{PlotData@var{n}}) and store
28730the values in those variables. The ``x'' and ``y'' variables are what
28731go into the @code{plot} command in the template. If you add a curve
28732that uses a certain variable and then later change that variable, you
28733can replot the graph without having to delete and re-add the curve.
28734That's because the variable name, not the vector, interval or formula
28735itself, is what was added by @kbd{g a}.
28736
28737A numeric prefix argument on @kbd{g a} or @kbd{g f} changes the way
28738stack entries are interpreted as curves. With a positive prefix
28739argument @expr{n}, the top @expr{n} stack entries are ``y'' values
28740for @expr{n} different curves which share a common ``x'' value in
28741the @expr{n+1}st stack entry. (Thus @kbd{g a} with no prefix
28742argument is equivalent to @kbd{C-u 1 g a}.)
28743
28744A prefix of zero or plain @kbd{C-u} means to take two stack entries,
28745``x'' and ``y'' as usual, but to interpret ``y'' as a vector of
28746``y'' values for several curves that share a common ``x''.
28747
28748A negative prefix argument tells Calc to read @expr{n} vectors from
28749the stack; each vector @expr{[x, y]} describes an independent curve.
28750This is the only form of @kbd{g a} that creates several curves at once
28751that don't have common ``x'' values. (Of course, the range of ``x''
28752values covered by all the curves ought to be roughly the same if
28753they are to look nice on the same graph.)
28754
28755For example, to plot
28756@texline @math{\sin n x}
28757@infoline @expr{sin(n x)}
28758for integers @expr{n}
28759from 1 to 5, you could use @kbd{v x} to create a vector of integers
28760(@expr{n}), then @kbd{V M '} or @kbd{V M $} to map @samp{sin(n x)}
28761across this vector. The resulting vector of formulas is suitable
28762for use as the ``y'' argument to a @kbd{C-u g a} or @kbd{C-u g f}
28763command.
28764
28765@kindex g A
28766@pindex calc-graph-add-3d
28767The @kbd{g A} (@code{calc-graph-add-3d}) command adds a 3D curve
28768to the graph. It is not valid to intermix 2D and 3D curves in a
28769single graph. This command takes three arguments, ``x'', ``y'',
28770and ``z'', from the stack. With a positive prefix @expr{n}, it
28771takes @expr{n+2} arguments (common ``x'' and ``y'', plus @expr{n}
28772separate ``z''s). With a zero prefix, it takes three stack entries
28773but the ``z'' entry is a vector of curve values. With a negative
28774prefix @expr{-n}, it takes @expr{n} vectors of the form @expr{[x, y, z]}.
28775The @kbd{g A} command works by adding a @code{splot} (surface-plot)
28776command to the @samp{*Gnuplot Commands*} buffer.
28777
28778(Although @kbd{g a} adds a 2D @code{plot} command to the
28779@samp{*Gnuplot Commands*} buffer, Calc changes this to @code{splot}
28780before sending it to GNUPLOT if it notices that the data points are
28781evaluating to @code{xyz} calls. It will not work to mix 2D and 3D
28782@kbd{g a} curves in a single graph, although Calc does not currently
28783check for this.)
28784
28785@kindex g d
28786@pindex calc-graph-delete
28787The @kbd{g d} (@code{calc-graph-delete}) command deletes the most
28788recently added curve from the graph. It has no effect if there are
28789no curves in the graph. With a numeric prefix argument of any kind,
28790it deletes all of the curves from the graph.
28791
28792@kindex g H
28793@pindex calc-graph-hide
28794The @kbd{g H} (@code{calc-graph-hide}) command ``hides'' or ``unhides''
28795the most recently added curve. A hidden curve will not appear in
28796the actual plot, but information about it such as its name and line and
28797point styles will be retained.
28798
28799@kindex g j
28800@pindex calc-graph-juggle
28801The @kbd{g j} (@code{calc-graph-juggle}) command moves the curve
28802at the end of the list (the ``most recently added curve'') to the
28803front of the list. The next-most-recent curve is thus exposed for
28804@w{@kbd{g d}} or similar commands to use. With @kbd{g j} you can work
28805with any curve in the graph even though curve-related commands only
28806affect the last curve in the list.
28807
28808@kindex g p
28809@pindex calc-graph-plot
28810The @kbd{g p} (@code{calc-graph-plot}) command uses GNUPLOT to draw
28811the graph described in the @samp{*Gnuplot Commands*} buffer. Any
28812GNUPLOT parameters which are not defined by commands in this buffer
28813are reset to their default values. The variables named in the @code{plot}
28814command are written to a temporary data file and the variable names
28815are then replaced by the file name in the template. The resulting
28816plotting commands are fed to the GNUPLOT program. See the documentation
28817for the GNUPLOT program for more specific information. All temporary
28818files are removed when Emacs or GNUPLOT exits.
28819
28820If you give a formula for ``y'', Calc will remember all the values that
28821it calculates for the formula so that later plots can reuse these values.
28822Calc throws out these saved values when you change any circumstances
28823that may affect the data, such as switching from Degrees to Radians
28824mode, or changing the value of a parameter in the formula. You can
28825force Calc to recompute the data from scratch by giving a negative
28826numeric prefix argument to @kbd{g p}.
28827
28828Calc uses a fairly rough step size when graphing formulas over intervals.
28829This is to ensure quick response. You can ``refine'' a plot by giving
28830a positive numeric prefix argument to @kbd{g p}. Calc goes through
28831the data points it has computed and saved from previous plots of the
28832function, and computes and inserts a new data point midway between
28833each of the existing points. You can refine a plot any number of times,
28834but beware that the amount of calculation involved doubles each time.
28835
28836Calc does not remember computed values for 3D graphs. This means the
28837numerix prefix argument, if any, to @kbd{g p} is effectively ignored if
28838the current graph is three-dimensional.
28839
28840@kindex g P
28841@pindex calc-graph-print
28842The @kbd{g P} (@code{calc-graph-print}) command is like @kbd{g p},
28843except that it sends the output to a printer instead of to the
28844screen. More precisely, @kbd{g p} looks for @samp{set terminal}
28845or @samp{set output} commands in the @samp{*Gnuplot Commands*} buffer;
28846lacking these it uses the default settings. However, @kbd{g P}
28847ignores @samp{set terminal} and @samp{set output} commands and
28848uses a different set of default values. All of these values are
28849controlled by the @kbd{g D} and @kbd{g O} commands discussed below.
28850Provided everything is set up properly, @kbd{g p} will plot to
28851the screen unless you have specified otherwise and @kbd{g P} will
28852always plot to the printer.
28853
28854@node Graphics Options, Devices, Managing Curves, Graphics
28855@section Graphics Options
28856
28857@noindent
28858@kindex g g
28859@pindex calc-graph-grid
28860The @kbd{g g} (@code{calc-graph-grid}) command turns the ``grid''
28861on and off. It is off by default; tick marks appear only at the
28862edges of the graph. With the grid turned on, dotted lines appear
28863across the graph at each tick mark. Note that this command only
28864changes the setting in @samp{*Gnuplot Commands*}; to see the effects
28865of the change you must give another @kbd{g p} command.
28866
28867@kindex g b
28868@pindex calc-graph-border
28869The @kbd{g b} (@code{calc-graph-border}) command turns the border
28870(the box that surrounds the graph) on and off. It is on by default.
28871This command will only work with GNUPLOT 3.0 and later versions.
28872
28873@kindex g k
28874@pindex calc-graph-key
28875The @kbd{g k} (@code{calc-graph-key}) command turns the ``key''
28876on and off. The key is a chart in the corner of the graph that
28877shows the correspondence between curves and line styles. It is
28878off by default, and is only really useful if you have several
28879curves on the same graph.
28880
28881@kindex g N
28882@pindex calc-graph-num-points
28883The @kbd{g N} (@code{calc-graph-num-points}) command allows you
28884to select the number of data points in the graph. This only affects
28885curves where neither ``x'' nor ``y'' is specified as a vector.
28886Enter a blank line to revert to the default value (initially 15).
28887With no prefix argument, this command affects only the current graph.
28888With a positive prefix argument this command changes or, if you enter
28889a blank line, displays the default number of points used for all
28890graphs created by @kbd{g a} that don't specify the resolution explicitly.
28891With a negative prefix argument, this command changes or displays
28892the default value (initially 5) used for 3D graphs created by @kbd{g A}.
28893Note that a 3D setting of 5 means that a total of @expr{5^2 = 25} points
28894will be computed for the surface.
28895
28896Data values in the graph of a function are normally computed to a
28897precision of five digits, regardless of the current precision at the
28898time. This is usually more than adequate, but there are cases where
28899it will not be. For example, plotting @expr{1 + x} with @expr{x} in the
28900interval @samp{[0 ..@: 1e-6]} will round all the data points down
28901to 1.0! Putting the command @samp{set precision @var{n}} in the
28902@samp{*Gnuplot Commands*} buffer will cause the data to be computed
28903at precision @var{n} instead of 5. Since this is such a rare case,
28904there is no keystroke-based command to set the precision.
28905
28906@kindex g h
28907@pindex calc-graph-header
28908The @kbd{g h} (@code{calc-graph-header}) command sets the title
28909for the graph. This will show up centered above the graph.
28910The default title is blank (no title).
28911
28912@kindex g n
28913@pindex calc-graph-name
28914The @kbd{g n} (@code{calc-graph-name}) command sets the title of an
28915individual curve. Like the other curve-manipulating commands, it
28916affects the most recently added curve, i.e., the last curve on the
28917list in the @samp{*Gnuplot Commands*} buffer. To set the title of
28918the other curves you must first juggle them to the end of the list
28919with @kbd{g j}, or edit the @samp{*Gnuplot Commands*} buffer by hand.
28920Curve titles appear in the key; if the key is turned off they are
28921not used.
28922
28923@kindex g t
28924@kindex g T
28925@pindex calc-graph-title-x
28926@pindex calc-graph-title-y
28927The @kbd{g t} (@code{calc-graph-title-x}) and @kbd{g T}
28928(@code{calc-graph-title-y}) commands set the titles on the ``x''
28929and ``y'' axes, respectively. These titles appear next to the
28930tick marks on the left and bottom edges of the graph, respectively.
28931Calc does not have commands to control the tick marks themselves,
28932but you can edit them into the @samp{*Gnuplot Commands*} buffer if
28933you wish. See the GNUPLOT documentation for details.
28934
28935@kindex g r
28936@kindex g R
28937@pindex calc-graph-range-x
28938@pindex calc-graph-range-y
28939The @kbd{g r} (@code{calc-graph-range-x}) and @kbd{g R}
28940(@code{calc-graph-range-y}) commands set the range of values on the
28941``x'' and ``y'' axes, respectively. You are prompted to enter a
28942suitable range. This should be either a pair of numbers of the
28943form, @samp{@var{min}:@var{max}}, or a blank line to revert to the
28944default behavior of setting the range based on the range of values
28945in the data, or @samp{$} to take the range from the top of the stack.
28946Ranges on the stack can be represented as either interval forms or
28947vectors: @samp{[@var{min} ..@: @var{max}]} or @samp{[@var{min}, @var{max}]}.
28948
28949@kindex g l
28950@kindex g L
28951@pindex calc-graph-log-x
28952@pindex calc-graph-log-y
28953The @kbd{g l} (@code{calc-graph-log-x}) and @kbd{g L} (@code{calc-graph-log-y})
28954commands allow you to set either or both of the axes of the graph to
28955be logarithmic instead of linear.
28956
28957@kindex g C-l
28958@kindex g C-r
28959@kindex g C-t
28960@pindex calc-graph-log-z
28961@pindex calc-graph-range-z
28962@pindex calc-graph-title-z
28963For 3D plots, @kbd{g C-t}, @kbd{g C-r}, and @kbd{g C-l} (those are
28964letters with the Control key held down) are the corresponding commands
28965for the ``z'' axis.
28966
28967@kindex g z
28968@kindex g Z
28969@pindex calc-graph-zero-x
28970@pindex calc-graph-zero-y
28971The @kbd{g z} (@code{calc-graph-zero-x}) and @kbd{g Z}
28972(@code{calc-graph-zero-y}) commands control whether a dotted line is
28973drawn to indicate the ``x'' and/or ``y'' zero axes. (These are the same
28974dotted lines that would be drawn there anyway if you used @kbd{g g} to
28975turn the ``grid'' feature on.) Zero-axis lines are on by default, and
28976may be turned off only in GNUPLOT 3.0 and later versions. They are
28977not available for 3D plots.
28978
28979@kindex g s
28980@pindex calc-graph-line-style
28981The @kbd{g s} (@code{calc-graph-line-style}) command turns the connecting
28982lines on or off for the most recently added curve, and optionally selects
28983the style of lines to be used for that curve. Plain @kbd{g s} simply
28984toggles the lines on and off. With a numeric prefix argument, @kbd{g s}
28985turns lines on and sets a particular line style. Line style numbers
28986start at one and their meanings vary depending on the output device.
28987GNUPLOT guarantees that there will be at least six different line styles
28988available for any device.
28989
28990@kindex g S
28991@pindex calc-graph-point-style
28992The @kbd{g S} (@code{calc-graph-point-style}) command similarly turns
28993the symbols at the data points on or off, or sets the point style.
28994If you turn both lines and points off, the data points will show as
28995tiny dots. If the ``y'' values being plotted contain error forms and
28996the connecting lines are turned off, then this command will also turn
28997the error bars on or off.
28998
28999@cindex @code{LineStyles} variable
29000@cindex @code{PointStyles} variable
29001@vindex LineStyles
29002@vindex PointStyles
29003Another way to specify curve styles is with the @code{LineStyles} and
29004@code{PointStyles} variables. These variables initially have no stored
29005values, but if you store a vector of integers in one of these variables,
29006the @kbd{g a} and @kbd{g f} commands will use those style numbers
29007instead of the defaults for new curves that are added to the graph.
29008An entry should be a positive integer for a specific style, or 0 to let
29009the style be chosen automatically, or @mathit{-1} to turn off lines or points
29010altogether. If there are more curves than elements in the vector, the
29011last few curves will continue to have the default styles. Of course,
29012you can later use @kbd{g s} and @kbd{g S} to change any of these styles.
29013
29014For example, @kbd{'[2 -1 3] @key{RET} s t LineStyles} causes the first curve
29015to have lines in style number 2, the second curve to have no connecting
29016lines, and the third curve to have lines in style 3. Point styles will
29017still be assigned automatically, but you could store another vector in
29018@code{PointStyles} to define them, too.
29019
29020@node Devices, , Graphics Options, Graphics
29021@section Graphical Devices
29022
29023@noindent
29024@kindex g D
29025@pindex calc-graph-device
29026The @kbd{g D} (@code{calc-graph-device}) command sets the device name
29027(or ``terminal name'' in GNUPLOT lingo) to be used by @kbd{g p} commands
29028on this graph. It does not affect the permanent default device name.
29029If you enter a blank name, the device name reverts to the default.
29030Enter @samp{?} to see a list of supported devices.
29031
29032With a positive numeric prefix argument, @kbd{g D} instead sets
29033the default device name, used by all plots in the future which do
29034not override it with a plain @kbd{g D} command. If you enter a
29035blank line this command shows you the current default. The special
29036name @code{default} signifies that Calc should choose @code{x11} if
29037the X window system is in use (as indicated by the presence of a
29038@code{DISPLAY} environment variable), or otherwise @code{dumb} under
29039GNUPLOT 3.0 and later, or @code{postscript} under GNUPLOT 2.0.
29040This is the initial default value.
29041
29042The @code{dumb} device is an interface to ``dumb terminals,'' i.e.,
29043terminals with no special graphics facilities. It writes a crude
29044picture of the graph composed of characters like @code{-} and @code{|}
29045to a buffer called @samp{*Gnuplot Trail*}, which Calc then displays.
29046The graph is made the same size as the Emacs screen, which on most
29047dumb terminals will be
29048@texline @math{80\times24}
29049@infoline 80x24
29050characters. The graph is displayed in
29051an Emacs ``recursive edit''; type @kbd{q} or @kbd{C-c C-c} to exit
29052the recursive edit and return to Calc. Note that the @code{dumb}
29053device is present only in GNUPLOT 3.0 and later versions.
29054
29055The word @code{dumb} may be followed by two numbers separated by
29056spaces. These are the desired width and height of the graph in
29057characters. Also, the device name @code{big} is like @code{dumb}
29058but creates a graph four times the width and height of the Emacs
29059screen. You will then have to scroll around to view the entire
29060graph. In the @samp{*Gnuplot Trail*} buffer, @key{SPC}, @key{DEL},
29061@kbd{<}, and @kbd{>} are defined to scroll by one screenful in each
29062of the four directions.
29063
29064With a negative numeric prefix argument, @kbd{g D} sets or displays
29065the device name used by @kbd{g P} (@code{calc-graph-print}). This
29066is initially @code{postscript}. If you don't have a PostScript
29067printer, you may decide once again to use @code{dumb} to create a
29068plot on any text-only printer.
29069
29070@kindex g O
29071@pindex calc-graph-output
29072The @kbd{g O} (@code{calc-graph-output}) command sets the name of
29073the output file used by GNUPLOT. For some devices, notably @code{x11},
29074there is no output file and this information is not used. Many other
29075``devices'' are really file formats like @code{postscript}; in these
29076cases the output in the desired format goes into the file you name
29077with @kbd{g O}. Type @kbd{g O stdout @key{RET}} to set GNUPLOT to write
29078to its standard output stream, i.e., to @samp{*Gnuplot Trail*}.
29079This is the default setting.
29080
29081Another special output name is @code{tty}, which means that GNUPLOT
29082is going to write graphics commands directly to its standard output,
29083which you wish Emacs to pass through to your terminal. Tektronix
29084graphics terminals, among other devices, operate this way. Calc does
29085this by telling GNUPLOT to write to a temporary file, then running a
29086sub-shell executing the command @samp{cat tempfile >/dev/tty}. On
29087typical Unix systems, this will copy the temporary file directly to
29088the terminal, bypassing Emacs entirely. You will have to type @kbd{C-l}
29089to Emacs afterwards to refresh the screen.
29090
29091Once again, @kbd{g O} with a positive or negative prefix argument
29092sets the default or printer output file names, respectively. In each
29093case you can specify @code{auto}, which causes Calc to invent a temporary
29094file name for each @kbd{g p} (or @kbd{g P}) command. This temporary file
29095will be deleted once it has been displayed or printed. If the output file
29096name is not @code{auto}, the file is not automatically deleted.
29097
29098The default and printer devices and output files can be saved
29099permanently by the @kbd{m m} (@code{calc-save-modes}) command. The
29100default number of data points (see @kbd{g N}) and the X geometry
29101(see @kbd{g X}) are also saved. Other graph information is @emph{not}
29102saved; you can save a graph's configuration simply by saving the contents
29103of the @samp{*Gnuplot Commands*} buffer.
29104
29105@vindex calc-gnuplot-plot-command
29106@vindex calc-gnuplot-default-device
29107@vindex calc-gnuplot-default-output
29108@vindex calc-gnuplot-print-command
29109@vindex calc-gnuplot-print-device
29110@vindex calc-gnuplot-print-output
29111You may wish to configure the default and
29112printer devices and output files for the whole system. The relevant
29113Lisp variables are @code{calc-gnuplot-default-device} and @code{-output},
29114and @code{calc-gnuplot-print-device} and @code{-output}. The output
29115file names must be either strings as described above, or Lisp
29116expressions which are evaluated on the fly to get the output file names.
29117
29118Other important Lisp variables are @code{calc-gnuplot-plot-command} and
29119@code{calc-gnuplot-print-command}, which give the system commands to
29120display or print the output of GNUPLOT, respectively. These may be
29121@code{nil} if no command is necessary, or strings which can include
29122@samp{%s} to signify the name of the file to be displayed or printed.
29123Or, these variables may contain Lisp expressions which are evaluated
29124to display or print the output. These variables are customizable
29125(@pxref{Customizing Calc}).
29126
29127@kindex g x
29128@pindex calc-graph-display
29129The @kbd{g x} (@code{calc-graph-display}) command lets you specify
29130on which X window system display your graphs should be drawn. Enter
29131a blank line to see the current display name. This command has no
29132effect unless the current device is @code{x11}.
29133
29134@kindex g X
29135@pindex calc-graph-geometry
29136The @kbd{g X} (@code{calc-graph-geometry}) command is a similar
29137command for specifying the position and size of the X window.
29138The normal value is @code{default}, which generally means your
29139window manager will let you place the window interactively.
29140Entering @samp{800x500+0+0} would create an 800-by-500 pixel
29141window in the upper-left corner of the screen.
29142
29143The buffer called @samp{*Gnuplot Trail*} holds a transcript of the
29144session with GNUPLOT. This shows the commands Calc has ``typed'' to
29145GNUPLOT and the responses it has received. Calc tries to notice when an
29146error message has appeared here and display the buffer for you when
29147this happens. You can check this buffer yourself if you suspect
29148something has gone wrong.
29149
29150@kindex g C
29151@pindex calc-graph-command
29152The @kbd{g C} (@code{calc-graph-command}) command prompts you to
29153enter any line of text, then simply sends that line to the current
29154GNUPLOT process. The @samp{*Gnuplot Trail*} buffer looks deceptively
29155like a Shell buffer but you can't type commands in it yourself.
29156Instead, you must use @kbd{g C} for this purpose.
29157
29158@kindex g v
29159@kindex g V
29160@pindex calc-graph-view-commands
29161@pindex calc-graph-view-trail
29162The @kbd{g v} (@code{calc-graph-view-commands}) and @kbd{g V}
29163(@code{calc-graph-view-trail}) commands display the @samp{*Gnuplot Commands*}
29164and @samp{*Gnuplot Trail*} buffers, respectively, in another window.
29165This happens automatically when Calc thinks there is something you
29166will want to see in either of these buffers. If you type @kbd{g v}
29167or @kbd{g V} when the relevant buffer is already displayed, the
29168buffer is hidden again.
29169
29170One reason to use @kbd{g v} is to add your own commands to the
29171@samp{*Gnuplot Commands*} buffer. Press @kbd{g v}, then use
29172@kbd{C-x o} to switch into that window. For example, GNUPLOT has
29173@samp{set label} and @samp{set arrow} commands that allow you to
29174annotate your plots. Since Calc doesn't understand these commands,
29175you have to add them to the @samp{*Gnuplot Commands*} buffer
29176yourself, then use @w{@kbd{g p}} to replot using these new commands. Note
29177that your commands must appear @emph{before} the @code{plot} command.
29178To get help on any GNUPLOT feature, type, e.g., @kbd{g C help set label}.
29179You may have to type @kbd{g C @key{RET}} a few times to clear the
29180``press return for more'' or ``subtopic of @dots{}'' requests.
29181Note that Calc always sends commands (like @samp{set nolabel}) to
29182reset all plotting parameters to the defaults before each plot, so
29183to delete a label all you need to do is delete the @samp{set label}
29184line you added (or comment it out with @samp{#}) and then replot
29185with @kbd{g p}.
29186
29187@kindex g q
29188@pindex calc-graph-quit
29189You can use @kbd{g q} (@code{calc-graph-quit}) to kill the GNUPLOT
29190process that is running. The next graphing command you give will
29191start a fresh GNUPLOT process. The word @samp{Graph} appears in
29192the Calc window's mode line whenever a GNUPLOT process is currently
29193running. The GNUPLOT process is automatically killed when you
29194exit Emacs if you haven't killed it manually by then.
29195
29196@kindex g K
29197@pindex calc-graph-kill
29198The @kbd{g K} (@code{calc-graph-kill}) command is like @kbd{g q}
29199except that it also views the @samp{*Gnuplot Trail*} buffer so that
29200you can see the process being killed. This is better if you are
29201killing GNUPLOT because you think it has gotten stuck.
29202
29203@node Kill and Yank, Keypad Mode, Graphics, Top
29204@chapter Kill and Yank Functions
29205
29206@noindent
29207The commands in this chapter move information between the Calculator and
29208other Emacs editing buffers.
29209
29210In many cases Embedded mode is an easier and more natural way to
29211work with Calc from a regular editing buffer. @xref{Embedded Mode}.
29212
29213@menu
29214* Killing From Stack::
29215* Yanking Into Stack::
538c2573
JB
29216* Saving Into Registers::
29217* Inserting From Registers::
4009494e
GM
29218* Grabbing From Buffers::
29219* Yanking Into Buffers::
29220* X Cut and Paste::
29221@end menu
29222
29223@node Killing From Stack, Yanking Into Stack, Kill and Yank, Kill and Yank
29224@section Killing from the Stack
29225
29226@noindent
29227@kindex C-k
29228@pindex calc-kill
29229@kindex M-k
29230@pindex calc-copy-as-kill
29231@kindex C-w
29232@pindex calc-kill-region
29233@kindex M-w
29234@pindex calc-copy-region-as-kill
aee08080 29235@kindex M-C-w
4009494e 29236@cindex Kill ring
aee08080
JB
29237@dfn{Kill} commands are Emacs commands that insert text into the ``kill
29238ring,'' from which it can later be ``yanked'' by a @kbd{C-y} command.
29239Three common kill commands in normal Emacs are @kbd{C-k}, which kills
29240one line, @kbd{C-w}, which kills the region between mark and point, and
29241@kbd{M-w}, which puts the region into the kill ring without actually
29242deleting it. All of these commands work in the Calculator, too,
29243although in the Calculator they operate on whole stack entries, so they
29244``round up'' the specified region to encompass full lines. (To copy
29245only parts of lines, the @kbd{M-C-w} command in the Calculator will copy
29246the region to the kill ring without any ``rounding up'', just like the
29247@kbd{M-w} command in normal Emacs.) Also, @kbd{M-k} has been provided
29248to complete the set; it puts the current line into the kill ring without
29249deleting anything.
4009494e
GM
29250
29251The kill commands are unusual in that they pay attention to the location
aee08080
JB
29252of the cursor in the Calculator buffer. If the cursor is on or below
29253the bottom line, the kill commands operate on the top of the stack.
29254Otherwise, they operate on whatever stack element the cursor is on. The
29255text is copied into the kill ring exactly as it appears on the screen,
29256including line numbers if they are enabled.
4009494e
GM
29257
29258A numeric prefix argument to @kbd{C-k} or @kbd{M-k} affects the number
29259of lines killed. A positive argument kills the current line and @expr{n-1}
29260lines below it. A negative argument kills the @expr{-n} lines above the
29261current line. Again this mirrors the behavior of the standard Emacs
29262@kbd{C-k} command. Although a whole line is always deleted, @kbd{C-k}
29263with no argument copies only the number itself into the kill ring, whereas
29264@kbd{C-k} with a prefix argument of 1 copies the number with its trailing
29265newline.
29266
538c2573 29267@node Yanking Into Stack, Saving Into Registers, Killing From Stack, Kill and Yank
4009494e
GM
29268@section Yanking into the Stack
29269
29270@noindent
29271@kindex C-y
29272@pindex calc-yank
29273The @kbd{C-y} command yanks the most recently killed text back into the
29274Calculator. It pushes this value onto the top of the stack regardless of
29275the cursor position. In general it re-parses the killed text as a number
29276or formula (or a list of these separated by commas or newlines). However if
29277the thing being yanked is something that was just killed from the Calculator
29278itself, its full internal structure is yanked. For example, if you have
29279set the floating-point display mode to show only four significant digits,
29280then killing and re-yanking 3.14159 (which displays as 3.142) will yank the
29281full 3.14159, even though yanking it into any other buffer would yank the
29282number in its displayed form, 3.142. (Since the default display modes
29283show all objects to their full precision, this feature normally makes no
29284difference.)
29285
538c2573
JB
29286@node Saving Into Registers, Inserting From Registers, Yanking Into Stack, Kill and Yank
29287@section Saving into Registers
29288
29289@noindent
29290@kindex r s
29291@pindex calc-copy-to-register
29292@pindex calc-prepend-to-register
29293@pindex calc-append-to-register
29294@cindex Registers
29295An alternative to killing and yanking stack entries is using
29296registers in Calc. Saving stack entries in registers is like
29297saving text in normal Emacs registers; although, like Calc's kill
29298commands, register commands always operate on whole stack
29299entries.
29300
29301Registers in Calc are places to store stack entries for later use;
29302each register is indexed by a single character. To store the current
29303region (rounded up, of course, to include full stack entries) into a
29304register, use the command @kbd{r s} (@code{calc-copy-to-register}).
29305You will then be prompted for a register to use, the next character
29306you type will be the index for the register. To store the region in
29307register @var{r}, the full command will be @kbd{r s @var{r}}. With an
29308argument, @kbd{C-u r s @var{r}}, the region being copied to the
29309register will be deleted from the Calc buffer.
29310
29311It is possible to add additional stack entries to a register. The
29312command @kbd{M-x calc-append-to-register} will prompt for a register,
29313then add the stack entries in the region to the end of the register
29314contents. The command @kbd{M-x calc-prepend-to-register} will
29315similarly prompt for a register and add the stack entries in the
29316region to the beginning of the register contents. Both commands take
29317@kbd{C-u} arguments, which will cause the region to be deleted after being
29318added to the register.
29319
29320@node Inserting From Registers, Grabbing From Buffers, Saving Into Registers, Kill and Yank
29321@section Inserting from Registers
29322@noindent
29323@kindex r i
29324@pindex calc-insert-register
29325The command @kbd{r i} (@code{calc-insert-register}) will prompt for a
29326register, then insert the contents of that register into the
29327Calculator. If the contents of the register were placed there from
29328within Calc, then the full internal structure of the contents will be
29329inserted into the Calculator, otherwise whatever text is in the
29330register is reparsed and then inserted into the Calculator.
29331
29332@node Grabbing From Buffers, Yanking Into Buffers, Inserting From Registers, Kill and Yank
4009494e
GM
29333@section Grabbing from Other Buffers
29334
29335@noindent
29336@kindex C-x * g
29337@pindex calc-grab-region
29338The @kbd{C-x * g} (@code{calc-grab-region}) command takes the text between
29339point and mark in the current buffer and attempts to parse it as a
29340vector of values. Basically, it wraps the text in vector brackets
29341@samp{[ ]} unless the text already is enclosed in vector brackets,
29342then reads the text as if it were an algebraic entry. The contents
29343of the vector may be numbers, formulas, or any other Calc objects.
29344If the @kbd{C-x * g} command works successfully, it does an automatic
29345@kbd{C-x * c} to enter the Calculator buffer.
29346
29347A numeric prefix argument grabs the specified number of lines around
29348point, ignoring the mark. A positive prefix grabs from point to the
29349@expr{n}th following newline (so that @kbd{M-1 C-x * g} grabs from point
29350to the end of the current line); a negative prefix grabs from point
29351back to the @expr{n+1}st preceding newline. In these cases the text
29352that is grabbed is exactly the same as the text that @kbd{C-k} would
29353delete given that prefix argument.
29354
29355A prefix of zero grabs the current line; point may be anywhere on the
29356line.
29357
29358A plain @kbd{C-u} prefix interprets the region between point and mark
29359as a single number or formula rather than a vector. For example,
29360@kbd{C-x * g} on the text @samp{2 a b} produces the vector of three
29361values @samp{[2, a, b]}, but @kbd{C-u C-x * g} on the same region
29362reads a formula which is a product of three things: @samp{2 a b}.
29363(The text @samp{a + b}, on the other hand, will be grabbed as a
29364vector of one element by plain @kbd{C-x * g} because the interpretation
29365@samp{[a, +, b]} would be a syntax error.)
29366
29367If a different language has been specified (@pxref{Language Modes}),
29368the grabbed text will be interpreted according to that language.
29369
29370@kindex C-x * r
29371@pindex calc-grab-rectangle
29372The @kbd{C-x * r} (@code{calc-grab-rectangle}) command takes the text between
29373point and mark and attempts to parse it as a matrix. If point and mark
29374are both in the leftmost column, the lines in between are parsed in their
29375entirety. Otherwise, point and mark define the corners of a rectangle
29376whose contents are parsed.
29377
29378Each line of the grabbed area becomes a row of the matrix. The result
29379will actually be a vector of vectors, which Calc will treat as a matrix
29380only if every row contains the same number of values.
29381
29382If a line contains a portion surrounded by square brackets (or curly
29383braces), that portion is interpreted as a vector which becomes a row
29384of the matrix. Any text surrounding the bracketed portion on the line
29385is ignored.
29386
29387Otherwise, the entire line is interpreted as a row vector as if it
29388were surrounded by square brackets. Leading line numbers (in the
29389format used in the Calc stack buffer) are ignored. If you wish to
29390force this interpretation (even if the line contains bracketed
29391portions), give a negative numeric prefix argument to the
29392@kbd{C-x * r} command.
29393
29394If you give a numeric prefix argument of zero or plain @kbd{C-u}, each
29395line is instead interpreted as a single formula which is converted into
29396a one-element vector. Thus the result of @kbd{C-u C-x * r} will be a
29397one-column matrix. For example, suppose one line of the data is the
29398expression @samp{2 a}. A plain @w{@kbd{C-x * r}} will interpret this as
29399@samp{[2 a]}, which in turn is read as a two-element vector that forms
29400one row of the matrix. But a @kbd{C-u C-x * r} will interpret this row
29401as @samp{[2*a]}.
29402
29403If you give a positive numeric prefix argument @var{n}, then each line
29404will be split up into columns of width @var{n}; each column is parsed
29405separately as a matrix element. If a line contained
29406@w{@samp{2 +/- 3 4 +/- 5}}, then grabbing with a prefix argument of 8
29407would correctly split the line into two error forms.
29408
29409@xref{Matrix Functions}, to see how to pull the matrix apart into its
29410constituent rows and columns. (If it is a
29411@texline @math{1\times1}
29412@infoline 1x1
29413matrix, just hit @kbd{v u} (@code{calc-unpack}) twice.)
29414
29415@kindex C-x * :
29416@kindex C-x * _
29417@pindex calc-grab-sum-across
29418@pindex calc-grab-sum-down
29419@cindex Summing rows and columns of data
29420The @kbd{C-x * :} (@code{calc-grab-sum-down}) command is a handy way to
29421grab a rectangle of data and sum its columns. It is equivalent to
29422typing @kbd{C-x * r}, followed by @kbd{V R : +} (the vector reduction
29423command that sums the columns of a matrix; @pxref{Reducing}). The
29424result of the command will be a vector of numbers, one for each column
29425in the input data. The @kbd{C-x * _} (@code{calc-grab-sum-across}) command
29426similarly grabs a rectangle and sums its rows by executing @w{@kbd{V R _ +}}.
29427
29428As well as being more convenient, @kbd{C-x * :} and @kbd{C-x * _} are also
29429much faster because they don't actually place the grabbed vector on
29430the stack. In a @kbd{C-x * r V R : +} sequence, formatting the vector
29431for display on the stack takes a large fraction of the total time
29432(unless you have planned ahead and used @kbd{v .} and @kbd{t .} modes).
29433
29434For example, suppose we have a column of numbers in a file which we
29435wish to sum. Go to one corner of the column and press @kbd{C-@@} to
29436set the mark; go to the other corner and type @kbd{C-x * :}. Since there
29437is only one column, the result will be a vector of one number, the sum.
29438(You can type @kbd{v u} to unpack this vector into a plain number if
29439you want to do further arithmetic with it.)
29440
29441To compute the product of the column of numbers, we would have to do
29442it ``by hand'' since there's no special grab-and-multiply command.
29443Use @kbd{C-x * r} to grab the column of numbers into the calculator in
29444the form of a column matrix. The statistics command @kbd{u *} is a
29445handy way to find the product of a vector or matrix of numbers.
29446@xref{Statistical Operations}. Another approach would be to use
29447an explicit column reduction command, @kbd{V R : *}.
29448
29449@node Yanking Into Buffers, X Cut and Paste, Grabbing From Buffers, Kill and Yank
29450@section Yanking into Other Buffers
29451
29452@noindent
29453@kindex y
29454@pindex calc-copy-to-buffer
29455The plain @kbd{y} (@code{calc-copy-to-buffer}) command inserts the number
29456at the top of the stack into the most recently used normal editing buffer.
29457(More specifically, this is the most recently used buffer which is displayed
29458in a window and whose name does not begin with @samp{*}. If there is no
29459such buffer, this is the most recently used buffer except for Calculator
29460and Calc Trail buffers.) The number is inserted exactly as it appears and
29461without a newline. (If line-numbering is enabled, the line number is
29462normally not included.) The number is @emph{not} removed from the stack.
29463
29464With a prefix argument, @kbd{y} inserts several numbers, one per line.
29465A positive argument inserts the specified number of values from the top
29466of the stack. A negative argument inserts the @expr{n}th value from the
29467top of the stack. An argument of zero inserts the entire stack. Note
29468that @kbd{y} with an argument of 1 is slightly different from @kbd{y}
29469with no argument; the former always copies full lines, whereas the
29470latter strips off the trailing newline.
29471
29472With a lone @kbd{C-u} as a prefix argument, @kbd{y} @emph{replaces} the
29473region in the other buffer with the yanked text, then quits the
29474Calculator, leaving you in that buffer. A typical use would be to use
29475@kbd{C-x * g} to read a region of data into the Calculator, operate on the
29476data to produce a new matrix, then type @kbd{C-u y} to replace the
29477original data with the new data. One might wish to alter the matrix
29478display style (@pxref{Vector and Matrix Formats}) or change the current
29479display language (@pxref{Language Modes}) before doing this. Also, note
29480that this command replaces a linear region of text (as grabbed by
29481@kbd{C-x * g}), not a rectangle (as grabbed by @kbd{C-x * r}).
29482
29483If the editing buffer is in overwrite (as opposed to insert) mode,
29484and the @kbd{C-u} prefix was not used, then the yanked number will
29485overwrite the characters following point rather than being inserted
29486before those characters. The usual conventions of overwrite mode
29487are observed; for example, characters will be inserted at the end of
29488a line rather than overflowing onto the next line. Yanking a multi-line
29489object such as a matrix in overwrite mode overwrites the next @var{n}
29490lines in the buffer, lengthening or shortening each line as necessary.
29491Finally, if the thing being yanked is a simple integer or floating-point
29492number (like @samp{-1.2345e-3}) and the characters following point also
29493make up such a number, then Calc will replace that number with the new
29494number, lengthening or shortening as necessary. The concept of
29495``overwrite mode'' has thus been generalized from overwriting characters
29496to overwriting one complete number with another.
29497
29498@kindex C-x * y
29499The @kbd{C-x * y} key sequence is equivalent to @kbd{y} except that
29500it can be typed anywhere, not just in Calc. This provides an easy
29501way to guarantee that Calc knows which editing buffer you want to use!
29502
29503@node X Cut and Paste, , Yanking Into Buffers, Kill and Yank
29504@section X Cut and Paste
29505
29506@noindent
29507If you are using Emacs with the X window system, there is an easier
29508way to move small amounts of data into and out of the calculator:
29509Use the mouse-oriented cut and paste facilities of X.
29510
29511The default bindings for a three-button mouse cause the left button
29512to move the Emacs cursor to the given place, the right button to
29513select the text between the cursor and the clicked location, and
29514the middle button to yank the selection into the buffer at the
29515clicked location. So, if you have a Calc window and an editing
29516window on your Emacs screen, you can use left-click/right-click
29517to select a number, vector, or formula from one window, then
29518middle-click to paste that value into the other window. When you
29519paste text into the Calc window, Calc interprets it as an algebraic
29520entry. It doesn't matter where you click in the Calc window; the
29521new value is always pushed onto the top of the stack.
29522
29523The @code{xterm} program that is typically used for general-purpose
29524shell windows in X interprets the mouse buttons in the same way.
29525So you can use the mouse to move data between Calc and any other
29526Unix program. One nice feature of @code{xterm} is that a double
29527left-click selects one word, and a triple left-click selects a
29528whole line. So you can usually transfer a single number into Calc
29529just by double-clicking on it in the shell, then middle-clicking
29530in the Calc window.
29531
29532@node Keypad Mode, Embedded Mode, Kill and Yank, Top
29533@chapter Keypad Mode
29534
29535@noindent
29536@kindex C-x * k
29537@pindex calc-keypad
29538The @kbd{C-x * k} (@code{calc-keypad}) command starts the Calculator
29539and displays a picture of a calculator-style keypad. If you are using
29540the X window system, you can click on any of the ``keys'' in the
29541keypad using the left mouse button to operate the calculator.
29542The original window remains the selected window; in Keypad mode
29543you can type in your file while simultaneously performing
29544calculations with the mouse.
29545
29546@pindex full-calc-keypad
29547If you have used @kbd{C-x * b} first, @kbd{C-x * k} instead invokes
29548the @code{full-calc-keypad} command, which takes over the whole
29549Emacs screen and displays the keypad, the Calc stack, and the Calc
29550trail all at once. This mode would normally be used when running
29551Calc standalone (@pxref{Standalone Operation}).
29552
29553If you aren't using the X window system, you must switch into
29554the @samp{*Calc Keypad*} window, place the cursor on the desired
29555``key,'' and type @key{SPC} or @key{RET}. If you think this
29556is easier than using Calc normally, go right ahead.
29557
29558Calc commands are more or less the same in Keypad mode. Certain
29559keypad keys differ slightly from the corresponding normal Calc
29560keystrokes; all such deviations are described below.
29561
29562Keypad mode includes many more commands than will fit on the keypad
29563at once. Click the right mouse button [@code{calc-keypad-menu}]
29564to switch to the next menu. The bottom five rows of the keypad
29565stay the same; the top three rows change to a new set of commands.
29566To return to earlier menus, click the middle mouse button
29567[@code{calc-keypad-menu-back}] or simply advance through the menus
29568until you wrap around. Typing @key{TAB} inside the keypad window
29569is equivalent to clicking the right mouse button there.
29570
29571You can always click the @key{EXEC} button and type any normal
29572Calc key sequence. This is equivalent to switching into the
29573Calc buffer, typing the keys, then switching back to your
29574original buffer.
29575
29576@menu
29577* Keypad Main Menu::
29578* Keypad Functions Menu::
29579* Keypad Binary Menu::
29580* Keypad Vectors Menu::
29581* Keypad Modes Menu::
29582@end menu
29583
29584@node Keypad Main Menu, Keypad Functions Menu, Keypad Mode, Keypad Mode
29585@section Main Menu
29586
29587@smallexample
29588@group
29589|----+-----Calc 2.1------+----1
29590|FLR |CEIL|RND |TRNC|CLN2|FLT |
29591|----+----+----+----+----+----|
29592| LN |EXP | |ABS |IDIV|MOD |
29593|----+----+----+----+----+----|
29594|SIN |COS |TAN |SQRT|y^x |1/x |
29595|----+----+----+----+----+----|
29596| ENTER |+/- |EEX |UNDO| <- |
29597|-----+---+-+--+--+-+---++----|
29598| INV | 7 | 8 | 9 | / |
29599|-----+-----+-----+-----+-----|
29600| HYP | 4 | 5 | 6 | * |
29601|-----+-----+-----+-----+-----|
29602|EXEC | 1 | 2 | 3 | - |
29603|-----+-----+-----+-----+-----|
29604| OFF | 0 | . | PI | + |
29605|-----+-----+-----+-----+-----+
29606@end group
29607@end smallexample
29608
29609@noindent
29610This is the menu that appears the first time you start Keypad mode.
29611It will show up in a vertical window on the right side of your screen.
29612Above this menu is the traditional Calc stack display. On a 24-line
29613screen you will be able to see the top three stack entries.
29614
29615The ten digit keys, decimal point, and @key{EEX} key are used for
29616entering numbers in the obvious way. @key{EEX} begins entry of an
29617exponent in scientific notation. Just as with regular Calc, the
29618number is pushed onto the stack as soon as you press @key{ENTER}
29619or any other function key.
29620
29621The @key{+/-} key corresponds to normal Calc's @kbd{n} key. During
29622numeric entry it changes the sign of the number or of the exponent.
29623At other times it changes the sign of the number on the top of the
29624stack.
29625
29626The @key{INV} and @key{HYP} keys modify other keys. As well as
29627having the effects described elsewhere in this manual, Keypad mode
29628defines several other ``inverse'' operations. These are described
29629below and in the following sections.
29630
29631The @key{ENTER} key finishes the current numeric entry, or otherwise
29632duplicates the top entry on the stack.
29633
29634The @key{UNDO} key undoes the most recent Calc operation.
29635@kbd{INV UNDO} is the ``redo'' command, and @kbd{HYP UNDO} is
29636``last arguments'' (@kbd{M-@key{RET}}).
29637
29638The @key{<-} key acts as a ``backspace'' during numeric entry.
29639At other times it removes the top stack entry. @kbd{INV <-}
29640clears the entire stack. @kbd{HYP <-} takes an integer from
29641the stack, then removes that many additional stack elements.
29642
29643The @key{EXEC} key prompts you to enter any keystroke sequence
29644that would normally work in Calc mode. This can include a
29645numeric prefix if you wish. It is also possible simply to
29646switch into the Calc window and type commands in it; there is
29647nothing ``magic'' about this window when Keypad mode is active.
29648
29649The other keys in this display perform their obvious calculator
29650functions. @key{CLN2} rounds the top-of-stack by temporarily
29651reducing the precision by 2 digits. @key{FLT} converts an
29652integer or fraction on the top of the stack to floating-point.
29653
29654The @key{INV} and @key{HYP} keys combined with several of these keys
29655give you access to some common functions even if the appropriate menu
29656is not displayed. Obviously you don't need to learn these keys
29657unless you find yourself wasting time switching among the menus.
29658
29659@table @kbd
29660@item INV +/-
29661is the same as @key{1/x}.
29662@item INV +
29663is the same as @key{SQRT}.
29664@item INV -
29665is the same as @key{CONJ}.
29666@item INV *
29667is the same as @key{y^x}.
29668@item INV /
29669is the same as @key{INV y^x} (the @expr{x}th root of @expr{y}).
29670@item HYP/INV 1
29671are the same as @key{SIN} / @kbd{INV SIN}.
29672@item HYP/INV 2
29673are the same as @key{COS} / @kbd{INV COS}.
29674@item HYP/INV 3
29675are the same as @key{TAN} / @kbd{INV TAN}.
29676@item INV/HYP 4
29677are the same as @key{LN} / @kbd{HYP LN}.
29678@item INV/HYP 5
29679are the same as @key{EXP} / @kbd{HYP EXP}.
29680@item INV 6
29681is the same as @key{ABS}.
29682@item INV 7
29683is the same as @key{RND} (@code{calc-round}).
29684@item INV 8
29685is the same as @key{CLN2}.
29686@item INV 9
29687is the same as @key{FLT} (@code{calc-float}).
29688@item INV 0
29689is the same as @key{IMAG}.
29690@item INV .
29691is the same as @key{PREC}.
29692@item INV ENTER
29693is the same as @key{SWAP}.
29694@item HYP ENTER
29695is the same as @key{RLL3}.
29696@item INV HYP ENTER
29697is the same as @key{OVER}.
29698@item HYP +/-
29699packs the top two stack entries as an error form.
29700@item HYP EEX
29701packs the top two stack entries as a modulo form.
29702@item INV EEX
29703creates an interval form; this removes an integer which is one
29704of 0 @samp{[]}, 1 @samp{[)}, 2 @samp{(]} or 3 @samp{()}, followed
29705by the two limits of the interval.
29706@end table
29707
29708The @kbd{OFF} key turns Calc off; typing @kbd{C-x * k} or @kbd{C-x * *}
29709again has the same effect. This is analogous to typing @kbd{q} or
29710hitting @kbd{C-x * c} again in the normal calculator. If Calc is
29711running standalone (the @code{full-calc-keypad} command appeared in the
29712command line that started Emacs), then @kbd{OFF} is replaced with
29713@kbd{EXIT}; clicking on this actually exits Emacs itself.
29714
29715@node Keypad Functions Menu, Keypad Binary Menu, Keypad Main Menu, Keypad Mode
29716@section Functions Menu
29717
29718@smallexample
29719@group
29720|----+----+----+----+----+----2
29721|IGAM|BETA|IBET|ERF |BESJ|BESY|
29722|----+----+----+----+----+----|
29723|IMAG|CONJ| RE |ATN2|RAND|RAGN|
29724|----+----+----+----+----+----|
29725|GCD |FACT|DFCT|BNOM|PERM|NXTP|
29726|----+----+----+----+----+----|
29727@end group
29728@end smallexample
29729
29730@noindent
29731This menu provides various operations from the @kbd{f} and @kbd{k}
29732prefix keys.
29733
29734@key{IMAG} multiplies the number on the stack by the imaginary
29735number @expr{i = (0, 1)}.
29736
29737@key{RE} extracts the real part a complex number. @kbd{INV RE}
29738extracts the imaginary part.
29739
29740@key{RAND} takes a number from the top of the stack and computes
29741a random number greater than or equal to zero but less than that
29742number. (@xref{Random Numbers}.) @key{RAGN} is the ``random
29743again'' command; it computes another random number using the
29744same limit as last time.
29745
29746@key{INV GCD} computes the LCM (least common multiple) function.
29747
29748@key{INV FACT} is the gamma function.
29749@texline @math{\Gamma(x) = (x-1)!}.
29750@infoline @expr{gamma(x) = (x-1)!}.
29751
29752@key{PERM} is the number-of-permutations function, which is on the
29753@kbd{H k c} key in normal Calc.
29754
29755@key{NXTP} finds the next prime after a number. @kbd{INV NXTP}
29756finds the previous prime.
29757
29758@node Keypad Binary Menu, Keypad Vectors Menu, Keypad Functions Menu, Keypad Mode
29759@section Binary Menu
29760
29761@smallexample
29762@group
29763|----+----+----+----+----+----3
29764|AND | OR |XOR |NOT |LSH |RSH |
29765|----+----+----+----+----+----|
29766|DEC |HEX |OCT |BIN |WSIZ|ARSH|
29767|----+----+----+----+----+----|
29768| A | B | C | D | E | F |
29769|----+----+----+----+----+----|
29770@end group
29771@end smallexample
29772
29773@noindent
29774The keys in this menu perform operations on binary integers.
29775Note that both logical and arithmetic right-shifts are provided.
29776@key{INV LSH} rotates one bit to the left.
29777
29778The ``difference'' function (normally on @kbd{b d}) is on @key{INV AND}.
29779The ``clip'' function (normally on @w{@kbd{b c}}) is on @key{INV NOT}.
29780
29781The @key{DEC}, @key{HEX}, @key{OCT}, and @key{BIN} keys select the
29782current radix for display and entry of numbers: Decimal, hexadecimal,
29783octal, or binary. The six letter keys @key{A} through @key{F} are used
29784for entering hexadecimal numbers.
29785
29786The @key{WSIZ} key displays the current word size for binary operations
29787and allows you to enter a new word size. You can respond to the prompt
29788using either the keyboard or the digits and @key{ENTER} from the keypad.
29789The initial word size is 32 bits.
29790
29791@node Keypad Vectors Menu, Keypad Modes Menu, Keypad Binary Menu, Keypad Mode
29792@section Vectors Menu
29793
29794@smallexample
29795@group
29796|----+----+----+----+----+----4
29797|SUM |PROD|MAX |MAP*|MAP^|MAP$|
29798|----+----+----+----+----+----|
29799|MINV|MDET|MTRN|IDNT|CRSS|"x" |
29800|----+----+----+----+----+----|
29801|PACK|UNPK|INDX|BLD |LEN |... |
29802|----+----+----+----+----+----|
29803@end group
29804@end smallexample
29805
29806@noindent
29807The keys in this menu operate on vectors and matrices.
29808
29809@key{PACK} removes an integer @var{n} from the top of the stack;
29810the next @var{n} stack elements are removed and packed into a vector,
29811which is replaced onto the stack. Thus the sequence
29812@kbd{1 ENTER 3 ENTER 5 ENTER 3 PACK} enters the vector
29813@samp{[1, 3, 5]} onto the stack. To enter a matrix, build each row
29814on the stack as a vector, then use a final @key{PACK} to collect the
29815rows into a matrix.
29816
29817@key{UNPK} unpacks the vector on the stack, pushing each of its
29818components separately.
29819
29820@key{INDX} removes an integer @var{n}, then builds a vector of
29821integers from 1 to @var{n}. @kbd{INV INDX} takes three numbers
29822from the stack: The vector size @var{n}, the starting number,
29823and the increment. @kbd{BLD} takes an integer @var{n} and any
29824value @var{x} and builds a vector of @var{n} copies of @var{x}.
29825
29826@key{IDNT} removes an integer @var{n}, then builds an @var{n}-by-@var{n}
29827identity matrix.
29828
29829@key{LEN} replaces a vector by its length, an integer.
29830
29831@key{...} turns on or off ``abbreviated'' display mode for large vectors.
29832
29833@key{MINV}, @key{MDET}, @key{MTRN}, and @key{CROSS} are the matrix
29834inverse, determinant, and transpose, and vector cross product.
29835
29836@key{SUM} replaces a vector by the sum of its elements. It is
29837equivalent to @kbd{u +} in normal Calc (@pxref{Statistical Operations}).
29838@key{PROD} computes the product of the elements of a vector, and
29839@key{MAX} computes the maximum of all the elements of a vector.
29840
29841@key{INV SUM} computes the alternating sum of the first element
29842minus the second, plus the third, minus the fourth, and so on.
29843@key{INV MAX} computes the minimum of the vector elements.
29844
29845@key{HYP SUM} computes the mean of the vector elements.
29846@key{HYP PROD} computes the sample standard deviation.
29847@key{HYP MAX} computes the median.
29848
29849@key{MAP*} multiplies two vectors elementwise. It is equivalent
29850to the @kbd{V M *} command. @key{MAP^} computes powers elementwise.
29851The arguments must be vectors of equal length, or one must be a vector
29852and the other must be a plain number. For example, @kbd{2 MAP^} squares
29853all the elements of a vector.
29854
29855@key{MAP$} maps the formula on the top of the stack across the
29856vector in the second-to-top position. If the formula contains
29857several variables, Calc takes that many vectors starting at the
29858second-to-top position and matches them to the variables in
29859alphabetical order. The result is a vector of the same size as
29860the input vectors, whose elements are the formula evaluated with
29861the variables set to the various sets of numbers in those vectors.
29862For example, you could simulate @key{MAP^} using @key{MAP$} with
29863the formula @samp{x^y}.
29864
29865The @kbd{"x"} key pushes the variable name @expr{x} onto the
29866stack. To build the formula @expr{x^2 + 6}, you would use the
29867key sequence @kbd{"x" 2 y^x 6 +}. This formula would then be
29868suitable for use with the @key{MAP$} key described above.
29869With @key{INV}, @key{HYP}, or @key{INV} and @key{HYP}, the
29870@kbd{"x"} key pushes the variable names @expr{y}, @expr{z}, and
29871@expr{t}, respectively.
29872
29873@node Keypad Modes Menu, , Keypad Vectors Menu, Keypad Mode
29874@section Modes Menu
29875
29876@smallexample
29877@group
29878|----+----+----+----+----+----5
29879|FLT |FIX |SCI |ENG |GRP | |
29880|----+----+----+----+----+----|
29881|RAD |DEG |FRAC|POLR|SYMB|PREC|
29882|----+----+----+----+----+----|
29883|SWAP|RLL3|RLL4|OVER|STO |RCL |
29884|----+----+----+----+----+----|
29885@end group
29886@end smallexample
29887
29888@noindent
29889The keys in this menu manipulate modes, variables, and the stack.
29890
29891The @key{FLT}, @key{FIX}, @key{SCI}, and @key{ENG} keys select
29892floating-point, fixed-point, scientific, or engineering notation.
29893@key{FIX} displays two digits after the decimal by default; the
29894others display full precision. With the @key{INV} prefix, these
29895keys pop a number-of-digits argument from the stack.
29896
29897The @key{GRP} key turns grouping of digits with commas on or off.
29898@kbd{INV GRP} enables grouping to the right of the decimal point as
29899well as to the left.
29900
29901The @key{RAD} and @key{DEG} keys switch between radians and degrees
29902for trigonometric functions.
29903
29904The @key{FRAC} key turns Fraction mode on or off. This affects
29905whether commands like @kbd{/} with integer arguments produce
29906fractional or floating-point results.
29907
29908The @key{POLR} key turns Polar mode on or off, determining whether
29909polar or rectangular complex numbers are used by default.
29910
29911The @key{SYMB} key turns Symbolic mode on or off, in which
29912operations that would produce inexact floating-point results
29913are left unevaluated as algebraic formulas.
29914
29915The @key{PREC} key selects the current precision. Answer with
29916the keyboard or with the keypad digit and @key{ENTER} keys.
29917
29918The @key{SWAP} key exchanges the top two stack elements.
29919The @key{RLL3} key rotates the top three stack elements upwards.
29920The @key{RLL4} key rotates the top four stack elements upwards.
29921The @key{OVER} key duplicates the second-to-top stack element.
29922
29923The @key{STO} and @key{RCL} keys are analogous to @kbd{s t} and
29924@kbd{s r} in regular Calc. @xref{Store and Recall}. Click the
29925@key{STO} or @key{RCL} key, then one of the ten digits. (Named
29926variables are not available in Keypad mode.) You can also use,
29927for example, @kbd{STO + 3} to add to register 3.
29928
29929@node Embedded Mode, Programming, Keypad Mode, Top
29930@chapter Embedded Mode
29931
29932@noindent
29933Embedded mode in Calc provides an alternative to copying numbers
29934and formulas back and forth between editing buffers and the Calc
29935stack. In Embedded mode, your editing buffer becomes temporarily
29936linked to the stack and this copying is taken care of automatically.
29937
29938@menu
29939* Basic Embedded Mode::
29940* More About Embedded Mode::
29941* Assignments in Embedded Mode::
29942* Mode Settings in Embedded Mode::
29943* Customizing Embedded Mode::
29944@end menu
29945
29946@node Basic Embedded Mode, More About Embedded Mode, Embedded Mode, Embedded Mode
29947@section Basic Embedded Mode
29948
29949@noindent
29950@kindex C-x * e
29951@pindex calc-embedded
29952To enter Embedded mode, position the Emacs point (cursor) on a
29953formula in any buffer and press @kbd{C-x * e} (@code{calc-embedded}).
29954Note that @kbd{C-x * e} is not to be used in the Calc stack buffer
29955like most Calc commands, but rather in regular editing buffers that
29956are visiting your own files.
29957
29958Calc will try to guess an appropriate language based on the major mode
29959of the editing buffer. (@xref{Language Modes}.) If the current buffer is
29960in @code{latex-mode}, for example, Calc will set its language to La@TeX{}.
29961Similarly, Calc will use @TeX{} language for @code{tex-mode},
29962@code{plain-tex-mode} and @code{context-mode}, C language for
29963@code{c-mode} and @code{c++-mode}, FORTRAN language for
29964@code{fortran-mode} and @code{f90-mode}, Pascal for @code{pascal-mode},
29965and eqn for @code{nroff-mode} (@pxref{Customizing Calc}).
29966These can be overridden with Calc's mode
29967changing commands (@pxref{Mode Settings in Embedded Mode}). If no
29968suitable language is available, Calc will continue with its current language.
29969
29970Calc normally scans backward and forward in the buffer for the
29971nearest opening and closing @dfn{formula delimiters}. The simplest
29972delimiters are blank lines. Other delimiters that Embedded mode
29973understands are:
29974
29975@enumerate
29976@item
29977The @TeX{} and La@TeX{} math delimiters @samp{$ $}, @samp{$$ $$},
29978@samp{\[ \]}, and @samp{\( \)};
29979@item
29980Lines beginning with @samp{\begin} and @samp{\end} (except matrix delimiters);
29981@item
29982Lines beginning with @samp{@@} (Texinfo delimiters).
29983@item
29984Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
29985@item
29986Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
29987@end enumerate
29988
29989@xref{Customizing Embedded Mode}, to see how to make Calc recognize
29990your own favorite delimiters. Delimiters like @samp{$ $} can appear
29991on their own separate lines or in-line with the formula.
29992
29993If you give a positive or negative numeric prefix argument, Calc
29994instead uses the current point as one end of the formula, and includes
29995that many lines forward or backward (respectively, including the current
29996line). Explicit delimiters are not necessary in this case.
29997
29998With a prefix argument of zero, Calc uses the current region (delimited
29999by point and mark) instead of formula delimiters. With a prefix
30000argument of @kbd{C-u} only, Calc uses the current line as the formula.
30001
30002@kindex C-x * w
30003@pindex calc-embedded-word
30004The @kbd{C-x * w} (@code{calc-embedded-word}) command will start Embedded
30005mode on the current ``word''; in this case Calc will scan for the first
30006non-numeric character (i.e., the first character that is not a digit,
30007sign, decimal point, or upper- or lower-case @samp{e}) forward and
30008backward to delimit the formula.
30009
30010When you enable Embedded mode for a formula, Calc reads the text
30011between the delimiters and tries to interpret it as a Calc formula.
30012Calc can generally identify @TeX{} formulas and
30013Big-style formulas even if the language mode is wrong. If Calc
30014can't make sense of the formula, it beeps and refuses to enter
30015Embedded mode. But if the current language is wrong, Calc can
30016sometimes parse the formula successfully (but incorrectly);
30017for example, the C expression @samp{atan(a[1])} can be parsed
30018in Normal language mode, but the @code{atan} won't correspond to
30019the built-in @code{arctan} function, and the @samp{a[1]} will be
30020interpreted as @samp{a} times the vector @samp{[1]}!
30021
30022If you press @kbd{C-x * e} or @kbd{C-x * w} to activate an embedded
30023formula which is blank, say with the cursor on the space between
30024the two delimiters @samp{$ $}, Calc will immediately prompt for
30025an algebraic entry.
30026
30027Only one formula in one buffer can be enabled at a time. If you
30028move to another area of the current buffer and give Calc commands,
30029Calc turns Embedded mode off for the old formula and then tries
30030to restart Embedded mode at the new position. Other buffers are
30031not affected by Embedded mode.
30032
30033When Embedded mode begins, Calc pushes the current formula onto
30034the stack. No Calc stack window is created; however, Calc copies
30035the top-of-stack position into the original buffer at all times.
30036You can create a Calc window by hand with @kbd{C-x * o} if you
30037find you need to see the entire stack.
30038
30039For example, typing @kbd{C-x * e} while somewhere in the formula
30040@samp{n>2} in the following line enables Embedded mode on that
30041inequality:
30042
30043@example
30044We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.
30045@end example
30046
30047@noindent
30048The formula @expr{n>2} will be pushed onto the Calc stack, and
30049the top of stack will be copied back into the editing buffer.
30050This means that spaces will appear around the @samp{>} symbol
30051to match Calc's usual display style:
30052
30053@example
30054We define $F_n = F_(n-1)+F_(n-2)$ for all $n > 2$.
30055@end example
30056
30057@noindent
30058No spaces have appeared around the @samp{+} sign because it's
30059in a different formula, one which we have not yet touched with
30060Embedded mode.
30061
30062Now that Embedded mode is enabled, keys you type in this buffer
30063are interpreted as Calc commands. At this point we might use
30064the ``commute'' command @kbd{j C} to reverse the inequality.
30065This is a selection-based command for which we first need to
30066move the cursor onto the operator (@samp{>} in this case) that
30067needs to be commuted.
30068
30069@example
30070We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.
30071@end example
30072
30073The @kbd{C-x * o} command is a useful way to open a Calc window
30074without actually selecting that window. Giving this command
30075verifies that @samp{2 < n} is also on the Calc stack. Typing
30076@kbd{17 @key{RET}} would produce:
30077
30078@example
30079We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.
30080@end example
30081
30082@noindent
30083with @samp{2 < n} and @samp{17} on the stack; typing @key{TAB}
30084at this point will exchange the two stack values and restore
30085@samp{2 < n} to the embedded formula. Even though you can't
30086normally see the stack in Embedded mode, it is still there and
30087it still operates in the same way. But, as with old-fashioned
30088RPN calculators, you can only see the value at the top of the
30089stack at any given time (unless you use @kbd{C-x * o}).
30090
30091Typing @kbd{C-x * e} again turns Embedded mode off. The Calc
30092window reveals that the formula @w{@samp{2 < n}} is automatically
30093removed from the stack, but the @samp{17} is not. Entering
30094Embedded mode always pushes one thing onto the stack, and
30095leaving Embedded mode always removes one thing. Anything else
30096that happens on the stack is entirely your business as far as
30097Embedded mode is concerned.
30098
30099If you press @kbd{C-x * e} in the wrong place by accident, it is
30100possible that Calc will be able to parse the nearby text as a
30101formula and will mangle that text in an attempt to redisplay it
30102``properly'' in the current language mode. If this happens,
30103press @kbd{C-x * e} again to exit Embedded mode, then give the
30104regular Emacs ``undo'' command (@kbd{C-_} or @kbd{C-x u}) to put
30105the text back the way it was before Calc edited it. Note that Calc's
30106own Undo command (typed before you turn Embedded mode back off)
30107will not do you any good, because as far as Calc is concerned
30108you haven't done anything with this formula yet.
30109
30110@node More About Embedded Mode, Assignments in Embedded Mode, Basic Embedded Mode, Embedded Mode
30111@section More About Embedded Mode
30112
30113@noindent
30114When Embedded mode ``activates'' a formula, i.e., when it examines
30115the formula for the first time since the buffer was created or
30116loaded, Calc tries to sense the language in which the formula was
30117written. If the formula contains any La@TeX{}-like @samp{\} sequences,
30118it is parsed (i.e., read) in La@TeX{} mode. If the formula appears to
30119be written in multi-line Big mode, it is parsed in Big mode. Otherwise,
30120it is parsed according to the current language mode.
30121
30122Note that Calc does not change the current language mode according
30123the formula it reads in. Even though it can read a La@TeX{} formula when
30124not in La@TeX{} mode, it will immediately rewrite this formula using
30125whatever language mode is in effect.
30126
30127@tex
30128\bigskip
30129@end tex
30130
30131@kindex d p
30132@pindex calc-show-plain
30133Calc's parser is unable to read certain kinds of formulas. For
30134example, with @kbd{v ]} (@code{calc-matrix-brackets}) you can
30135specify matrix display styles which the parser is unable to
30136recognize as matrices. The @kbd{d p} (@code{calc-show-plain})
30137command turns on a mode in which a ``plain'' version of a
30138formula is placed in front of the fully-formatted version.
30139When Calc reads a formula that has such a plain version in
30140front, it reads the plain version and ignores the formatted
30141version.
30142
30143Plain formulas are preceded and followed by @samp{%%%} signs
30144by default. This notation has the advantage that the @samp{%}
30145character begins a comment in @TeX{} and La@TeX{}, so if your formula is
30146embedded in a @TeX{} or La@TeX{} document its plain version will be
30147invisible in the final printed copy. Certain major modes have different
30148delimiters to ensure that the ``plain'' version will be
30149in a comment for those modes, also.
30150See @ref{Customizing Embedded Mode} to see how to change the ``plain''
30151formula delimiters.
30152
30153There are several notations which Calc's parser for ``big''
30154formatted formulas can't yet recognize. In particular, it can't
30155read the large symbols for @code{sum}, @code{prod}, and @code{integ},
30156and it can't handle @samp{=>} with the righthand argument omitted.
30157Also, Calc won't recognize special formats you have defined with
30158the @kbd{Z C} command (@pxref{User-Defined Compositions}). In
30159these cases it is important to use ``plain'' mode to make sure
30160Calc will be able to read your formula later.
30161
30162Another example where ``plain'' mode is important is if you have
30163specified a float mode with few digits of precision. Normally
30164any digits that are computed but not displayed will simply be
30165lost when you save and re-load your embedded buffer, but ``plain''
30166mode allows you to make sure that the complete number is present
30167in the file as well as the rounded-down number.
30168
30169@tex
30170\bigskip
30171@end tex
30172
30173Embedded buffers remember active formulas for as long as they
30174exist in Emacs memory. Suppose you have an embedded formula
30175which is @cpi{} to the normal 12 decimal places, and then
30176type @w{@kbd{C-u 5 d n}} to display only five decimal places.
30177If you then type @kbd{d n}, all 12 places reappear because the
30178full number is still there on the Calc stack. More surprisingly,
30179even if you exit Embedded mode and later re-enter it for that
30180formula, typing @kbd{d n} will restore all 12 places because
30181each buffer remembers all its active formulas. However, if you
30182save the buffer in a file and reload it in a new Emacs session,
30183all non-displayed digits will have been lost unless you used
30184``plain'' mode.
30185
30186@tex
30187\bigskip
30188@end tex
30189
30190In some applications of Embedded mode, you will want to have a
30191sequence of copies of a formula that show its evolution as you
30192work on it. For example, you might want to have a sequence
30193like this in your file (elaborating here on the example from
30194the ``Getting Started'' chapter):
30195
30196@smallexample
30197The derivative of
30198
30199 ln(ln(x))
30200
30201is
30202
30203 @r{(the derivative of }ln(ln(x))@r{)}
30204
30205whose value at x = 2 is
30206
30207 @r{(the value)}
30208
30209and at x = 3 is
30210
30211 @r{(the value)}
30212@end smallexample
30213
30214@kindex C-x * d
30215@pindex calc-embedded-duplicate
30216The @kbd{C-x * d} (@code{calc-embedded-duplicate}) command is a
30217handy way to make sequences like this. If you type @kbd{C-x * d},
30218the formula under the cursor (which may or may not have Embedded
30219mode enabled for it at the time) is copied immediately below and
30220Embedded mode is then enabled for that copy.
30221
30222For this example, you would start with just
30223
30224@smallexample
30225The derivative of
30226
30227 ln(ln(x))
30228@end smallexample
30229
30230@noindent
30231and press @kbd{C-x * d} with the cursor on this formula. The result
30232is
30233
30234@smallexample
30235The derivative of
30236
30237 ln(ln(x))
30238
30239
30240 ln(ln(x))
30241@end smallexample
30242
30243@noindent
30244with the second copy of the formula enabled in Embedded mode.
30245You can now press @kbd{a d x @key{RET}} to take the derivative, and
30246@kbd{C-x * d C-x * d} to make two more copies of the derivative.
30247To complete the computations, type @kbd{3 s l x @key{RET}} to evaluate
30248the last formula, then move up to the second-to-last formula
30249and type @kbd{2 s l x @key{RET}}.
30250
30251Finally, you would want to press @kbd{C-x * e} to exit Embedded
30252mode, then go up and insert the necessary text in between the
30253various formulas and numbers.
30254
30255@tex
30256\bigskip
30257@end tex
30258
30259@kindex C-x * f
30260@kindex C-x * '
30261@pindex calc-embedded-new-formula
30262The @kbd{C-x * f} (@code{calc-embedded-new-formula}) command
30263creates a new embedded formula at the current point. It inserts
30264some default delimiters, which are usually just blank lines,
30265and then does an algebraic entry to get the formula (which is
30266then enabled for Embedded mode). This is just shorthand for
30267typing the delimiters yourself, positioning the cursor between
30268the new delimiters, and pressing @kbd{C-x * e}. The key sequence
30269@kbd{C-x * '} is equivalent to @kbd{C-x * f}.
30270
30271@kindex C-x * n
30272@kindex C-x * p
30273@pindex calc-embedded-next
30274@pindex calc-embedded-previous
30275The @kbd{C-x * n} (@code{calc-embedded-next}) and @kbd{C-x * p}
30276(@code{calc-embedded-previous}) commands move the cursor to the
30277next or previous active embedded formula in the buffer. They
30278can take positive or negative prefix arguments to move by several
30279formulas. Note that these commands do not actually examine the
30280text of the buffer looking for formulas; they only see formulas
30281which have previously been activated in Embedded mode. In fact,
30282@kbd{C-x * n} and @kbd{C-x * p} are a useful way to tell which
30283embedded formulas are currently active. Also, note that these
30284commands do not enable Embedded mode on the next or previous
30285formula, they just move the cursor.
30286
30287@kindex C-x * `
30288@pindex calc-embedded-edit
30289The @kbd{C-x * `} (@code{calc-embedded-edit}) command edits the
30290embedded formula at the current point as if by @kbd{`} (@code{calc-edit}).
30291Embedded mode does not have to be enabled for this to work. Press
30292@kbd{C-c C-c} to finish the edit, or @kbd{C-x k} to cancel.
30293
30294@node Assignments in Embedded Mode, Mode Settings in Embedded Mode, More About Embedded Mode, Embedded Mode
30295@section Assignments in Embedded Mode
30296
30297@noindent
30298The @samp{:=} (assignment) and @samp{=>} (``evaluates-to'') operators
30299are especially useful in Embedded mode. They allow you to make
30300a definition in one formula, then refer to that definition in
30301other formulas embedded in the same buffer.
30302
30303An embedded formula which is an assignment to a variable, as in
30304
30305@example
30306foo := 5
30307@end example
30308
30309@noindent
30310records @expr{5} as the stored value of @code{foo} for the
30311purposes of Embedded mode operations in the current buffer. It
30312does @emph{not} actually store @expr{5} as the ``global'' value
30313of @code{foo}, however. Regular Calc operations, and Embedded
30314formulas in other buffers, will not see this assignment.
30315
30316One way to use this assigned value is simply to create an
30317Embedded formula elsewhere that refers to @code{foo}, and to press
30318@kbd{=} in that formula. However, this permanently replaces the
30319@code{foo} in the formula with its current value. More interesting
30320is to use @samp{=>} elsewhere:
30321
30322@example
30323foo + 7 => 12
30324@end example
30325
30326@xref{Evaluates-To Operator}, for a general discussion of @samp{=>}.
30327
30328If you move back and change the assignment to @code{foo}, any
30329@samp{=>} formulas which refer to it are automatically updated.
30330
30331@example
30332foo := 17
30333
30334foo + 7 => 24
30335@end example
30336
30337The obvious question then is, @emph{how} can one easily change the
30338assignment to @code{foo}? If you simply select the formula in
30339Embedded mode and type 17, the assignment itself will be replaced
30340by the 17. The effect on the other formula will be that the
30341variable @code{foo} becomes unassigned:
30342
30343@example
3034417
30345
30346foo + 7 => foo + 7
30347@end example
30348
30349The right thing to do is first to use a selection command (@kbd{j 2}
30350will do the trick) to select the righthand side of the assignment.
30351Then, @kbd{17 @key{TAB} @key{DEL}} will swap the 17 into place (@pxref{Selecting
30352Subformulas}, to see how this works).
30353
30354@kindex C-x * j
30355@pindex calc-embedded-select
30356The @kbd{C-x * j} (@code{calc-embedded-select}) command provides an
30357easy way to operate on assignments. It is just like @kbd{C-x * e},
30358except that if the enabled formula is an assignment, it uses
30359@kbd{j 2} to select the righthand side. If the enabled formula
30360is an evaluates-to, it uses @kbd{j 1} to select the lefthand side.
30361A formula can also be a combination of both:
30362
30363@example
30364bar := foo + 3 => 20
30365@end example
30366
30367@noindent
30368in which case @kbd{C-x * j} will select the middle part (@samp{foo + 3}).
30369
30370The formula is automatically deselected when you leave Embedded
30371mode.
30372
30373@kindex C-x * u
30374@pindex calc-embedded-update-formula
30375Another way to change the assignment to @code{foo} would simply be
30376to edit the number using regular Emacs editing rather than Embedded
30377mode. Then, we have to find a way to get Embedded mode to notice
30378the change. The @kbd{C-x * u} (@code{calc-embedded-update-formula})
30379command is a convenient way to do this.
30380
30381@example
30382foo := 6
30383
30384foo + 7 => 13
30385@end example
30386
30387Pressing @kbd{C-x * u} is much like pressing @kbd{C-x * e = C-x * e}, that
30388is, temporarily enabling Embedded mode for the formula under the
30389cursor and then evaluating it with @kbd{=}. But @kbd{C-x * u} does
30390not actually use @kbd{C-x * e}, and in fact another formula somewhere
30391else can be enabled in Embedded mode while you use @kbd{C-x * u} and
30392that formula will not be disturbed.
30393
30394With a numeric prefix argument, @kbd{C-x * u} updates all active
30395@samp{=>} formulas in the buffer. Formulas which have not yet
30396been activated in Embedded mode, and formulas which do not have
30397@samp{=>} as their top-level operator, are not affected by this.
30398(This is useful only if you have used @kbd{m C}; see below.)
30399
30400With a plain @kbd{C-u} prefix, @kbd{C-u C-x * u} updates only in the
30401region between mark and point rather than in the whole buffer.
30402
30403@kbd{C-x * u} is also a handy way to activate a formula, such as an
30404@samp{=>} formula that has freshly been typed in or loaded from a
30405file.
30406
30407@kindex C-x * a
30408@pindex calc-embedded-activate
30409The @kbd{C-x * a} (@code{calc-embedded-activate}) command scans
30410through the current buffer and activates all embedded formulas
30411that contain @samp{:=} or @samp{=>} symbols. This does not mean
30412that Embedded mode is actually turned on, but only that the
30413formulas' positions are registered with Embedded mode so that
30414the @samp{=>} values can be properly updated as assignments are
30415changed.
30416
30417It is a good idea to type @kbd{C-x * a} right after loading a file
30418that uses embedded @samp{=>} operators. Emacs includes a nifty
30419``buffer-local variables'' feature that you can use to do this
30420automatically. The idea is to place near the end of your file
30421a few lines that look like this:
30422
30423@example
30424--- Local Variables: ---
30425--- eval:(calc-embedded-activate) ---
30426--- End: ---
30427@end example
30428
30429@noindent
30430where the leading and trailing @samp{---} can be replaced by
30431any suitable strings (which must be the same on all three lines)
30432or omitted altogether; in a @TeX{} or La@TeX{} file, @samp{%} would be a good
30433leading string and no trailing string would be necessary. In a
30434C program, @samp{/*} and @samp{*/} would be good leading and
30435trailing strings.
30436
30437When Emacs loads a file into memory, it checks for a Local Variables
30438section like this one at the end of the file. If it finds this
30439section, it does the specified things (in this case, running
30440@kbd{C-x * a} automatically) before editing of the file begins.
30441The Local Variables section must be within 3000 characters of the
30442end of the file for Emacs to find it, and it must be in the last
30443page of the file if the file has any page separators.
30444@xref{File Variables, , Local Variables in Files, emacs, the
30445Emacs manual}.
30446
30447Note that @kbd{C-x * a} does not update the formulas it finds.
30448To do this, type, say, @kbd{M-1 C-x * u} after @w{@kbd{C-x * a}}.
30449Generally this should not be a problem, though, because the
30450formulas will have been up-to-date already when the file was
30451saved.
30452
30453Normally, @kbd{C-x * a} activates all the formulas it finds, but
30454any previous active formulas remain active as well. With a
30455positive numeric prefix argument, @kbd{C-x * a} first deactivates
30456all current active formulas, then actives the ones it finds in
30457its scan of the buffer. With a negative prefix argument,
30458@kbd{C-x * a} simply deactivates all formulas.
30459
30460Embedded mode has two symbols, @samp{Active} and @samp{~Active},
30461which it puts next to the major mode name in a buffer's mode line.
30462It puts @samp{Active} if it has reason to believe that all
30463formulas in the buffer are active, because you have typed @kbd{C-x * a}
30464and Calc has not since had to deactivate any formulas (which can
30465happen if Calc goes to update an @samp{=>} formula somewhere because
30466a variable changed, and finds that the formula is no longer there
30467due to some kind of editing outside of Embedded mode). Calc puts
30468@samp{~Active} in the mode line if some, but probably not all,
30469formulas in the buffer are active. This happens if you activate
30470a few formulas one at a time but never use @kbd{C-x * a}, or if you
30471used @kbd{C-x * a} but then Calc had to deactivate a formula
30472because it lost track of it. If neither of these symbols appears
30473in the mode line, no embedded formulas are active in the buffer
30474(e.g., before Embedded mode has been used, or after a @kbd{M-- C-x * a}).
30475
30476Embedded formulas can refer to assignments both before and after them
30477in the buffer. If there are several assignments to a variable, the
30478nearest preceding assignment is used if there is one, otherwise the
30479following assignment is used.
30480
30481@example
30482x => 1
30483
30484x := 1
30485
30486x => 1
30487
30488x := 2
30489
30490x => 2
30491@end example
30492
30493As well as simple variables, you can also assign to subscript
30494expressions of the form @samp{@var{var}_@var{number}} (as in
30495@code{x_0}), or @samp{@var{var}_@var{var}} (as in @code{x_max}).
30496Assignments to other kinds of objects can be represented by Calc,
30497but the automatic linkage between assignments and references works
30498only for plain variables and these two kinds of subscript expressions.
30499
30500If there are no assignments to a given variable, the global
30501stored value for the variable is used (@pxref{Storing Variables}),
30502or, if no value is stored, the variable is left in symbolic form.
30503Note that global stored values will be lost when the file is saved
30504and loaded in a later Emacs session, unless you have used the
30505@kbd{s p} (@code{calc-permanent-variable}) command to save them;
30506@pxref{Operations on Variables}.
30507
30508The @kbd{m C} (@code{calc-auto-recompute}) command turns automatic
30509recomputation of @samp{=>} forms on and off. If you turn automatic
30510recomputation off, you will have to use @kbd{C-x * u} to update these
30511formulas manually after an assignment has been changed. If you
30512plan to change several assignments at once, it may be more efficient
30513to type @kbd{m C}, change all the assignments, then use @kbd{M-1 C-x * u}
30514to update the entire buffer afterwards. The @kbd{m C} command also
30515controls @samp{=>} formulas on the stack; @pxref{Evaluates-To
30516Operator}. When you turn automatic recomputation back on, the
30517stack will be updated but the Embedded buffer will not; you must
30518use @kbd{C-x * u} to update the buffer by hand.
30519
30520@node Mode Settings in Embedded Mode, Customizing Embedded Mode, Assignments in Embedded Mode, Embedded Mode
30521@section Mode Settings in Embedded Mode
30522
30523@kindex m e
30524@pindex calc-embedded-preserve-modes
30525@noindent
30526The mode settings can be changed while Calc is in embedded mode, but
30527by default they will revert to their original values when embedded mode
30528is ended. However, the modes saved when the mode-recording mode is
30529@code{Save} (see below) and the modes in effect when the @kbd{m e}
30530(@code{calc-embedded-preserve-modes}) command is given
30531will be preserved when embedded mode is ended.
30532
30533Embedded mode has a rather complicated mechanism for handling mode
30534settings in Embedded formulas. It is possible to put annotations
30535in the file that specify mode settings either global to the entire
30536file or local to a particular formula or formulas. In the latter
30537case, different modes can be specified for use when a formula
30538is the enabled Embedded mode formula.
30539
30540When you give any mode-setting command, like @kbd{m f} (for Fraction
30541mode) or @kbd{d s} (for scientific notation), Embedded mode adds
30542a line like the following one to the file just before the opening
30543delimiter of the formula.
30544
30545@example
30546% [calc-mode: fractions: t]
30547% [calc-mode: float-format: (sci 0)]
30548@end example
30549
30550When Calc interprets an embedded formula, it scans the text before
30551the formula for mode-setting annotations like these and sets the
30552Calc buffer to match these modes. Modes not explicitly described
30553in the file are not changed. Calc scans all the way to the top of
30554the file, or up to a line of the form
30555
30556@example
30557% [calc-defaults]
30558@end example
30559
30560@noindent
30561which you can insert at strategic places in the file if this backward
30562scan is getting too slow, or just to provide a barrier between one
30563``zone'' of mode settings and another.
30564
30565If the file contains several annotations for the same mode, the
30566closest one before the formula is used. Annotations after the
30567formula are never used (except for global annotations, described
30568below).
30569
30570The scan does not look for the leading @samp{% }, only for the
30571square brackets and the text they enclose. In fact, the leading
30572characters are different for different major modes. You can edit the
30573mode annotations to a style that works better in context if you wish.
30574@xref{Customizing Embedded Mode}, to see how to change the style
30575that Calc uses when it generates the annotations. You can write
30576mode annotations into the file yourself if you know the syntax;
30577the easiest way to find the syntax for a given mode is to let
30578Calc write the annotation for it once and see what it does.
30579
30580If you give a mode-changing command for a mode that already has
30581a suitable annotation just above the current formula, Calc will
30582modify that annotation rather than generating a new, conflicting
30583one.
30584
30585Mode annotations have three parts, separated by colons. (Spaces
30586after the colons are optional.) The first identifies the kind
30587of mode setting, the second is a name for the mode itself, and
30588the third is the value in the form of a Lisp symbol, number,
30589or list. Annotations with unrecognizable text in the first or
30590second parts are ignored. The third part is not checked to make
30591sure the value is of a valid type or range; if you write an
30592annotation by hand, be sure to give a proper value or results
30593will be unpredictable. Mode-setting annotations are case-sensitive.
30594
30595While Embedded mode is enabled, the word @code{Local} appears in
30596the mode line. This is to show that mode setting commands generate
30597annotations that are ``local'' to the current formula or set of
30598formulas. The @kbd{m R} (@code{calc-mode-record-mode}) command
30599causes Calc to generate different kinds of annotations. Pressing
30600@kbd{m R} repeatedly cycles through the possible modes.
30601
30602@code{LocEdit} and @code{LocPerm} modes generate annotations
30603that look like this, respectively:
30604
30605@example
30606% [calc-edit-mode: float-format: (sci 0)]
30607% [calc-perm-mode: float-format: (sci 5)]
30608@end example
30609
30610The first kind of annotation will be used only while a formula
30611is enabled in Embedded mode. The second kind will be used only
30612when the formula is @emph{not} enabled. (Whether the formula
30613is ``active'' or not, i.e., whether Calc has seen this formula
30614yet, is not relevant here.)
30615
30616@code{Global} mode generates an annotation like this at the end
30617of the file:
30618
30619@example
30620% [calc-global-mode: fractions t]
30621@end example
30622
30623Global mode annotations affect all formulas throughout the file,
30624and may appear anywhere in the file. This allows you to tuck your
30625mode annotations somewhere out of the way, say, on a new page of
30626the file, as long as those mode settings are suitable for all
30627formulas in the file.
30628
30629Enabling a formula with @kbd{C-x * e} causes a fresh scan for local
30630mode annotations; you will have to use this after adding annotations
30631above a formula by hand to get the formula to notice them. Updating
30632a formula with @kbd{C-x * u} will also re-scan the local modes, but
30633global modes are only re-scanned by @kbd{C-x * a}.
30634
30635Another way that modes can get out of date is if you add a local
30636mode annotation to a formula that has another formula after it.
30637In this example, we have used the @kbd{d s} command while the
30638first of the two embedded formulas is active. But the second
30639formula has not changed its style to match, even though by the
30640rules of reading annotations the @samp{(sci 0)} applies to it, too.
30641
30642@example
30643% [calc-mode: float-format: (sci 0)]
306441.23e2
30645
30646456.
30647@end example
30648
30649We would have to go down to the other formula and press @kbd{C-x * u}
30650on it in order to get it to notice the new annotation.
30651
30652Two more mode-recording modes selectable by @kbd{m R} are available
30653which are also available outside of Embedded mode.
30654(@pxref{General Mode Commands}.) They are @code{Save}, in which mode
30655settings are recorded permanently in your Calc init file (the file given
30656by the variable @code{calc-settings-file}, typically @file{~/.calc.el})
30657rather than by annotating the current document, and no-recording
30658mode (where there is no symbol like @code{Save} or @code{Local} in
30659the mode line), in which mode-changing commands do not leave any
30660annotations at all.
30661
30662When Embedded mode is not enabled, mode-recording modes except
30663for @code{Save} have no effect.
30664
30665@node Customizing Embedded Mode, , Mode Settings in Embedded Mode, Embedded Mode
30666@section Customizing Embedded Mode
30667
30668@noindent
30669You can modify Embedded mode's behavior by setting various Lisp
30670variables described here. These variables are customizable
30671(@pxref{Customizing Calc}), or you can use @kbd{M-x set-variable}
30672or @kbd{M-x edit-options} to adjust a variable on the fly.
30673(Another possibility would be to use a file-local variable annotation at
30674the end of the file;
30675@pxref{File Variables, , Local Variables in Files, emacs, the Emacs manual}.)
30676Many of the variables given mentioned here can be set to depend on the
30677major mode of the editing buffer (@pxref{Customizing Calc}).
30678
30679@vindex calc-embedded-open-formula
30680The @code{calc-embedded-open-formula} variable holds a regular
30681expression for the opening delimiter of a formula. @xref{Regexp Search,
30682, Regular Expression Search, emacs, the Emacs manual}, to see
30683how regular expressions work. Basically, a regular expression is a
30684pattern that Calc can search for. A regular expression that considers
30685blank lines, @samp{$}, and @samp{$$} to be opening delimiters is
30686@code{"\\`\\|^\n\\|\\$\\$?"}. Just in case the meaning of this
30687regular expression is not completely plain, let's go through it
30688in detail.
30689
30690The surrounding @samp{" "} marks quote the text between them as a
30691Lisp string. If you left them off, @code{set-variable} or
30692@code{edit-options} would try to read the regular expression as a
30693Lisp program.
30694
30695The most obvious property of this regular expression is that it
30696contains indecently many backslashes. There are actually two levels
30697of backslash usage going on here. First, when Lisp reads a quoted
30698string, all pairs of characters beginning with a backslash are
30699interpreted as special characters. Here, @code{\n} changes to a
30700new-line character, and @code{\\} changes to a single backslash.
30701So the actual regular expression seen by Calc is
30702@samp{\`\|^ @r{(newline)} \|\$\$?}.
30703
30704Regular expressions also consider pairs beginning with backslash
30705to have special meanings. Sometimes the backslash is used to quote
30706a character that otherwise would have a special meaning in a regular
30707expression, like @samp{$}, which normally means ``end-of-line,''
30708or @samp{?}, which means that the preceding item is optional. So
30709@samp{\$\$?} matches either one or two dollar signs.
30710
30711The other codes in this regular expression are @samp{^}, which matches
30712``beginning-of-line,'' @samp{\|}, which means ``or,'' and @samp{\`},
30713which matches ``beginning-of-buffer.'' So the whole pattern means
30714that a formula begins at the beginning of the buffer, or on a newline
30715that occurs at the beginning of a line (i.e., a blank line), or at
30716one or two dollar signs.
30717
30718The default value of @code{calc-embedded-open-formula} looks just
30719like this example, with several more alternatives added on to
30720recognize various other common kinds of delimiters.
30721
30722By the way, the reason to use @samp{^\n} rather than @samp{^$}
30723or @samp{\n\n}, which also would appear to match blank lines,
30724is that the former expression actually ``consumes'' only one
30725newline character as @emph{part of} the delimiter, whereas the
30726latter expressions consume zero or two newlines, respectively.
30727The former choice gives the most natural behavior when Calc
30728must operate on a whole formula including its delimiters.
30729
30730See the Emacs manual for complete details on regular expressions.
30731But just for your convenience, here is a list of all characters
30732which must be quoted with backslash (like @samp{\$}) to avoid
30733some special interpretation: @samp{. * + ? [ ] ^ $ \}. (Note
30734the backslash in this list; for example, to match @samp{\[} you
30735must use @code{"\\\\\\["}. An exercise for the reader is to
30736account for each of these six backslashes!)
30737
30738@vindex calc-embedded-close-formula
30739The @code{calc-embedded-close-formula} variable holds a regular
30740expression for the closing delimiter of a formula. A closing
30741regular expression to match the above example would be
30742@code{"\\'\\|\n$\\|\\$\\$?"}. This is almost the same as the
30743other one, except it now uses @samp{\'} (``end-of-buffer'') and
30744@samp{\n$} (newline occurring at end of line, yet another way
30745of describing a blank line that is more appropriate for this
30746case).
30747
30748@vindex calc-embedded-open-word
30749@vindex calc-embedded-close-word
30750The @code{calc-embedded-open-word} and @code{calc-embedded-close-word}
30751variables are similar expressions used when you type @kbd{C-x * w}
30752instead of @kbd{C-x * e} to enable Embedded mode.
30753
30754@vindex calc-embedded-open-plain
30755The @code{calc-embedded-open-plain} variable is a string which
30756begins a ``plain'' formula written in front of the formatted
30757formula when @kbd{d p} mode is turned on. Note that this is an
30758actual string, not a regular expression, because Calc must be able
30759to write this string into a buffer as well as to recognize it.
30760The default string is @code{"%%% "} (note the trailing space), but may
30761be different for certain major modes.
30762
30763@vindex calc-embedded-close-plain
30764The @code{calc-embedded-close-plain} variable is a string which
30765ends a ``plain'' formula. The default is @code{" %%%\n"}, but may be
30766different for different major modes. Without
30767the trailing newline here, the first line of a Big mode formula
30768that followed might be shifted over with respect to the other lines.
30769
30770@vindex calc-embedded-open-new-formula
30771The @code{calc-embedded-open-new-formula} variable is a string
30772which is inserted at the front of a new formula when you type
30773@kbd{C-x * f}. Its default value is @code{"\n\n"}. If this
30774string begins with a newline character and the @kbd{C-x * f} is
30775typed at the beginning of a line, @kbd{C-x * f} will skip this
30776first newline to avoid introducing unnecessary blank lines in
30777the file.
30778
30779@vindex calc-embedded-close-new-formula
30780The @code{calc-embedded-close-new-formula} variable is the corresponding
30781string which is inserted at the end of a new formula. Its default
30782value is also @code{"\n\n"}. The final newline is omitted by
30783@w{@kbd{C-x * f}} if typed at the end of a line. (It follows that if
30784@kbd{C-x * f} is typed on a blank line, both a leading opening
30785newline and a trailing closing newline are omitted.)
30786
30787@vindex calc-embedded-announce-formula
30788The @code{calc-embedded-announce-formula} variable is a regular
30789expression which is sure to be followed by an embedded formula.
30790The @kbd{C-x * a} command searches for this pattern as well as for
30791@samp{=>} and @samp{:=} operators. Note that @kbd{C-x * a} will
30792not activate just anything surrounded by formula delimiters; after
30793all, blank lines are considered formula delimiters by default!
30794But if your language includes a delimiter which can only occur
30795actually in front of a formula, you can take advantage of it here.
30796The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, but may be
30797different for different major modes.
30798This pattern will check for @samp{%Embed} followed by any number of
30799lines beginning with @samp{%} and a space. This last is important to
30800make Calc consider mode annotations part of the pattern, so that the
30801formula's opening delimiter really is sure to follow the pattern.
30802
30803@vindex calc-embedded-open-mode
30804The @code{calc-embedded-open-mode} variable is a string (not a
30805regular expression) which should precede a mode annotation.
30806Calc never scans for this string; Calc always looks for the
30807annotation itself. But this is the string that is inserted before
30808the opening bracket when Calc adds an annotation on its own.
30809The default is @code{"% "}, but may be different for different major
30810modes.
30811
30812@vindex calc-embedded-close-mode
30813The @code{calc-embedded-close-mode} variable is a string which
30814follows a mode annotation written by Calc. Its default value
30815is simply a newline, @code{"\n"}, but may be different for different
30816major modes. If you change this, it is a good idea still to end with a
30817newline so that mode annotations will appear on lines by themselves.
30818
30819@node Programming, Copying, Embedded Mode, Top
30820@chapter Programming
30821
30822@noindent
30823There are several ways to ``program'' the Emacs Calculator, depending
30824on the nature of the problem you need to solve.
30825
30826@enumerate
30827@item
30828@dfn{Keyboard macros} allow you to record a sequence of keystrokes
30829and play them back at a later time. This is just the standard Emacs
30830keyboard macro mechanism, dressed up with a few more features such
30831as loops and conditionals.
30832
30833@item
30834@dfn{Algebraic definitions} allow you to use any formula to define a
30835new function. This function can then be used in algebraic formulas or
30836as an interactive command.
30837
30838@item
30839@dfn{Rewrite rules} are discussed in the section on algebra commands.
30840@xref{Rewrite Rules}. If you put your rewrite rules in the variable
30841@code{EvalRules}, they will be applied automatically to all Calc
30842results in just the same way as an internal ``rule'' is applied to
30843evaluate @samp{sqrt(9)} to 3 and so on. @xref{Automatic Rewrites}.
30844
30845@item
30846@dfn{Lisp} is the programming language that Calc (and most of Emacs)
30847is written in. If the above techniques aren't powerful enough, you
30848can write Lisp functions to do anything that built-in Calc commands
30849can do. Lisp code is also somewhat faster than keyboard macros or
30850rewrite rules.
30851@end enumerate
30852
30853@kindex z
30854Programming features are available through the @kbd{z} and @kbd{Z}
30855prefix keys. New commands that you define are two-key sequences
30856beginning with @kbd{z}. Commands for managing these definitions
30857use the shift-@kbd{Z} prefix. (The @kbd{Z T} (@code{calc-timing})
30858command is described elsewhere; @pxref{Troubleshooting Commands}.
30859The @kbd{Z C} (@code{calc-user-define-composition}) command is also
30860described elsewhere; @pxref{User-Defined Compositions}.)
30861
30862@menu
30863* Creating User Keys::
30864* Keyboard Macros::
30865* Invocation Macros::
30866* Algebraic Definitions::
30867* Lisp Definitions::
30868@end menu
30869
30870@node Creating User Keys, Keyboard Macros, Programming, Programming
30871@section Creating User Keys
30872
30873@noindent
30874@kindex Z D
30875@pindex calc-user-define
30876Any Calculator command may be bound to a key using the @kbd{Z D}
30877(@code{calc-user-define}) command. Actually, it is bound to a two-key
30878sequence beginning with the lower-case @kbd{z} prefix.
30879
30880The @kbd{Z D} command first prompts for the key to define. For example,
30881press @kbd{Z D a} to define the new key sequence @kbd{z a}. You are then
30882prompted for the name of the Calculator command that this key should
30883run. For example, the @code{calc-sincos} command is not normally
30884available on a key. Typing @kbd{Z D s sincos @key{RET}} programs the
30885@kbd{z s} key sequence to run @code{calc-sincos}. This definition will remain
30886in effect for the rest of this Emacs session, or until you redefine
30887@kbd{z s} to be something else.
30888
30889You can actually bind any Emacs command to a @kbd{z} key sequence by
30890backspacing over the @samp{calc-} when you are prompted for the command name.
30891
30892As with any other prefix key, you can type @kbd{z ?} to see a list of
30893all the two-key sequences you have defined that start with @kbd{z}.
30894Initially, no @kbd{z} sequences (except @kbd{z ?} itself) are defined.
30895
30896User keys are typically letters, but may in fact be any key.
30897(@key{META}-keys are not permitted, nor are a terminal's special
30898function keys which generate multi-character sequences when pressed.)
30899You can define different commands on the shifted and unshifted versions
30900of a letter if you wish.
30901
30902@kindex Z U
30903@pindex calc-user-undefine
30904The @kbd{Z U} (@code{calc-user-undefine}) command unbinds a user key.
30905For example, the key sequence @kbd{Z U s} will undefine the @code{sincos}
30906key we defined above.
30907
30908@kindex Z P
30909@pindex calc-user-define-permanent
30910@cindex Storing user definitions
30911@cindex Permanent user definitions
30912@cindex Calc init file, user-defined commands
30913The @kbd{Z P} (@code{calc-user-define-permanent}) command makes a key
30914binding permanent so that it will remain in effect even in future Emacs
30915sessions. (It does this by adding a suitable bit of Lisp code into
30916your Calc init file; that is, the file given by the variable
30917@code{calc-settings-file}, typically @file{~/.calc.el}.) For example,
30918@kbd{Z P s} would register our @code{sincos} command permanently. If
30919you later wish to unregister this command you must edit your Calc init
30920file by hand. (@xref{General Mode Commands}, for a way to tell Calc to
30921use a different file for the Calc init file.)
30922
30923The @kbd{Z P} command also saves the user definition, if any, for the
30924command bound to the key. After @kbd{Z F} and @kbd{Z C}, a given user
30925key could invoke a command, which in turn calls an algebraic function,
30926which might have one or more special display formats. A single @kbd{Z P}
30927command will save all of these definitions.
30928To save an algebraic function, type @kbd{'} (the apostrophe)
30929when prompted for a key, and type the function name. To save a command
30930without its key binding, type @kbd{M-x} and enter a function name. (The
30931@samp{calc-} prefix will automatically be inserted for you.)
30932(If the command you give implies a function, the function will be saved,
30933and if the function has any display formats, those will be saved, but
30934not the other way around: Saving a function will not save any commands
30935or key bindings associated with the function.)
30936
30937@kindex Z E
30938@pindex calc-user-define-edit
30939@cindex Editing user definitions
30940The @kbd{Z E} (@code{calc-user-define-edit}) command edits the definition
30941of a user key. This works for keys that have been defined by either
30942keyboard macros or formulas; further details are contained in the relevant
30943following sections.
30944
30945@node Keyboard Macros, Invocation Macros, Creating User Keys, Programming
30946@section Programming with Keyboard Macros
30947
30948@noindent
30949@kindex X
30950@cindex Programming with keyboard macros
30951@cindex Keyboard macros
30952The easiest way to ``program'' the Emacs Calculator is to use standard
30953keyboard macros. Press @w{@kbd{C-x (}} to begin recording a macro. From
30954this point on, keystrokes you type will be saved away as well as
30955performing their usual functions. Press @kbd{C-x )} to end recording.
30956Press shift-@kbd{X} (or the standard Emacs key sequence @kbd{C-x e}) to
30957execute your keyboard macro by replaying the recorded keystrokes.
30958@xref{Keyboard Macros, , , emacs, the Emacs Manual}, for further
30959information.
30960
30961When you use @kbd{X} to invoke a keyboard macro, the entire macro is
30962treated as a single command by the undo and trail features. The stack
30963display buffer is not updated during macro execution, but is instead
30964fixed up once the macro completes. Thus, commands defined with keyboard
30965macros are convenient and efficient. The @kbd{C-x e} command, on the
30966other hand, invokes the keyboard macro with no special treatment: Each
30967command in the macro will record its own undo information and trail entry,
30968and update the stack buffer accordingly. If your macro uses features
30969outside of Calc's control to operate on the contents of the Calc stack
30970buffer, or if it includes Undo, Redo, or last-arguments commands, you
30971must use @kbd{C-x e} to make sure the buffer and undo list are up-to-date
30972at all times. You could also consider using @kbd{K} (@code{calc-keep-args})
30973instead of @kbd{M-@key{RET}} (@code{calc-last-args}).
30974
30975Calc extends the standard Emacs keyboard macros in several ways.
30976Keyboard macros can be used to create user-defined commands. Keyboard
30977macros can include conditional and iteration structures, somewhat
30978analogous to those provided by a traditional programmable calculator.
30979
30980@menu
30981* Naming Keyboard Macros::
30982* Conditionals in Macros::
30983* Loops in Macros::
30984* Local Values in Macros::
30985* Queries in Macros::
30986@end menu
30987
30988@node Naming Keyboard Macros, Conditionals in Macros, Keyboard Macros, Keyboard Macros
30989@subsection Naming Keyboard Macros
30990
30991@noindent
30992@kindex Z K
30993@pindex calc-user-define-kbd-macro
30994Once you have defined a keyboard macro, you can bind it to a @kbd{z}
30995key sequence with the @kbd{Z K} (@code{calc-user-define-kbd-macro}) command.
30996This command prompts first for a key, then for a command name. For
30997example, if you type @kbd{C-x ( n @key{TAB} n @key{TAB} C-x )} you will
30998define a keyboard macro which negates the top two numbers on the stack
30999(@key{TAB} swaps the top two stack elements). Now you can type
31000@kbd{Z K n @key{RET}} to define this keyboard macro onto the @kbd{z n} key
31001sequence. The default command name (if you answer the second prompt with
31002just the @key{RET} key as in this example) will be something like
31003@samp{calc-User-n}. The keyboard macro will now be available as both
31004@kbd{z n} and @kbd{M-x calc-User-n}. You can backspace and enter a more
31005descriptive command name if you wish.
31006
31007Macros defined by @kbd{Z K} act like single commands; they are executed
31008in the same way as by the @kbd{X} key. If you wish to define the macro
31009as a standard no-frills Emacs macro (to be executed as if by @kbd{C-x e}),
31010give a negative prefix argument to @kbd{Z K}.
31011
31012Once you have bound your keyboard macro to a key, you can use
31013@kbd{Z P} to register it permanently with Emacs. @xref{Creating User Keys}.
31014
31015@cindex Keyboard macros, editing
31016The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
31017been defined by a keyboard macro tries to use the @code{edmacro} package
31018edit the macro. Type @kbd{C-c C-c} to finish editing and update
31019the definition stored on the key, or, to cancel the edit, kill the
31020buffer with @kbd{C-x k}.
31021The special characters @code{RET}, @code{LFD}, @code{TAB}, @code{SPC},
31022@code{DEL}, and @code{NUL} must be entered as these three character
31023sequences, written in all uppercase, as must the prefixes @code{C-} and
31024@code{M-}. Spaces and line breaks are ignored. Other characters are
31025copied verbatim into the keyboard macro. Basically, the notation is the
31026same as is used in all of this manual's examples, except that the manual
31027takes some liberties with spaces: When we say @kbd{' [1 2 3] @key{RET}},
31028we take it for granted that it is clear we really mean
31029@kbd{' [1 @key{SPC} 2 @key{SPC} 3] @key{RET}}.
31030
31031@kindex C-x * m
31032@pindex read-kbd-macro
31033The @kbd{C-x * m} (@code{read-kbd-macro}) command reads an Emacs ``region''
31034of spelled-out keystrokes and defines it as the current keyboard macro.
31035It is a convenient way to define a keyboard macro that has been stored
31036in a file, or to define a macro without executing it at the same time.
31037
31038@node Conditionals in Macros, Loops in Macros, Naming Keyboard Macros, Keyboard Macros
31039@subsection Conditionals in Keyboard Macros
31040
31041@noindent
31042@kindex Z [
31043@kindex Z ]
31044@pindex calc-kbd-if
31045@pindex calc-kbd-else
31046@pindex calc-kbd-else-if
31047@pindex calc-kbd-end-if
31048@cindex Conditional structures
31049The @kbd{Z [} (@code{calc-kbd-if}) and @kbd{Z ]} (@code{calc-kbd-end-if})
31050commands allow you to put simple tests in a keyboard macro. When Calc
31051sees the @kbd{Z [}, it pops an object from the stack and, if the object is
31052a non-zero value, continues executing keystrokes. But if the object is
31053zero, or if it is not provably nonzero, Calc skips ahead to the matching
31054@kbd{Z ]} keystroke. @xref{Logical Operations}, for a set of commands for
31055performing tests which conveniently produce 1 for true and 0 for false.
31056
31057For example, @kbd{@key{RET} 0 a < Z [ n Z ]} implements an absolute-value
31058function in the form of a keyboard macro. This macro duplicates the
31059number on the top of the stack, pushes zero and compares using @kbd{a <}
31060(@code{calc-less-than}), then, if the number was less than zero,
31061executes @kbd{n} (@code{calc-change-sign}). Otherwise, the change-sign
31062command is skipped.
31063
31064To program this macro, type @kbd{C-x (}, type the above sequence of
31065keystrokes, then type @kbd{C-x )}. Note that the keystrokes will be
31066executed while you are making the definition as well as when you later
31067re-execute the macro by typing @kbd{X}. Thus you should make sure a
31068suitable number is on the stack before defining the macro so that you
31069don't get a stack-underflow error during the definition process.
31070
31071Conditionals can be nested arbitrarily. However, there should be exactly
31072one @kbd{Z ]} for each @kbd{Z [} in a keyboard macro.
31073
31074@kindex Z :
31075The @kbd{Z :} (@code{calc-kbd-else}) command allows you to choose between
31076two keystroke sequences. The general format is @kbd{@var{cond} Z [
31077@var{then-part} Z : @var{else-part} Z ]}. If @var{cond} is true
31078(i.e., if the top of stack contains a non-zero number after @var{cond}
31079has been executed), the @var{then-part} will be executed and the
31080@var{else-part} will be skipped. Otherwise, the @var{then-part} will
31081be skipped and the @var{else-part} will be executed.
31082
31083@kindex Z |
31084The @kbd{Z |} (@code{calc-kbd-else-if}) command allows you to choose
31085between any number of alternatives. For example,
31086@kbd{@var{cond1} Z [ @var{part1} Z : @var{cond2} Z | @var{part2} Z :
31087@var{part3} Z ]} will execute @var{part1} if @var{cond1} is true,
31088otherwise it will execute @var{part2} if @var{cond2} is true, otherwise
31089it will execute @var{part3}.
31090
31091More precisely, @kbd{Z [} pops a number and conditionally skips to the
31092next matching @kbd{Z :} or @kbd{Z ]} key. @w{@kbd{Z ]}} has no effect when
31093actually executed. @kbd{Z :} skips to the next matching @kbd{Z ]}.
31094@kbd{Z |} pops a number and conditionally skips to the next matching
31095@kbd{Z :} or @kbd{Z ]}; thus, @kbd{Z [} and @kbd{Z |} are functionally
31096equivalent except that @kbd{Z [} participates in nesting but @kbd{Z |}
31097does not.
31098
31099Calc's conditional and looping constructs work by scanning the
31100keyboard macro for occurrences of character sequences like @samp{Z:}
31101and @samp{Z]}. One side-effect of this is that if you use these
31102constructs you must be careful that these character pairs do not
31103occur by accident in other parts of the macros. Since Calc rarely
31104uses shift-@kbd{Z} for any purpose except as a prefix character, this
31105is not likely to be a problem. Another side-effect is that it will
31106not work to define your own custom key bindings for these commands.
31107Only the standard shift-@kbd{Z} bindings will work correctly.
31108
31109@kindex Z C-g
31110If Calc gets stuck while skipping characters during the definition of a
31111macro, type @kbd{Z C-g} to cancel the definition. (Typing plain @kbd{C-g}
31112actually adds a @kbd{C-g} keystroke to the macro.)
31113
31114@node Loops in Macros, Local Values in Macros, Conditionals in Macros, Keyboard Macros
31115@subsection Loops in Keyboard Macros
31116
31117@noindent
31118@kindex Z <
31119@kindex Z >
31120@pindex calc-kbd-repeat
31121@pindex calc-kbd-end-repeat
31122@cindex Looping structures
31123@cindex Iterative structures
31124The @kbd{Z <} (@code{calc-kbd-repeat}) and @kbd{Z >}
31125(@code{calc-kbd-end-repeat}) commands pop a number from the stack,
31126which must be an integer, then repeat the keystrokes between the brackets
31127the specified number of times. If the integer is zero or negative, the
31128body is skipped altogether. For example, @kbd{1 @key{TAB} Z < 2 * Z >}
31129computes two to a nonnegative integer power. First, we push 1 on the
31130stack and then swap the integer argument back to the top. The @kbd{Z <}
31131pops that argument leaving the 1 back on top of the stack. Then, we
31132repeat a multiply-by-two step however many times.
31133
31134Once again, the keyboard macro is executed as it is being entered.
31135In this case it is especially important to set up reasonable initial
31136conditions before making the definition: Suppose the integer 1000 just
31137happened to be sitting on the stack before we typed the above definition!
31138Another approach is to enter a harmless dummy definition for the macro,
31139then go back and edit in the real one with a @kbd{Z E} command. Yet
31140another approach is to type the macro as written-out keystroke names
31141in a buffer, then use @kbd{C-x * m} (@code{read-kbd-macro}) to read the
31142macro.
31143
31144@kindex Z /
31145@pindex calc-break
31146The @kbd{Z /} (@code{calc-kbd-break}) command allows you to break out
31147of a keyboard macro loop prematurely. It pops an object from the stack;
31148if that object is true (a non-zero number), control jumps out of the
31149innermost enclosing @kbd{Z <} @dots{} @kbd{Z >} loop and continues
31150after the @kbd{Z >}. If the object is false, the @kbd{Z /} has no
31151effect. Thus @kbd{@var{cond} Z /} is similar to @samp{if (@var{cond}) break;}
31152in the C language.
31153
31154@kindex Z (
31155@kindex Z )
31156@pindex calc-kbd-for
31157@pindex calc-kbd-end-for
31158The @kbd{Z (} (@code{calc-kbd-for}) and @kbd{Z )} (@code{calc-kbd-end-for})
31159commands are similar to @kbd{Z <} and @kbd{Z >}, except that they make the
31160value of the counter available inside the loop. The general layout is
31161@kbd{@var{init} @var{final} Z ( @var{body} @var{step} Z )}. The @kbd{Z (}
31162command pops initial and final values from the stack. It then creates
31163a temporary internal counter and initializes it with the value @var{init}.
31164The @kbd{Z (} command then repeatedly pushes the counter value onto the
31165stack and executes @var{body} and @var{step}, adding @var{step} to the
31166counter each time until the loop finishes.
31167
31168@cindex Summations (by keyboard macros)
31169By default, the loop finishes when the counter becomes greater than (or
31170less than) @var{final}, assuming @var{initial} is less than (greater
31171than) @var{final}. If @var{initial} is equal to @var{final}, the body
31172executes exactly once. The body of the loop always executes at least
31173once. For example, @kbd{0 1 10 Z ( 2 ^ + 1 Z )} computes the sum of the
31174squares of the integers from 1 to 10, in steps of 1.
31175
31176If you give a numeric prefix argument of 1 to @kbd{Z (}, the loop is
31177forced to use upward-counting conventions. In this case, if @var{initial}
31178is greater than @var{final} the body will not be executed at all.
31179Note that @var{step} may still be negative in this loop; the prefix
31180argument merely constrains the loop-finished test. Likewise, a prefix
31181argument of @mathit{-1} forces downward-counting conventions.
31182
31183@kindex Z @{
31184@kindex Z @}
31185@pindex calc-kbd-loop
31186@pindex calc-kbd-end-loop
31187The @kbd{Z @{} (@code{calc-kbd-loop}) and @kbd{Z @}}
31188(@code{calc-kbd-end-loop}) commands are similar to @kbd{Z <} and
31189@kbd{Z >}, except that they do not pop a count from the stack---they
31190effectively create an infinite loop. Every @kbd{Z @{} @dots{} @kbd{Z @}}
31191loop ought to include at least one @kbd{Z /} to make sure the loop
31192doesn't run forever. (If any error message occurs which causes Emacs
31193to beep, the keyboard macro will also be halted; this is a standard
31194feature of Emacs. You can also generally press @kbd{C-g} to halt a
31195running keyboard macro, although not all versions of Unix support
31196this feature.)
31197
31198The conditional and looping constructs are not actually tied to
31199keyboard macros, but they are most often used in that context.
31200For example, the keystrokes @kbd{10 Z < 23 @key{RET} Z >} push
31201ten copies of 23 onto the stack. This can be typed ``live'' just
31202as easily as in a macro definition.
31203
31204@xref{Conditionals in Macros}, for some additional notes about
31205conditional and looping commands.
31206
31207@node Local Values in Macros, Queries in Macros, Loops in Macros, Keyboard Macros
31208@subsection Local Values in Macros
31209
31210@noindent
31211@cindex Local variables
31212@cindex Restoring saved modes
31213Keyboard macros sometimes want to operate under known conditions
31214without affecting surrounding conditions. For example, a keyboard
31215macro may wish to turn on Fraction mode, or set a particular
31216precision, independent of the user's normal setting for those
31217modes.
31218
31219@kindex Z `
31220@kindex Z '
31221@pindex calc-kbd-push
31222@pindex calc-kbd-pop
31223Macros also sometimes need to use local variables. Assignments to
31224local variables inside the macro should not affect any variables
31225outside the macro. The @kbd{Z `} (@code{calc-kbd-push}) and @kbd{Z '}
31226(@code{calc-kbd-pop}) commands give you both of these capabilities.
31227
31228When you type @kbd{Z `} (with a backquote or accent grave character),
31229the values of various mode settings are saved away. The ten ``quick''
31230variables @code{q0} through @code{q9} are also saved. When
31231you type @w{@kbd{Z '}} (with an apostrophe), these values are restored.
31232Pairs of @kbd{Z `} and @kbd{Z '} commands may be nested.
31233
31234If a keyboard macro halts due to an error in between a @kbd{Z `} and
31235a @kbd{Z '}, the saved values will be restored correctly even though
31236the macro never reaches the @kbd{Z '} command. Thus you can use
31237@kbd{Z `} and @kbd{Z '} without having to worry about what happens
31238in exceptional conditions.
31239
31240If you type @kbd{Z `} ``live'' (not in a keyboard macro), Calc puts
31241you into a ``recursive edit.'' You can tell you are in a recursive
31242edit because there will be extra square brackets in the mode line,
31243as in @samp{[(Calculator)]}. These brackets will go away when you
31244type the matching @kbd{Z '} command. The modes and quick variables
31245will be saved and restored in just the same way as if actual keyboard
31246macros were involved.
31247
31248The modes saved by @kbd{Z `} and @kbd{Z '} are the current precision
31249and binary word size, the angular mode (Deg, Rad, or HMS), the
31250simplification mode, Algebraic mode, Symbolic mode, Infinite mode,
31251Matrix or Scalar mode, Fraction mode, and the current complex mode
31252(Polar or Rectangular). The ten ``quick'' variables' values (or lack
31253thereof) are also saved.
31254
31255Most mode-setting commands act as toggles, but with a numeric prefix
31256they force the mode either on (positive prefix) or off (negative
31257or zero prefix). Since you don't know what the environment might
31258be when you invoke your macro, it's best to use prefix arguments
31259for all mode-setting commands inside the macro.
31260
31261In fact, @kbd{C-u Z `} is like @kbd{Z `} except that it sets the modes
31262listed above to their default values. As usual, the matching @kbd{Z '}
31263will restore the modes to their settings from before the @kbd{C-u Z `}.
31264Also, @w{@kbd{Z `}} with a negative prefix argument resets the algebraic mode
31265to its default (off) but leaves the other modes the same as they were
31266outside the construct.
31267
31268The contents of the stack and trail, values of non-quick variables, and
31269other settings such as the language mode and the various display modes,
31270are @emph{not} affected by @kbd{Z `} and @kbd{Z '}.
31271
31272@node Queries in Macros, , Local Values in Macros, Keyboard Macros
31273@subsection Queries in Keyboard Macros
31274
31275@c @noindent
31276@c @kindex Z =
31277@c @pindex calc-kbd-report
31278@c The @kbd{Z =} (@code{calc-kbd-report}) command displays an informative
31279@c message including the value on the top of the stack. You are prompted
31280@c to enter a string. That string, along with the top-of-stack value,
31281@c is displayed unless @kbd{m w} (@code{calc-working}) has been used
31282@c to turn such messages off.
31283
31284@noindent
31285@kindex Z #
31286@pindex calc-kbd-query
31287The @kbd{Z #} (@code{calc-kbd-query}) command prompts for an algebraic
31288entry which takes its input from the keyboard, even during macro
31289execution. All the normal conventions of algebraic input, including the
31290use of @kbd{$} characters, are supported. The prompt message itself is
31291taken from the top of the stack, and so must be entered (as a string)
31292before the @kbd{Z #} command. (Recall, as a string it can be entered by
31293pressing the @kbd{"} key and will appear as a vector when it is put on
31294the stack. The prompt message is only put on the stack to provide a
31295prompt for the @kbd{Z #} command; it will not play any role in any
31296subsequent calculations.) This command allows your keyboard macros to
31297accept numbers or formulas as interactive input.
31298
31299As an example,
31300@kbd{2 @key{RET} "Power: " @key{RET} Z # 3 @key{RET} ^} will prompt for
31301input with ``Power: '' in the minibuffer, then return 2 to the provided
31302power. (The response to the prompt that's given, 3 in this example,
31303will not be part of the macro.)
31304
31305@xref{Keyboard Macro Query, , , emacs, the Emacs Manual}, for a description of
31306@kbd{C-x q} (@code{kbd-macro-query}), the standard Emacs way to accept
31307keyboard input during a keyboard macro. In particular, you can use
31308@kbd{C-x q} to enter a recursive edit, which allows the user to perform
31309any Calculator operations interactively before pressing @kbd{C-M-c} to
31310return control to the keyboard macro.
31311
31312@node Invocation Macros, Algebraic Definitions, Keyboard Macros, Programming
31313@section Invocation Macros
31314
31315@kindex C-x * z
31316@kindex Z I
31317@pindex calc-user-invocation
31318@pindex calc-user-define-invocation
31319Calc provides one special keyboard macro, called up by @kbd{C-x * z}
31320(@code{calc-user-invocation}), that is intended to allow you to define
31321your own special way of starting Calc. To define this ``invocation
31322macro,'' create the macro in the usual way with @kbd{C-x (} and
31323@kbd{C-x )}, then type @kbd{Z I} (@code{calc-user-define-invocation}).
31324There is only one invocation macro, so you don't need to type any
31325additional letters after @kbd{Z I}. From now on, you can type
31326@kbd{C-x * z} at any time to execute your invocation macro.
31327
31328For example, suppose you find yourself often grabbing rectangles of
31329numbers into Calc and multiplying their columns. You can do this
31330by typing @kbd{C-x * r} to grab, and @kbd{V R : *} to multiply columns.
31331To make this into an invocation macro, just type @kbd{C-x ( C-x * r
31332V R : * C-x )}, then @kbd{Z I}. Then, to multiply a rectangle of data,
31333just mark the data in its buffer in the usual way and type @kbd{C-x * z}.
31334
31335Invocation macros are treated like regular Emacs keyboard macros;
31336all the special features described above for @kbd{Z K}-style macros
31337do not apply. @kbd{C-x * z} is just like @kbd{C-x e}, except that it
31338uses the macro that was last stored by @kbd{Z I}. (In fact, the
31339macro does not even have to have anything to do with Calc!)
31340
31341The @kbd{m m} command saves the last invocation macro defined by
31342@kbd{Z I} along with all the other Calc mode settings.
31343@xref{General Mode Commands}.
31344
31345@node Algebraic Definitions, Lisp Definitions, Invocation Macros, Programming
31346@section Programming with Formulas
31347
31348@noindent
31349@kindex Z F
31350@pindex calc-user-define-formula
31351@cindex Programming with algebraic formulas
31352Another way to create a new Calculator command uses algebraic formulas.
31353The @kbd{Z F} (@code{calc-user-define-formula}) command stores the
31354formula at the top of the stack as the definition for a key. This
31355command prompts for five things: The key, the command name, the function
31356name, the argument list, and the behavior of the command when given
31357non-numeric arguments.
31358
31359For example, suppose we type @kbd{' a+2b @key{RET}} to push the formula
31360@samp{a + 2*b} onto the stack. We now type @kbd{Z F m} to define this
31361formula on the @kbd{z m} key sequence. The next prompt is for a command
31362name, beginning with @samp{calc-}, which should be the long (@kbd{M-x}) form
31363for the new command. If you simply press @key{RET}, a default name like
31364@code{calc-User-m} will be constructed. In our example, suppose we enter
31365@kbd{spam @key{RET}} to define the new command as @code{calc-spam}.
31366
31367If you want to give the formula a long-style name only, you can press
31368@key{SPC} or @key{RET} when asked which single key to use. For example
31369@kbd{Z F @key{RET} spam @key{RET}} defines the new command as
31370@kbd{M-x calc-spam}, with no keyboard equivalent.
31371
31372The third prompt is for an algebraic function name. The default is to
31373use the same name as the command name but without the @samp{calc-}
31374prefix. (If this is of the form @samp{User-m}, the hyphen is removed so
31375it won't be taken for a minus sign in algebraic formulas.)
31376This is the name you will use if you want to enter your
31377new function in an algebraic formula. Suppose we enter @kbd{yow @key{RET}}.
31378Then the new function can be invoked by pushing two numbers on the
31379stack and typing @kbd{z m} or @kbd{x spam}, or by entering the algebraic
31380formula @samp{yow(x,y)}.
31381
31382The fourth prompt is for the function's argument list. This is used to
31383associate values on the stack with the variables that appear in the formula.
31384The default is a list of all variables which appear in the formula, sorted
31385into alphabetical order. In our case, the default would be @samp{(a b)}.
31386This means that, when the user types @kbd{z m}, the Calculator will remove
31387two numbers from the stack, substitute these numbers for @samp{a} and
31388@samp{b} (respectively) in the formula, then simplify the formula and
31389push the result on the stack. In other words, @kbd{10 @key{RET} 100 z m}
31390would replace the 10 and 100 on the stack with the number 210, which is
31391@expr{a + 2 b} with @expr{a=10} and @expr{b=100}. Likewise, the formula
31392@samp{yow(10, 100)} will be evaluated by substituting @expr{a=10} and
31393@expr{b=100} in the definition.
31394
31395You can rearrange the order of the names before pressing @key{RET} to
31396control which stack positions go to which variables in the formula. If
31397you remove a variable from the argument list, that variable will be left
31398in symbolic form by the command. Thus using an argument list of @samp{(b)}
31399for our function would cause @kbd{10 z m} to replace the 10 on the stack
31400with the formula @samp{a + 20}. If we had used an argument list of
31401@samp{(b a)}, the result with inputs 10 and 100 would have been 120.
31402
31403You can also put a nameless function on the stack instead of just a
31404formula, as in @samp{<a, b : a + 2 b>}. @xref{Specifying Operators}.
31405In this example, the command will be defined by the formula @samp{a + 2 b}
31406using the argument list @samp{(a b)}.
31407
31408The final prompt is a y-or-n question concerning what to do if symbolic
31409arguments are given to your function. If you answer @kbd{y}, then
31410executing @kbd{z m} (using the original argument list @samp{(a b)}) with
31411arguments @expr{10} and @expr{x} will leave the function in symbolic
31412form, i.e., @samp{yow(10,x)}. On the other hand, if you answer @kbd{n},
31413then the formula will always be expanded, even for non-constant
31414arguments: @samp{10 + 2 x}. If you never plan to feed algebraic
31415formulas to your new function, it doesn't matter how you answer this
31416question.
31417
31418If you answered @kbd{y} to this question you can still cause a function
31419call to be expanded by typing @kbd{a "} (@code{calc-expand-formula}).
31420Also, Calc will expand the function if necessary when you take a
31421derivative or integral or solve an equation involving the function.
31422
31423@kindex Z G
31424@pindex calc-get-user-defn
31425Once you have defined a formula on a key, you can retrieve this formula
31426with the @kbd{Z G} (@code{calc-user-define-get-defn}) command. Press a
31427key, and this command pushes the formula that was used to define that
31428key onto the stack. Actually, it pushes a nameless function that
31429specifies both the argument list and the defining formula. You will get
31430an error message if the key is undefined, or if the key was not defined
31431by a @kbd{Z F} command.
31432
31433The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
31434been defined by a formula uses a variant of the @code{calc-edit} command
31435to edit the defining formula. Press @kbd{C-c C-c} to finish editing and
31436store the new formula back in the definition, or kill the buffer with
31437@kbd{C-x k} to
31438cancel the edit. (The argument list and other properties of the
31439definition are unchanged; to adjust the argument list, you can use
31440@kbd{Z G} to grab the function onto the stack, edit with @kbd{`}, and
31441then re-execute the @kbd{Z F} command.)
31442
31443As usual, the @kbd{Z P} command records your definition permanently.
31444In this case it will permanently record all three of the relevant
31445definitions: the key, the command, and the function.
31446
31447You may find it useful to turn off the default simplifications with
31448@kbd{m O} (@code{calc-no-simplify-mode}) when entering a formula to be
31449used as a function definition. For example, the formula @samp{deriv(a^2,v)}
31450which might be used to define a new function @samp{dsqr(a,v)} will be
31451``simplified'' to 0 immediately upon entry since @code{deriv} considers
31452@expr{a} to be constant with respect to @expr{v}. Turning off
31453default simplifications cures this problem: The definition will be stored
31454in symbolic form without ever activating the @code{deriv} function. Press
31455@kbd{m D} to turn the default simplifications back on afterwards.
31456
31457@node Lisp Definitions, , Algebraic Definitions, Programming
31458@section Programming with Lisp
31459
31460@noindent
31461The Calculator can be programmed quite extensively in Lisp. All you
31462do is write a normal Lisp function definition, but with @code{defmath}
31463in place of @code{defun}. This has the same form as @code{defun}, but it
31464automagically replaces calls to standard Lisp functions like @code{+} and
31465@code{zerop} with calls to the corresponding functions in Calc's own library.
31466Thus you can write natural-looking Lisp code which operates on all of the
31467standard Calculator data types. You can then use @kbd{Z D} if you wish to
31468bind your new command to a @kbd{z}-prefix key sequence. The @kbd{Z E} command
31469will not edit a Lisp-based definition.
31470
31471Emacs Lisp is described in the GNU Emacs Lisp Reference Manual. This section
31472assumes a familiarity with Lisp programming concepts; if you do not know
31473Lisp, you may find keyboard macros or rewrite rules to be an easier way
31474to program the Calculator.
31475
31476This section first discusses ways to write commands, functions, or
31477small programs to be executed inside of Calc. Then it discusses how
31478your own separate programs are able to call Calc from the outside.
31479Finally, there is a list of internal Calc functions and data structures
31480for the true Lisp enthusiast.
31481
31482@menu
31483* Defining Functions::
31484* Defining Simple Commands::
31485* Defining Stack Commands::
31486* Argument Qualifiers::
31487* Example Definitions::
31488
31489* Calling Calc from Your Programs::
31490* Internals::
31491@end menu
31492
31493@node Defining Functions, Defining Simple Commands, Lisp Definitions, Lisp Definitions
31494@subsection Defining New Functions
31495
31496@noindent
31497@findex defmath
31498The @code{defmath} function (actually a Lisp macro) is like @code{defun}
31499except that code in the body of the definition can make use of the full
31500range of Calculator data types. The prefix @samp{calcFunc-} is added
31501to the specified name to get the actual Lisp function name. As a simple
31502example,
31503
31504@example
31505(defmath myfact (n)
31506 (if (> n 0)
31507 (* n (myfact (1- n)))
31508 1))
31509@end example
31510
31511@noindent
31512This actually expands to the code,
31513
31514@example
31515(defun calcFunc-myfact (n)
31516 (if (math-posp n)
31517 (math-mul n (calcFunc-myfact (math-add n -1)))
31518 1))
31519@end example
31520
31521@noindent
31522This function can be used in algebraic expressions, e.g., @samp{myfact(5)}.
31523
31524The @samp{myfact} function as it is defined above has the bug that an
31525expression @samp{myfact(a+b)} will be simplified to 1 because the
31526formula @samp{a+b} is not considered to be @code{posp}. A robust
31527factorial function would be written along the following lines:
31528
31529@smallexample
31530(defmath myfact (n)
31531 (if (> n 0)
31532 (* n (myfact (1- n)))
31533 (if (= n 0)
31534 1
31535 nil))) ; this could be simplified as: (and (= n 0) 1)
31536@end smallexample
31537
31538If a function returns @code{nil}, it is left unsimplified by the Calculator
31539(except that its arguments will be simplified). Thus, @samp{myfact(a+1+2)}
31540will be simplified to @samp{myfact(a+3)} but no further. Beware that every
31541time the Calculator reexamines this formula it will attempt to resimplify
31542it, so your function ought to detect the returning-@code{nil} case as
31543efficiently as possible.
31544
31545The following standard Lisp functions are treated by @code{defmath}:
31546@code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^} or
31547@code{expt}, @code{=}, @code{<}, @code{>}, @code{<=}, @code{>=},
31548@code{/=}, @code{1+}, @code{1-}, @code{logand}, @code{logior}, @code{logxor},
31549@code{logandc2}, @code{lognot}. Also, @code{~=} is an abbreviation for
31550@code{math-nearly-equal}, which is useful in implementing Taylor series.
31551
31552For other functions @var{func}, if a function by the name
31553@samp{calcFunc-@var{func}} exists it is used, otherwise if a function by the
31554name @samp{math-@var{func}} exists it is used, otherwise if @var{func} itself
31555is defined as a function it is used, otherwise @samp{calcFunc-@var{func}} is
31556used on the assumption that this is a to-be-defined math function. Also, if
31557the function name is quoted as in @samp{('integerp a)} the function name is
31558always used exactly as written (but not quoted).
31559
31560Variable names have @samp{var-} prepended to them unless they appear in
31561the function's argument list or in an enclosing @code{let}, @code{let*},
31562@code{for}, or @code{foreach} form,
31563or their names already contain a @samp{-} character. Thus a reference to
31564@samp{foo} is the same as a reference to @samp{var-foo}.
31565
31566A few other Lisp extensions are available in @code{defmath} definitions:
31567
31568@itemize @bullet
31569@item
31570The @code{elt} function accepts any number of index variables.
31571Note that Calc vectors are stored as Lisp lists whose first
31572element is the symbol @code{vec}; thus, @samp{(elt v 2)} yields
31573the second element of vector @code{v}, and @samp{(elt m i j)}
31574yields one element of a Calc matrix.
31575
31576@item
31577The @code{setq} function has been extended to act like the Common
31578Lisp @code{setf} function. (The name @code{setf} is recognized as
31579a synonym of @code{setq}.) Specifically, the first argument of
31580@code{setq} can be an @code{nth}, @code{elt}, @code{car}, or @code{cdr} form,
31581in which case the effect is to store into the specified
31582element of a list. Thus, @samp{(setq (elt m i j) x)} stores @expr{x}
31583into one element of a matrix.
31584
31585@item
31586A @code{for} looping construct is available. For example,
31587@samp{(for ((i 0 10)) body)} executes @code{body} once for each
31588binding of @expr{i} from zero to 10. This is like a @code{let}
31589form in that @expr{i} is temporarily bound to the loop count
31590without disturbing its value outside the @code{for} construct.
31591Nested loops, as in @samp{(for ((i 0 10) (j 0 (1- i) 2)) body)},
31592are also available. For each value of @expr{i} from zero to 10,
31593@expr{j} counts from 0 to @expr{i-1} in steps of two. Note that
31594@code{for} has the same general outline as @code{let*}, except
31595that each element of the header is a list of three or four
31596things, not just two.
31597
31598@item
31599The @code{foreach} construct loops over elements of a list.
31600For example, @samp{(foreach ((x (cdr v))) body)} executes
31601@code{body} with @expr{x} bound to each element of Calc vector
31602@expr{v} in turn. The purpose of @code{cdr} here is to skip over
31603the initial @code{vec} symbol in the vector.
31604
31605@item
31606The @code{break} function breaks out of the innermost enclosing
31607@code{while}, @code{for}, or @code{foreach} loop. If given a
31608value, as in @samp{(break x)}, this value is returned by the
31609loop. (Lisp loops otherwise always return @code{nil}.)
31610
31611@item
31612The @code{return} function prematurely returns from the enclosing
31613function. For example, @samp{(return (+ x y))} returns @expr{x+y}
31614as the value of a function. You can use @code{return} anywhere
31615inside the body of the function.
31616@end itemize
31617
31618Non-integer numbers (and extremely large integers) cannot be included
31619directly into a @code{defmath} definition. This is because the Lisp
31620reader will fail to parse them long before @code{defmath} ever gets control.
31621Instead, use the notation, @samp{:"3.1415"}. In fact, any algebraic
31622formula can go between the quotes. For example,
31623
31624@smallexample
31625(defmath sqexp (x) ; sqexp(x) == sqrt(exp(x)) == exp(x*0.5)
31626 (and (numberp x)
31627 (exp :"x * 0.5")))
31628@end smallexample
31629
31630expands to
31631
31632@smallexample
31633(defun calcFunc-sqexp (x)
31634 (and (math-numberp x)
31635 (calcFunc-exp (math-mul x '(float 5 -1)))))
31636@end smallexample
31637
31638Note the use of @code{numberp} as a guard to ensure that the argument is
31639a number first, returning @code{nil} if not. The exponential function
31640could itself have been included in the expression, if we had preferred:
31641@samp{:"exp(x * 0.5)"}. As another example, the multiplication-and-recursion
31642step of @code{myfact} could have been written
31643
31644@example
31645:"n * myfact(n-1)"
31646@end example
31647
31648A good place to put your @code{defmath} commands is your Calc init file
31649(the file given by @code{calc-settings-file}, typically
31650@file{~/.calc.el}), which will not be loaded until Calc starts.
31651If a file named @file{.emacs} exists in your home directory, Emacs reads
31652and executes the Lisp forms in this file as it starts up. While it may
31653seem reasonable to put your favorite @code{defmath} commands there,
31654this has the unfortunate side-effect that parts of the Calculator must be
31655loaded in to process the @code{defmath} commands whether or not you will
31656actually use the Calculator! If you want to put the @code{defmath}
31657commands there (for example, if you redefine @code{calc-settings-file}
31658to be @file{.emacs}), a better effect can be had by writing
31659
31660@example
31661(put 'calc-define 'thing '(progn
31662 (defmath ... )
31663 (defmath ... )
31664))
31665@end example
31666
31667@noindent
31668@vindex calc-define
31669The @code{put} function adds a @dfn{property} to a symbol. Each Lisp
31670symbol has a list of properties associated with it. Here we add a
31671property with a name of @code{thing} and a @samp{(progn ...)} form as
31672its value. When Calc starts up, and at the start of every Calc command,
31673the property list for the symbol @code{calc-define} is checked and the
31674values of any properties found are evaluated as Lisp forms. The
31675properties are removed as they are evaluated. The property names
31676(like @code{thing}) are not used; you should choose something like the
31677name of your project so as not to conflict with other properties.
31678
31679The net effect is that you can put the above code in your @file{.emacs}
31680file and it will not be executed until Calc is loaded. Or, you can put
31681that same code in another file which you load by hand either before or
31682after Calc itself is loaded.
31683
31684The properties of @code{calc-define} are evaluated in the same order
31685that they were added. They can assume that the Calc modules @file{calc.el},
31686@file{calc-ext.el}, and @file{calc-macs.el} have been fully loaded, and
31687that the @samp{*Calculator*} buffer will be the current buffer.
31688
31689If your @code{calc-define} property only defines algebraic functions,
31690you can be sure that it will have been evaluated before Calc tries to
31691call your function, even if the file defining the property is loaded
31692after Calc is loaded. But if the property defines commands or key
31693sequences, it may not be evaluated soon enough. (Suppose it defines the
31694new command @code{tweak-calc}; the user can load your file, then type
31695@kbd{M-x tweak-calc} before Calc has had chance to do anything.) To
31696protect against this situation, you can put
31697
31698@example
31699(run-hooks 'calc-check-defines)
31700@end example
31701
31702@findex calc-check-defines
31703@noindent
31704at the end of your file. The @code{calc-check-defines} function is what
31705looks for and evaluates properties on @code{calc-define}; @code{run-hooks}
31706has the advantage that it is quietly ignored if @code{calc-check-defines}
31707is not yet defined because Calc has not yet been loaded.
31708
31709Examples of things that ought to be enclosed in a @code{calc-define}
31710property are @code{defmath} calls, @code{define-key} calls that modify
31711the Calc key map, and any calls that redefine things defined inside Calc.
31712Ordinary @code{defun}s need not be enclosed with @code{calc-define}.
31713
31714@node Defining Simple Commands, Defining Stack Commands, Defining Functions, Lisp Definitions
31715@subsection Defining New Simple Commands
31716
31717@noindent
31718@findex interactive
31719If a @code{defmath} form contains an @code{interactive} clause, it defines
31720a Calculator command. Actually such a @code{defmath} results in @emph{two}
31721function definitions: One, a @samp{calcFunc-} function as was just described,
31722with the @code{interactive} clause removed. Two, a @samp{calc-} function
31723with a suitable @code{interactive} clause and some sort of wrapper to make
31724the command work in the Calc environment.
31725
31726In the simple case, the @code{interactive} clause has the same form as
31727for normal Emacs Lisp commands:
31728
31729@smallexample
31730(defmath increase-precision (delta)
31731 "Increase precision by DELTA." ; This is the "documentation string"
31732 (interactive "p") ; Register this as a M-x-able command
31733 (setq calc-internal-prec (+ calc-internal-prec delta)))
31734@end smallexample
31735
31736This expands to the pair of definitions,
31737
31738@smallexample
31739(defun calc-increase-precision (delta)
31740 "Increase precision by DELTA."
31741 (interactive "p")
31742 (calc-wrapper
31743 (setq calc-internal-prec (math-add calc-internal-prec delta))))
31744
31745(defun calcFunc-increase-precision (delta)
31746 "Increase precision by DELTA."
31747 (setq calc-internal-prec (math-add calc-internal-prec delta)))
31748@end smallexample
31749
31750@noindent
31751where in this case the latter function would never really be used! Note
31752that since the Calculator stores small integers as plain Lisp integers,
31753the @code{math-add} function will work just as well as the native
31754@code{+} even when the intent is to operate on native Lisp integers.
31755
31756@findex calc-wrapper
31757The @samp{calc-wrapper} call invokes a macro which surrounds the body of
31758the function with code that looks roughly like this:
31759
31760@smallexample
31761(let ((calc-command-flags nil))
31762 (unwind-protect
31763 (save-excursion
31764 (calc-select-buffer)
31765 @emph{body of function}
31766 @emph{renumber stack}
31767 @emph{clear} Working @emph{message})
31768 @emph{realign cursor and window}
31769 @emph{clear Inverse, Hyperbolic, and Keep Args flags}
31770 @emph{update Emacs mode line}))
31771@end smallexample
31772
31773@findex calc-select-buffer
31774The @code{calc-select-buffer} function selects the @samp{*Calculator*}
31775buffer if necessary, say, because the command was invoked from inside
31776the @samp{*Calc Trail*} window.
31777
31778@findex calc-set-command-flag
31779You can call, for example, @code{(calc-set-command-flag 'no-align)} to
31780set the above-mentioned command flags. Calc routines recognize the
31781following command flags:
31782
31783@table @code
31784@item renum-stack
31785Stack line numbers @samp{1:}, @samp{2:}, and so on must be renumbered
31786after this command completes. This is set by routines like
31787@code{calc-push}.
31788
31789@item clear-message
31790Calc should call @samp{(message "")} if this command completes normally
31791(to clear a ``Working@dots{}'' message out of the echo area).
31792
31793@item no-align
31794Do not move the cursor back to the @samp{.} top-of-stack marker.
31795
31796@item position-point
31797Use the variables @code{calc-position-point-line} and
31798@code{calc-position-point-column} to position the cursor after
31799this command finishes.
31800
31801@item keep-flags
31802Do not clear @code{calc-inverse-flag}, @code{calc-hyperbolic-flag},
31803and @code{calc-keep-args-flag} at the end of this command.
31804
31805@item do-edit
31806Switch to buffer @samp{*Calc Edit*} after this command.
31807
31808@item hold-trail
31809Do not move trail pointer to end of trail when something is recorded
31810there.
31811@end table
31812
31813@kindex Y
31814@kindex Y ?
31815@vindex calc-Y-help-msgs
31816Calc reserves a special prefix key, shift-@kbd{Y}, for user-written
31817extensions to Calc. There are no built-in commands that work with
31818this prefix key; you must call @code{define-key} from Lisp (probably
31819from inside a @code{calc-define} property) to add to it. Initially only
31820@kbd{Y ?} is defined; it takes help messages from a list of strings
31821(initially @code{nil}) in the variable @code{calc-Y-help-msgs}. All
31822other undefined keys except for @kbd{Y} are reserved for use by
31823future versions of Calc.
31824
31825If you are writing a Calc enhancement which you expect to give to
31826others, it is best to minimize the number of @kbd{Y}-key sequences
31827you use. In fact, if you have more than one key sequence you should
31828consider defining three-key sequences with a @kbd{Y}, then a key that
31829stands for your package, then a third key for the particular command
31830within your package.
31831
31832Users may wish to install several Calc enhancements, and it is possible
31833that several enhancements will choose to use the same key. In the
31834example below, a variable @code{inc-prec-base-key} has been defined
31835to contain the key that identifies the @code{inc-prec} package. Its
31836value is initially @code{"P"}, but a user can change this variable
31837if necessary without having to modify the file.
31838
31839Here is a complete file, @file{inc-prec.el}, which makes a @kbd{Y P I}
31840command that increases the precision, and a @kbd{Y P D} command that
31841decreases the precision.
31842
31843@smallexample
31844;;; Increase and decrease Calc precision. Dave Gillespie, 5/31/91.
31845;; (Include copyright or copyleft stuff here.)
31846
31847(defvar inc-prec-base-key "P"
31848 "Base key for inc-prec.el commands.")
31849
31850(put 'calc-define 'inc-prec '(progn
31851
31852(define-key calc-mode-map (format "Y%sI" inc-prec-base-key)
31853 'increase-precision)
31854(define-key calc-mode-map (format "Y%sD" inc-prec-base-key)
31855 'decrease-precision)
31856
31857(setq calc-Y-help-msgs
31858 (cons (format "%s + Inc-prec, Dec-prec" inc-prec-base-key)
31859 calc-Y-help-msgs))
31860
31861(defmath increase-precision (delta)
31862 "Increase precision by DELTA."
31863 (interactive "p")
31864 (setq calc-internal-prec (+ calc-internal-prec delta)))
31865
31866(defmath decrease-precision (delta)
31867 "Decrease precision by DELTA."
31868 (interactive "p")
31869 (setq calc-internal-prec (- calc-internal-prec delta)))
31870
31871)) ; end of calc-define property
31872
31873(run-hooks 'calc-check-defines)
31874@end smallexample
31875
31876@node Defining Stack Commands, Argument Qualifiers, Defining Simple Commands, Lisp Definitions
31877@subsection Defining New Stack-Based Commands
31878
31879@noindent
31880To define a new computational command which takes and/or leaves arguments
31881on the stack, a special form of @code{interactive} clause is used.
31882
31883@example
31884(interactive @var{num} @var{tag})
31885@end example
31886
31887@noindent
31888where @var{num} is an integer, and @var{tag} is a string. The effect is
31889to pop @var{num} values off the stack, resimplify them by calling
31890@code{calc-normalize}, and hand them to your function according to the
31891function's argument list. Your function may include @code{&optional} and
31892@code{&rest} parameters, so long as calling the function with @var{num}
31893parameters is valid.
31894
31895Your function must return either a number or a formula in a form
31896acceptable to Calc, or a list of such numbers or formulas. These value(s)
31897are pushed onto the stack when the function completes. They are also
31898recorded in the Calc Trail buffer on a line beginning with @var{tag},
31899a string of (normally) four characters or less. If you omit @var{tag}
31900or use @code{nil} as a tag, the result is not recorded in the trail.
31901
31902As an example, the definition
31903
31904@smallexample
31905(defmath myfact (n)
31906 "Compute the factorial of the integer at the top of the stack."
31907 (interactive 1 "fact")
31908 (if (> n 0)
31909 (* n (myfact (1- n)))
31910 (and (= n 0) 1)))
31911@end smallexample
31912
31913@noindent
31914is a version of the factorial function shown previously which can be used
31915as a command as well as an algebraic function. It expands to
31916
31917@smallexample
31918(defun calc-myfact ()
31919 "Compute the factorial of the integer at the top of the stack."
31920 (interactive)
31921 (calc-slow-wrapper
31922 (calc-enter-result 1 "fact"
31923 (cons 'calcFunc-myfact (calc-top-list-n 1)))))
31924
31925(defun calcFunc-myfact (n)
31926 "Compute the factorial of the integer at the top of the stack."
31927 (if (math-posp n)
31928 (math-mul n (calcFunc-myfact (math-add n -1)))
31929 (and (math-zerop n) 1)))
31930@end smallexample
31931
31932@findex calc-slow-wrapper
31933The @code{calc-slow-wrapper} function is a version of @code{calc-wrapper}
31934that automatically puts up a @samp{Working...} message before the
31935computation begins. (This message can be turned off by the user
31936with an @kbd{m w} (@code{calc-working}) command.)
31937
31938@findex calc-top-list-n
31939The @code{calc-top-list-n} function returns a list of the specified number
31940of values from the top of the stack. It resimplifies each value by
31941calling @code{calc-normalize}. If its argument is zero it returns an
31942empty list. It does not actually remove these values from the stack.
31943
31944@findex calc-enter-result
31945The @code{calc-enter-result} function takes an integer @var{num} and string
31946@var{tag} as described above, plus a third argument which is either a
31947Calculator data object or a list of such objects. These objects are
31948resimplified and pushed onto the stack after popping the specified number
31949of values from the stack. If @var{tag} is non-@code{nil}, the values
31950being pushed are also recorded in the trail.
31951
31952Note that if @code{calcFunc-myfact} returns @code{nil} this represents
31953``leave the function in symbolic form.'' To return an actual empty list,
31954in the sense that @code{calc-enter-result} will push zero elements back
31955onto the stack, you should return the special value @samp{'(nil)}, a list
31956containing the single symbol @code{nil}.
31957
31958The @code{interactive} declaration can actually contain a limited
31959Emacs-style code string as well which comes just before @var{num} and
31960@var{tag}. Currently the only Emacs code supported is @samp{"p"}, as in
31961
31962@example
31963(defmath foo (a b &optional c)
31964 (interactive "p" 2 "foo")
31965 @var{body})
31966@end example
31967
31968In this example, the command @code{calc-foo} will evaluate the expression
31969@samp{foo(a,b)} if executed with no argument, or @samp{foo(a,b,n)} if
31970executed with a numeric prefix argument of @expr{n}.
31971
31972The other code string allowed is @samp{"m"} (unrelated to the usual @samp{"m"}
31973code as used with @code{defun}). It uses the numeric prefix argument as the
31974number of objects to remove from the stack and pass to the function.
31975In this case, the integer @var{num} serves as a default number of
31976arguments to be used when no prefix is supplied.
31977
31978@node Argument Qualifiers, Example Definitions, Defining Stack Commands, Lisp Definitions
31979@subsection Argument Qualifiers
31980
31981@noindent
31982Anywhere a parameter name can appear in the parameter list you can also use
31983an @dfn{argument qualifier}. Thus the general form of a definition is:
31984
31985@example
31986(defmath @var{name} (@var{param} @var{param...}
31987 &optional @var{param} @var{param...}
31988 &rest @var{param})
31989 @var{body})
31990@end example
31991
31992@noindent
31993where each @var{param} is either a symbol or a list of the form
31994
31995@example
31996(@var{qual} @var{param})
31997@end example
31998
31999The following qualifiers are recognized:
32000
32001@table @samp
32002@item complete
32003@findex complete
32004The argument must not be an incomplete vector, interval, or complex number.
32005(This is rarely needed since the Calculator itself will never call your
32006function with an incomplete argument. But there is nothing stopping your
32007own Lisp code from calling your function with an incomplete argument.)
32008
32009@item integer
32010@findex integer
32011The argument must be an integer. If it is an integer-valued float
32012it will be accepted but converted to integer form. Non-integers and
32013formulas are rejected.
32014
32015@item natnum
32016@findex natnum
32017Like @samp{integer}, but the argument must be non-negative.
32018
32019@item fixnum
32020@findex fixnum
32021Like @samp{integer}, but the argument must fit into a native Lisp integer,
32022which on most systems means less than 2^23 in absolute value. The
32023argument is converted into Lisp-integer form if necessary.
32024
32025@item float
32026@findex float
32027The argument is converted to floating-point format if it is a number or
32028vector. If it is a formula it is left alone. (The argument is never
32029actually rejected by this qualifier.)
32030
32031@item @var{pred}
32032The argument must satisfy predicate @var{pred}, which is one of the
32033standard Calculator predicates. @xref{Predicates}.
32034
32035@item not-@var{pred}
32036The argument must @emph{not} satisfy predicate @var{pred}.
32037@end table
32038
32039For example,
32040
32041@example
32042(defmath foo (a (constp (not-matrixp b)) &optional (float c)
32043 &rest (integer d))
32044 @var{body})
32045@end example
32046
32047@noindent
32048expands to
32049
32050@example
32051(defun calcFunc-foo (a b &optional c &rest d)
32052 (and (math-matrixp b)
32053 (math-reject-arg b 'not-matrixp))
32054 (or (math-constp b)
32055 (math-reject-arg b 'constp))
32056 (and c (setq c (math-check-float c)))
32057 (setq d (mapcar 'math-check-integer d))
32058 @var{body})
32059@end example
32060
32061@noindent
32062which performs the necessary checks and conversions before executing the
32063body of the function.
32064
32065@node Example Definitions, Calling Calc from Your Programs, Argument Qualifiers, Lisp Definitions
32066@subsection Example Definitions
32067
32068@noindent
32069This section includes some Lisp programming examples on a larger scale.
32070These programs make use of some of the Calculator's internal functions;
32071@pxref{Internals}.
32072
32073@menu
32074* Bit Counting Example::
32075* Sine Example::
32076@end menu
32077
32078@node Bit Counting Example, Sine Example, Example Definitions, Example Definitions
32079@subsubsection Bit-Counting
32080
32081@noindent
32082@ignore
32083@starindex
32084@end ignore
32085@tindex bcount
32086Calc does not include a built-in function for counting the number of
32087``one'' bits in a binary integer. It's easy to invent one using @kbd{b u}
32088to convert the integer to a set, and @kbd{V #} to count the elements of
32089that set; let's write a function that counts the bits without having to
32090create an intermediate set.
32091
32092@smallexample
32093(defmath bcount ((natnum n))
32094 (interactive 1 "bcnt")
32095 (let ((count 0))
32096 (while (> n 0)
32097 (if (oddp n)
32098 (setq count (1+ count)))
32099 (setq n (lsh n -1)))
32100 count))
32101@end smallexample
32102
32103@noindent
32104When this is expanded by @code{defmath}, it will become the following
32105Emacs Lisp function:
32106
32107@smallexample
32108(defun calcFunc-bcount (n)
32109 (setq n (math-check-natnum n))
32110 (let ((count 0))
32111 (while (math-posp n)
32112 (if (math-oddp n)
32113 (setq count (math-add count 1)))
32114 (setq n (calcFunc-lsh n -1)))
32115 count))
32116@end smallexample
32117
32118If the input numbers are large, this function involves a fair amount
32119of arithmetic. A binary right shift is essentially a division by two;
32120recall that Calc stores integers in decimal form so bit shifts must
32121involve actual division.
32122
32123To gain a bit more efficiency, we could divide the integer into
32124@var{n}-bit chunks, each of which can be handled quickly because
32125they fit into Lisp integers. It turns out that Calc's arithmetic
32126routines are especially fast when dividing by an integer less than
321271000, so we can set @var{n = 9} bits and use repeated division by 512:
32128
32129@smallexample
32130(defmath bcount ((natnum n))
32131 (interactive 1 "bcnt")
32132 (let ((count 0))
32133 (while (not (fixnump n))
32134 (let ((qr (idivmod n 512)))
32135 (setq count (+ count (bcount-fixnum (cdr qr)))
32136 n (car qr))))
32137 (+ count (bcount-fixnum n))))
32138
32139(defun bcount-fixnum (n)
32140 (let ((count 0))
32141 (while (> n 0)
32142 (setq count (+ count (logand n 1))
32143 n (lsh n -1)))
32144 count))
32145@end smallexample
32146
32147@noindent
32148Note that the second function uses @code{defun}, not @code{defmath}.
32149Because this function deals only with native Lisp integers (``fixnums''),
32150it can use the actual Emacs @code{+} and related functions rather
32151than the slower but more general Calc equivalents which @code{defmath}
32152uses.
32153
32154The @code{idivmod} function does an integer division, returning both
32155the quotient and the remainder at once. Again, note that while it
32156might seem that @samp{(logand n 511)} and @samp{(lsh n -9)} are
32157more efficient ways to split off the bottom nine bits of @code{n},
32158actually they are less efficient because each operation is really
32159a division by 512 in disguise; @code{idivmod} allows us to do the
32160same thing with a single division by 512.
32161
32162@node Sine Example, , Bit Counting Example, Example Definitions
32163@subsubsection The Sine Function
32164
32165@noindent
32166@ignore
32167@starindex
32168@end ignore
32169@tindex mysin
32170A somewhat limited sine function could be defined as follows, using the
32171well-known Taylor series expansion for
32172@texline @math{\sin x}:
32173@infoline @samp{sin(x)}:
32174
32175@smallexample
32176(defmath mysin ((float (anglep x)))
32177 (interactive 1 "mysn")
32178 (setq x (to-radians x)) ; Convert from current angular mode.
32179 (let ((sum x) ; Initial term of Taylor expansion of sin.
32180 newsum
32181 (nfact 1) ; "nfact" equals "n" factorial at all times.
32182 (xnegsqr :"-(x^2)")) ; "xnegsqr" equals -x^2.
32183 (for ((n 3 100 2)) ; Upper limit of 100 is a good precaution.
32184 (working "mysin" sum) ; Display "Working" message, if enabled.
32185 (setq nfact (* nfact (1- n) n)
32186 x (* x xnegsqr)
32187 newsum (+ sum (/ x nfact)))
32188 (if (~= newsum sum) ; If newsum is "nearly equal to" sum,
32189 (break)) ; then we are done.
32190 (setq sum newsum))
32191 sum))
32192@end smallexample
32193
32194The actual @code{sin} function in Calc works by first reducing the problem
32195to a sine or cosine of a nonnegative number less than @cpiover{4}. This
32196ensures that the Taylor series will converge quickly. Also, the calculation
32197is carried out with two extra digits of precision to guard against cumulative
32198round-off in @samp{sum}. Finally, complex arguments are allowed and handled
32199by a separate algorithm.
32200
32201@smallexample
32202(defmath mysin ((float (scalarp x)))
32203 (interactive 1 "mysn")
32204 (setq x (to-radians x)) ; Convert from current angular mode.
32205 (with-extra-prec 2 ; Evaluate with extra precision.
32206 (cond ((complexp x)
32207 (mysin-complex x))
32208 ((< x 0)
32209 (- (mysin-raw (- x))) ; Always call mysin-raw with x >= 0.
32210 (t (mysin-raw x))))))
32211
32212(defmath mysin-raw (x)
32213 (cond ((>= x 7)
32214 (mysin-raw (% x (two-pi)))) ; Now x < 7.
32215 ((> x (pi-over-2))
32216 (- (mysin-raw (- x (pi))))) ; Now -pi/2 <= x <= pi/2.
32217 ((> x (pi-over-4))
32218 (mycos-raw (- x (pi-over-2)))) ; Now -pi/2 <= x <= pi/4.
32219 ((< x (- (pi-over-4)))
32220 (- (mycos-raw (+ x (pi-over-2))))) ; Now -pi/4 <= x <= pi/4,
32221 (t (mysin-series x)))) ; so the series will be efficient.
32222@end smallexample
32223
32224@noindent
32225where @code{mysin-complex} is an appropriate function to handle complex
32226numbers, @code{mysin-series} is the routine to compute the sine Taylor
32227series as before, and @code{mycos-raw} is a function analogous to
32228@code{mysin-raw} for cosines.
32229
32230The strategy is to ensure that @expr{x} is nonnegative before calling
32231@code{mysin-raw}. This function then recursively reduces its argument
32232to a suitable range, namely, plus-or-minus @cpiover{4}. Note that each
32233test, and particularly the first comparison against 7, is designed so
32234that small roundoff errors cannot produce an infinite loop. (Suppose
32235we compared with @samp{(two-pi)} instead; if due to roundoff problems
32236the modulo operator ever returned @samp{(two-pi)} exactly, an infinite
32237recursion could result!) We use modulo only for arguments that will
32238clearly get reduced, knowing that the next rule will catch any reductions
32239that this rule misses.
32240
32241If a program is being written for general use, it is important to code
32242it carefully as shown in this second example. For quick-and-dirty programs,
32243when you know that your own use of the sine function will never encounter
32244a large argument, a simpler program like the first one shown is fine.
32245
32246@node Calling Calc from Your Programs, Internals, Example Definitions, Lisp Definitions
32247@subsection Calling Calc from Your Lisp Programs
32248
32249@noindent
32250A later section (@pxref{Internals}) gives a full description of
32251Calc's internal Lisp functions. It's not hard to call Calc from
32252inside your programs, but the number of these functions can be daunting.
32253So Calc provides one special ``programmer-friendly'' function called
32254@code{calc-eval} that can be made to do just about everything you
32255need. It's not as fast as the low-level Calc functions, but it's
32256much simpler to use!
32257
32258It may seem that @code{calc-eval} itself has a daunting number of
32259options, but they all stem from one simple operation.
32260
32261In its simplest manifestation, @samp{(calc-eval "1+2")} parses the
32262string @code{"1+2"} as if it were a Calc algebraic entry and returns
32263the result formatted as a string: @code{"3"}.
32264
32265Since @code{calc-eval} is on the list of recommended @code{autoload}
32266functions, you don't need to make any special preparations to load
32267Calc before calling @code{calc-eval} the first time. Calc will be
32268loaded and initialized for you.
32269
32270All the Calc modes that are currently in effect will be used when
32271evaluating the expression and formatting the result.
32272
32273@ifinfo
32274@example
32275
32276@end example
32277@end ifinfo
32278@subsubsection Additional Arguments to @code{calc-eval}
32279
32280@noindent
32281If the input string parses to a list of expressions, Calc returns
32282the results separated by @code{", "}. You can specify a different
32283separator by giving a second string argument to @code{calc-eval}:
32284@samp{(calc-eval "1+2,3+4" ";")} returns @code{"3;7"}.
32285
32286The ``separator'' can also be any of several Lisp symbols which
32287request other behaviors from @code{calc-eval}. These are discussed
32288one by one below.
32289
32290You can give additional arguments to be substituted for
32291@samp{$}, @samp{$$}, and so on in the main expression. For
32292example, @samp{(calc-eval "$/$$" nil "7" "1+1")} evaluates the
32293expression @code{"7/(1+1)"} to yield the result @code{"3.5"}
32294(assuming Fraction mode is not in effect). Note the @code{nil}
32295used as a placeholder for the item-separator argument.
32296
32297@ifinfo
32298@example
32299
32300@end example
32301@end ifinfo
32302@subsubsection Error Handling
32303
32304@noindent
32305If @code{calc-eval} encounters an error, it returns a list containing
32306the character position of the error, plus a suitable message as a
32307string. Note that @samp{1 / 0} is @emph{not} an error by Calc's
32308standards; it simply returns the string @code{"1 / 0"} which is the
32309division left in symbolic form. But @samp{(calc-eval "1/")} will
32310return the list @samp{(2 "Expected a number")}.
32311
32312If you bind the variable @code{calc-eval-error} to @code{t}
32313using a @code{let} form surrounding the call to @code{calc-eval},
32314errors instead call the Emacs @code{error} function which aborts
32315to the Emacs command loop with a beep and an error message.
32316
32317If you bind this variable to the symbol @code{string}, error messages
32318are returned as strings instead of lists. The character position is
32319ignored.
32320
32321As a courtesy to other Lisp code which may be using Calc, be sure
32322to bind @code{calc-eval-error} using @code{let} rather than changing
32323it permanently with @code{setq}.
32324
32325@ifinfo
32326@example
32327
32328@end example
32329@end ifinfo
32330@subsubsection Numbers Only
32331
32332@noindent
32333Sometimes it is preferable to treat @samp{1 / 0} as an error
32334rather than returning a symbolic result. If you pass the symbol
32335@code{num} as the second argument to @code{calc-eval}, results
32336that are not constants are treated as errors. The error message
32337reported is the first @code{calc-why} message if there is one,
32338or otherwise ``Number expected.''
32339
32340A result is ``constant'' if it is a number, vector, or other
32341object that does not include variables or function calls. If it
32342is a vector, the components must themselves be constants.
32343
32344@ifinfo
32345@example
32346
32347@end example
32348@end ifinfo
32349@subsubsection Default Modes
32350
32351@noindent
32352If the first argument to @code{calc-eval} is a list whose first
32353element is a formula string, then @code{calc-eval} sets all the
32354various Calc modes to their default values while the formula is
32355evaluated and formatted. For example, the precision is set to 12
32356digits, digit grouping is turned off, and the Normal language
32357mode is used.
32358
32359This same principle applies to the other options discussed below.
32360If the first argument would normally be @var{x}, then it can also
32361be the list @samp{(@var{x})} to use the default mode settings.
32362
32363If there are other elements in the list, they are taken as
32364variable-name/value pairs which override the default mode
32365settings. Look at the documentation at the front of the
32366@file{calc.el} file to find the names of the Lisp variables for
32367the various modes. The mode settings are restored to their
32368original values when @code{calc-eval} is done.
32369
32370For example, @samp{(calc-eval '("$+$$" calc-internal-prec 8) 'num a b)}
32371computes the sum of two numbers, requiring a numeric result, and
32372using default mode settings except that the precision is 8 instead
32373of the default of 12.
32374
32375It's usually best to use this form of @code{calc-eval} unless your
32376program actually considers the interaction with Calc's mode settings
32377to be a feature. This will avoid all sorts of potential ``gotchas'';
32378consider what happens with @samp{(calc-eval "sqrt(2)" 'num)}
32379when the user has left Calc in Symbolic mode or No-Simplify mode.
32380
32381As another example, @samp{(equal (calc-eval '("$<$$") nil a b) "1")}
32382checks if the number in string @expr{a} is less than the one in
32383string @expr{b}. Without using a list, the integer 1 might
32384come out in a variety of formats which would be hard to test for
32385conveniently: @code{"1"}, @code{"8#1"}, @code{"00001"}. (But
32386see ``Predicates'' mode, below.)
32387
32388@ifinfo
32389@example
32390
32391@end example
32392@end ifinfo
32393@subsubsection Raw Numbers
32394
32395@noindent
32396Normally all input and output for @code{calc-eval} is done with strings.
32397You can do arithmetic with, say, @samp{(calc-eval "$+$$" nil a b)}
32398in place of @samp{(+ a b)}, but this is very inefficient since the
32399numbers must be converted to and from string format as they are passed
32400from one @code{calc-eval} to the next.
32401
32402If the separator is the symbol @code{raw}, the result will be returned
32403as a raw Calc data structure rather than a string. You can read about
32404how these objects look in the following sections, but usually you can
32405treat them as ``black box'' objects with no important internal
32406structure.
32407
32408There is also a @code{rawnum} symbol, which is a combination of
32409@code{raw} (returning a raw Calc object) and @code{num} (signaling
32410an error if that object is not a constant).
32411
32412You can pass a raw Calc object to @code{calc-eval} in place of a
32413string, either as the formula itself or as one of the @samp{$}
32414arguments. Thus @samp{(calc-eval "$+$$" 'raw a b)} is an
32415addition function that operates on raw Calc objects. Of course
32416in this case it would be easier to call the low-level @code{math-add}
32417function in Calc, if you can remember its name.
32418
32419In particular, note that a plain Lisp integer is acceptable to Calc
32420as a raw object. (All Lisp integers are accepted on input, but
32421integers of more than six decimal digits are converted to ``big-integer''
32422form for output. @xref{Data Type Formats}.)
32423
32424When it comes time to display the object, just use @samp{(calc-eval a)}
32425to format it as a string.
32426
32427It is an error if the input expression evaluates to a list of
32428values. The separator symbol @code{list} is like @code{raw}
32429except that it returns a list of one or more raw Calc objects.
32430
32431Note that a Lisp string is not a valid Calc object, nor is a list
32432containing a string. Thus you can still safely distinguish all the
32433various kinds of error returns discussed above.
32434
32435@ifinfo
32436@example
32437
32438@end example
32439@end ifinfo
32440@subsubsection Predicates
32441
32442@noindent
32443If the separator symbol is @code{pred}, the result of the formula is
32444treated as a true/false value; @code{calc-eval} returns @code{t} or
32445@code{nil}, respectively. A value is considered ``true'' if it is a
32446non-zero number, or false if it is zero or if it is not a number.
32447
32448For example, @samp{(calc-eval "$<$$" 'pred a b)} tests whether
32449one value is less than another.
32450
32451As usual, it is also possible for @code{calc-eval} to return one of
32452the error indicators described above. Lisp will interpret such an
32453indicator as ``true'' if you don't check for it explicitly. If you
32454wish to have an error register as ``false'', use something like
32455@samp{(eq (calc-eval ...) t)}.
32456
32457@ifinfo
32458@example
32459
32460@end example
32461@end ifinfo
32462@subsubsection Variable Values
32463
32464@noindent
32465Variables in the formula passed to @code{calc-eval} are not normally
32466replaced by their values. If you wish this, you can use the
32467@code{evalv} function (@pxref{Algebraic Manipulation}). For example,
32468if 4 is stored in Calc variable @code{a} (i.e., in Lisp variable
32469@code{var-a}), then @samp{(calc-eval "a+pi")} will return the
32470formula @code{"a + pi"}, but @samp{(calc-eval "evalv(a+pi)")}
32471will return @code{"7.14159265359"}.
32472
32473To store in a Calc variable, just use @code{setq} to store in the
32474corresponding Lisp variable. (This is obtained by prepending
32475@samp{var-} to the Calc variable name.) Calc routines will
32476understand either string or raw form values stored in variables,
32477although raw data objects are much more efficient. For example,
32478to increment the Calc variable @code{a}:
32479
32480@example
32481(setq var-a (calc-eval "evalv(a+1)" 'raw))
32482@end example
32483
32484@ifinfo
32485@example
32486
32487@end example
32488@end ifinfo
32489@subsubsection Stack Access
32490
32491@noindent
32492If the separator symbol is @code{push}, the formula argument is
32493evaluated (with possible @samp{$} expansions, as usual). The
32494result is pushed onto the Calc stack. The return value is @code{nil}
32495(unless there is an error from evaluating the formula, in which
32496case the return value depends on @code{calc-eval-error} in the
32497usual way).
32498
32499If the separator symbol is @code{pop}, the first argument to
32500@code{calc-eval} must be an integer instead of a string. That
32501many values are popped from the stack and thrown away. A negative
32502argument deletes the entry at that stack level. The return value
32503is the number of elements remaining in the stack after popping;
32504@samp{(calc-eval 0 'pop)} is a good way to measure the size of
32505the stack.
32506
32507If the separator symbol is @code{top}, the first argument to
32508@code{calc-eval} must again be an integer. The value at that
32509stack level is formatted as a string and returned. Thus
32510@samp{(calc-eval 1 'top)} returns the top-of-stack value. If the
32511integer is out of range, @code{nil} is returned.
32512
32513The separator symbol @code{rawtop} is just like @code{top} except
32514that the stack entry is returned as a raw Calc object instead of
32515as a string.
32516
32517In all of these cases the first argument can be made a list in
32518order to force the default mode settings, as described above.
32519Thus @samp{(calc-eval '(2 calc-number-radix 16) 'top)} returns the
32520second-to-top stack entry, formatted as a string using the default
32521instead of current display modes, except that the radix is
32522hexadecimal instead of decimal.
32523
32524It is, of course, polite to put the Calc stack back the way you
32525found it when you are done, unless the user of your program is
32526actually expecting it to affect the stack.
32527
32528Note that you do not actually have to switch into the @samp{*Calculator*}
32529buffer in order to use @code{calc-eval}; it temporarily switches into
32530the stack buffer if necessary.
32531
32532@ifinfo
32533@example
32534
32535@end example
32536@end ifinfo
32537@subsubsection Keyboard Macros
32538
32539@noindent
32540If the separator symbol is @code{macro}, the first argument must be a
32541string of characters which Calc can execute as a sequence of keystrokes.
32542This switches into the Calc buffer for the duration of the macro.
32543For example, @samp{(calc-eval "vx5\rVR+" 'macro)} pushes the
32544vector @samp{[1,2,3,4,5]} on the stack and then replaces it
32545with the sum of those numbers. Note that @samp{\r} is the Lisp
32546notation for the carriage-return, @key{RET}, character.
32547
32548If your keyboard macro wishes to pop the stack, @samp{\C-d} is
32549safer than @samp{\177} (the @key{DEL} character) because some
32550installations may have switched the meanings of @key{DEL} and
32551@kbd{C-h}. Calc always interprets @kbd{C-d} as a synonym for
32552``pop-stack'' regardless of key mapping.
32553
32554If you provide a third argument to @code{calc-eval}, evaluation
32555of the keyboard macro will leave a record in the Trail using
32556that argument as a tag string. Normally the Trail is unaffected.
32557
32558The return value in this case is always @code{nil}.
32559
32560@ifinfo
32561@example
32562
32563@end example
32564@end ifinfo
32565@subsubsection Lisp Evaluation
32566
32567@noindent
32568Finally, if the separator symbol is @code{eval}, then the Lisp
32569@code{eval} function is called on the first argument, which must
32570be a Lisp expression rather than a Calc formula. Remember to
32571quote the expression so that it is not evaluated until inside
32572@code{calc-eval}.
32573
32574The difference from plain @code{eval} is that @code{calc-eval}
32575switches to the Calc buffer before evaluating the expression.
32576For example, @samp{(calc-eval '(setq calc-internal-prec 17) 'eval)}
32577will correctly affect the buffer-local Calc precision variable.
32578
32579An alternative would be @samp{(calc-eval '(calc-precision 17) 'eval)}.
32580This is evaluating a call to the function that is normally invoked
32581by the @kbd{p} key, giving it 17 as its ``numeric prefix argument.''
32582Note that this function will leave a message in the echo area as
32583a side effect. Also, all Calc functions switch to the Calc buffer
32584automatically if not invoked from there, so the above call is
32585also equivalent to @samp{(calc-precision 17)} by itself.
32586In all cases, Calc uses @code{save-excursion} to switch back to
32587your original buffer when it is done.
32588
32589As usual the first argument can be a list that begins with a Lisp
32590expression to use default instead of current mode settings.
32591
32592The result of @code{calc-eval} in this usage is just the result
32593returned by the evaluated Lisp expression.
32594
32595@ifinfo
32596@example
32597
32598@end example
32599@end ifinfo
32600@subsubsection Example
32601
32602@noindent
32603@findex convert-temp
32604Here is a sample Emacs command that uses @code{calc-eval}. Suppose
32605you have a document with lots of references to temperatures on the
32606Fahrenheit scale, say ``98.6 F'', and you wish to convert these
32607references to Centigrade. The following command does this conversion.
32608Place the Emacs cursor right after the letter ``F'' and invoke the
32609command to change ``98.6 F'' to ``37 C''. Or, if the temperature is
32610already in Centigrade form, the command changes it back to Fahrenheit.
32611
32612@example
32613(defun convert-temp ()
32614 (interactive)
32615 (save-excursion
32616 (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
32617 (let* ((top1 (match-beginning 1))
32618 (bot1 (match-end 1))
32619 (number (buffer-substring top1 bot1))
32620 (top2 (match-beginning 2))
32621 (bot2 (match-end 2))
32622 (type (buffer-substring top2 bot2)))
32623 (if (equal type "F")
32624 (setq type "C"
32625 number (calc-eval "($ - 32)*5/9" nil number))
32626 (setq type "F"
32627 number (calc-eval "$*9/5 + 32" nil number)))
32628 (goto-char top2)
32629 (delete-region top2 bot2)
32630 (insert-before-markers type)
32631 (goto-char top1)
32632 (delete-region top1 bot1)
32633 (if (string-match "\\.$" number) ; change "37." to "37"
32634 (setq number (substring number 0 -1)))
32635 (insert number))))
32636@end example
32637
32638Note the use of @code{insert-before-markers} when changing between
32639``F'' and ``C'', so that the character winds up before the cursor
32640instead of after it.
32641
32642@node Internals, , Calling Calc from Your Programs, Lisp Definitions
32643@subsection Calculator Internals
32644
32645@noindent
32646This section describes the Lisp functions defined by the Calculator that
32647may be of use to user-written Calculator programs (as described in the
32648rest of this chapter). These functions are shown by their names as they
32649conventionally appear in @code{defmath}. Their full Lisp names are
32650generally gotten by prepending @samp{calcFunc-} or @samp{math-} to their
32651apparent names. (Names that begin with @samp{calc-} are already in
32652their full Lisp form.) You can use the actual full names instead if you
32653prefer them, or if you are calling these functions from regular Lisp.
32654
32655The functions described here are scattered throughout the various
32656Calc component files. Note that @file{calc.el} includes @code{autoload}s
32657for only a few component files; when Calc wants to call an advanced
32658function it calls @samp{(calc-extensions)} first; this function
32659autoloads @file{calc-ext.el}, which in turn autoloads all the functions
32660in the remaining component files.
32661
32662Because @code{defmath} itself uses the extensions, user-written code
32663generally always executes with the extensions already loaded, so
32664normally you can use any Calc function and be confident that it will
32665be autoloaded for you when necessary. If you are doing something
32666special, check carefully to make sure each function you are using is
32667from @file{calc.el} or its components, and call @samp{(calc-extensions)}
32668before using any function based in @file{calc-ext.el} if you can't
32669prove this file will already be loaded.
32670
32671@menu
32672* Data Type Formats::
32673* Interactive Lisp Functions::
32674* Stack Lisp Functions::
32675* Predicates::
32676* Computational Lisp Functions::
32677* Vector Lisp Functions::
32678* Symbolic Lisp Functions::
32679* Formatting Lisp Functions::
32680* Hooks::
32681@end menu
32682
32683@node Data Type Formats, Interactive Lisp Functions, Internals, Internals
32684@subsubsection Data Type Formats
32685
32686@noindent
32687Integers are stored in either of two ways, depending on their magnitude.
32688Integers less than one million in absolute value are stored as standard
32689Lisp integers. This is the only storage format for Calc data objects
32690which is not a Lisp list.
32691
32692Large integers are stored as lists of the form @samp{(bigpos @var{d0}
32693@var{d1} @var{d2} @dots{})} for positive integers 1000000 or more, or
32694@samp{(bigneg @var{d0} @var{d1} @var{d2} @dots{})} for negative integers
32695@mathit{-1000000} or less. Each @var{d} is a base-1000 ``digit,'' a Lisp integer
32696from 0 to 999. The least significant digit is @var{d0}; the last digit,
32697@var{dn}, which is always nonzero, is the most significant digit. For
32698example, the integer @mathit{-12345678} is stored as @samp{(bigneg 678 345 12)}.
32699
32700The distinction between small and large integers is entirely hidden from
32701the user. In @code{defmath} definitions, the Lisp predicate @code{integerp}
32702returns true for either kind of integer, and in general both big and small
32703integers are accepted anywhere the word ``integer'' is used in this manual.
32704If the distinction must be made, native Lisp integers are called @dfn{fixnums}
32705and large integers are called @dfn{bignums}.
32706
32707Fractions are stored as a list of the form, @samp{(frac @var{n} @var{d})}
32708where @var{n} is an integer (big or small) numerator, @var{d} is an
32709integer denominator greater than one, and @var{n} and @var{d} are relatively
32710prime. Note that fractions where @var{d} is one are automatically converted
32711to plain integers by all math routines; fractions where @var{d} is negative
32712are normalized by negating the numerator and denominator.
32713
32714Floating-point numbers are stored in the form, @samp{(float @var{mant}
32715@var{exp})}, where @var{mant} (the ``mantissa'') is an integer less than
32716@samp{10^@var{p}} in absolute value (@var{p} represents the current
32717precision), and @var{exp} (the ``exponent'') is a fixnum. The value of
32718the float is @samp{@var{mant} * 10^@var{exp}}. For example, the number
32719@mathit{-3.14} is stored as @samp{(float -314 -2) = -314*10^-2}. Other constraints
32720are that the number 0.0 is always stored as @samp{(float 0 0)}, and,
32721except for the 0.0 case, the rightmost base-10 digit of @var{mant} is
32722always nonzero. (If the rightmost digit is zero, the number is
32723rearranged by dividing @var{mant} by ten and incrementing @var{exp}.)
32724
32725Rectangular complex numbers are stored in the form @samp{(cplx @var{re}
32726@var{im})}, where @var{re} and @var{im} are each real numbers, either
32727integers, fractions, or floats. The value is @samp{@var{re} + @var{im}i}.
32728The @var{im} part is nonzero; complex numbers with zero imaginary
32729components are converted to real numbers automatically.
32730
32731Polar complex numbers are stored in the form @samp{(polar @var{r}
32732@var{theta})}, where @var{r} is a positive real value and @var{theta}
32733is a real value or HMS form representing an angle. This angle is
32734usually normalized to lie in the interval @samp{(-180 ..@: 180)} degrees,
32735or @samp{(-pi ..@: pi)} radians, according to the current angular mode.
32736If the angle is 0 the value is converted to a real number automatically.
32737(If the angle is 180 degrees, the value is usually also converted to a
32738negative real number.)
32739
32740Hours-minutes-seconds forms are stored as @samp{(hms @var{h} @var{m}
32741@var{s})}, where @var{h} is an integer or an integer-valued float (i.e.,
32742a float with @samp{@var{exp} >= 0}), @var{m} is an integer or integer-valued
32743float in the range @w{@samp{[0 ..@: 60)}}, and @var{s} is any real number
32744in the range @samp{[0 ..@: 60)}.
32745
32746Date forms are stored as @samp{(date @var{n})}, where @var{n} is
32747a real number that counts days since midnight on the morning of
32748January 1, 1 AD. If @var{n} is an integer, this is a pure date
32749form. If @var{n} is a fraction or float, this is a date/time form.
32750
32751Modulo forms are stored as @samp{(mod @var{n} @var{m})}, where @var{m} is a
32752positive real number or HMS form, and @var{n} is a real number or HMS
32753form in the range @samp{[0 ..@: @var{m})}.
32754
32755Error forms are stored as @samp{(sdev @var{x} @var{sigma})}, where @var{x}
32756is the mean value and @var{sigma} is the standard deviation. Each
32757component is either a number, an HMS form, or a symbolic object
32758(a variable or function call). If @var{sigma} is zero, the value is
32759converted to a plain real number. If @var{sigma} is negative or
32760complex, it is automatically normalized to be a positive real.
32761
32762Interval forms are stored as @samp{(intv @var{mask} @var{lo} @var{hi})},
32763where @var{mask} is one of the integers 0, 1, 2, or 3, and @var{lo} and
32764@var{hi} are real numbers, HMS forms, or symbolic objects. The @var{mask}
32765is a binary integer where 1 represents the fact that the interval is
32766closed on the high end, and 2 represents the fact that it is closed on
32767the low end. (Thus 3 represents a fully closed interval.) The interval
32768@w{@samp{(intv 3 @var{x} @var{x})}} is converted to the plain number @var{x};
32769intervals @samp{(intv @var{mask} @var{x} @var{x})} for any other @var{mask}
32770represent empty intervals. If @var{hi} is less than @var{lo}, the interval
32771is converted to a standard empty interval by replacing @var{hi} with @var{lo}.
32772
32773Vectors are stored as @samp{(vec @var{v1} @var{v2} @dots{})}, where @var{v1}
32774is the first element of the vector, @var{v2} is the second, and so on.
32775An empty vector is stored as @samp{(vec)}. A matrix is simply a vector
32776where all @var{v}'s are themselves vectors of equal lengths. Note that
32777Calc vectors are unrelated to the Emacs Lisp ``vector'' type, which is
32778generally unused by Calc data structures.
32779
32780Variables are stored as @samp{(var @var{name} @var{sym})}, where
32781@var{name} is a Lisp symbol whose print name is used as the visible name
32782of the variable, and @var{sym} is a Lisp symbol in which the variable's
32783value is actually stored. Thus, @samp{(var pi var-pi)} represents the
32784special constant @samp{pi}. Almost always, the form is @samp{(var
32785@var{v} var-@var{v})}. If the variable name was entered with @code{#}
32786signs (which are converted to hyphens internally), the form is
32787@samp{(var @var{u} @var{v})}, where @var{u} is a symbol whose name
32788contains @code{#} characters, and @var{v} is a symbol that contains
32789@code{-} characters instead. The value of a variable is the Calc
32790object stored in its @var{sym} symbol's value cell. If the symbol's
32791value cell is void or if it contains @code{nil}, the variable has no
32792value. Special constants have the form @samp{(special-const
32793@var{value})} stored in their value cell, where @var{value} is a formula
32794which is evaluated when the constant's value is requested. Variables
32795which represent units are not stored in any special way; they are units
32796only because their names appear in the units table. If the value
32797cell contains a string, it is parsed to get the variable's value when
32798the variable is used.
32799
32800A Lisp list with any other symbol as the first element is a function call.
32801The symbols @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^},
32802and @code{|} represent special binary operators; these lists are always
32803of the form @samp{(@var{op} @var{lhs} @var{rhs})} where @var{lhs} is the
32804sub-formula on the lefthand side and @var{rhs} is the sub-formula on the
32805right. The symbol @code{neg} represents unary negation; this list is always
32806of the form @samp{(neg @var{arg})}. Any other symbol @var{func} represents a
32807function that would be displayed in function-call notation; the symbol
32808@var{func} is in general always of the form @samp{calcFunc-@var{name}}.
32809The function cell of the symbol @var{func} should contain a Lisp function
32810for evaluating a call to @var{func}. This function is passed the remaining
32811elements of the list (themselves already evaluated) as arguments; such
32812functions should return @code{nil} or call @code{reject-arg} to signify
32813that they should be left in symbolic form, or they should return a Calc
32814object which represents their value, or a list of such objects if they
32815wish to return multiple values. (The latter case is allowed only for
32816functions which are the outer-level call in an expression whose value is
32817about to be pushed on the stack; this feature is considered obsolete
32818and is not used by any built-in Calc functions.)
32819
32820@node Interactive Lisp Functions, Stack Lisp Functions, Data Type Formats, Internals
32821@subsubsection Interactive Functions
32822
32823@noindent
32824The functions described here are used in implementing interactive Calc
32825commands. Note that this list is not exhaustive! If there is an
32826existing command that behaves similarly to the one you want to define,
32827you may find helpful tricks by checking the source code for that command.
32828
32829@defun calc-set-command-flag flag
32830Set the command flag @var{flag}. This is generally a Lisp symbol, but
32831may in fact be anything. The effect is to add @var{flag} to the list
32832stored in the variable @code{calc-command-flags}, unless it is already
32833there. @xref{Defining Simple Commands}.
32834@end defun
32835
32836@defun calc-clear-command-flag flag
32837If @var{flag} appears among the list of currently-set command flags,
32838remove it from that list.
32839@end defun
32840
32841@defun calc-record-undo rec
32842Add the ``undo record'' @var{rec} to the list of steps to take if the
32843current operation should need to be undone. Stack push and pop functions
32844automatically call @code{calc-record-undo}, so the kinds of undo records
32845you might need to create take the form @samp{(set @var{sym} @var{value})},
32846which says that the Lisp variable @var{sym} was changed and had previously
32847contained @var{value}; @samp{(store @var{var} @var{value})} which says that
32848the Calc variable @var{var} (a string which is the name of the symbol that
32849contains the variable's value) was stored and its previous value was
32850@var{value} (either a Calc data object, or @code{nil} if the variable was
32851previously void); or @samp{(eval @var{undo} @var{redo} @var{args} @dots{})},
32852which means that to undo requires calling the function @samp{(@var{undo}
32853@var{args} @dots{})} and, if the undo is later redone, calling
32854@samp{(@var{redo} @var{args} @dots{})}.
32855@end defun
32856
32857@defun calc-record-why msg args
32858Record the error or warning message @var{msg}, which is normally a string.
32859This message will be replayed if the user types @kbd{w} (@code{calc-why});
32860if the message string begins with a @samp{*}, it is considered important
32861enough to display even if the user doesn't type @kbd{w}. If one or more
32862@var{args} are present, the displayed message will be of the form,
32863@samp{@var{msg}: @var{arg1}, @var{arg2}, @dots{}}, where the arguments are
32864formatted on the assumption that they are either strings or Calc objects of
32865some sort. If @var{msg} is a symbol, it is the name of a Calc predicate
32866(such as @code{integerp} or @code{numvecp}) which the arguments did not
32867satisfy; it is expanded to a suitable string such as ``Expected an
32868integer.'' The @code{reject-arg} function calls @code{calc-record-why}
32869automatically; @pxref{Predicates}.
32870@end defun
32871
32872@defun calc-is-inverse
32873This predicate returns true if the current command is inverse,
32874i.e., if the Inverse (@kbd{I} key) flag was set.
32875@end defun
32876
32877@defun calc-is-hyperbolic
32878This predicate is the analogous function for the @kbd{H} key.
32879@end defun
32880
32881@node Stack Lisp Functions, Predicates, Interactive Lisp Functions, Internals
32882@subsubsection Stack-Oriented Functions
32883
32884@noindent
32885The functions described here perform various operations on the Calc
32886stack and trail. They are to be used in interactive Calc commands.
32887
32888@defun calc-push-list vals n
32889Push the Calc objects in list @var{vals} onto the stack at stack level
32890@var{n}. If @var{n} is omitted it defaults to 1, so that the elements
32891are pushed at the top of the stack. If @var{n} is greater than 1, the
32892elements will be inserted into the stack so that the last element will
32893end up at level @var{n}, the next-to-last at level @var{n}+1, etc.
32894The elements of @var{vals} are assumed to be valid Calc objects, and
32895are not evaluated, rounded, or renormalized in any way. If @var{vals}
32896is an empty list, nothing happens.
32897
32898The stack elements are pushed without any sub-formula selections.
32899You can give an optional third argument to this function, which must
32900be a list the same size as @var{vals} of selections. Each selection
32901must be @code{eq} to some sub-formula of the corresponding formula
32902in @var{vals}, or @code{nil} if that formula should have no selection.
32903@end defun
32904
32905@defun calc-top-list n m
32906Return a list of the @var{n} objects starting at level @var{m} of the
32907stack. If @var{m} is omitted it defaults to 1, so that the elements are
32908taken from the top of the stack. If @var{n} is omitted, it also
32909defaults to 1, so that the top stack element (in the form of a
32910one-element list) is returned. If @var{m} is greater than 1, the
32911@var{m}th stack element will be at the end of the list, the @var{m}+1st
32912element will be next-to-last, etc. If @var{n} or @var{m} are out of
32913range, the command is aborted with a suitable error message. If @var{n}
32914is zero, the function returns an empty list. The stack elements are not
32915evaluated, rounded, or renormalized.
32916
32917If any stack elements contain selections, and selections have not
32918been disabled by the @kbd{j e} (@code{calc-enable-selections}) command,
32919this function returns the selected portions rather than the entire
32920stack elements. It can be given a third ``selection-mode'' argument
32921which selects other behaviors. If it is the symbol @code{t}, then
32922a selection in any of the requested stack elements produces an
32923``invalid operation on selections'' error. If it is the symbol @code{full},
32924the whole stack entry is always returned regardless of selections.
32925If it is the symbol @code{sel}, the selected portion is always returned,
32926or @code{nil} if there is no selection. (This mode ignores the @kbd{j e}
32927command.) If the symbol is @code{entry}, the complete stack entry in
32928list form is returned; the first element of this list will be the whole
32929formula, and the third element will be the selection (or @code{nil}).
32930@end defun
32931
32932@defun calc-pop-stack n m
32933Remove the specified elements from the stack. The parameters @var{n}
32934and @var{m} are defined the same as for @code{calc-top-list}. The return
32935value of @code{calc-pop-stack} is uninteresting.
32936
32937If there are any selected sub-formulas among the popped elements, and
32938@kbd{j e} has not been used to disable selections, this produces an
32939error without changing the stack. If you supply an optional third
32940argument of @code{t}, the stack elements are popped even if they
32941contain selections.
32942@end defun
32943
32944@defun calc-record-list vals tag
32945This function records one or more results in the trail. The @var{vals}
32946are a list of strings or Calc objects. The @var{tag} is the four-character
32947tag string to identify the values. If @var{tag} is omitted, a blank tag
32948will be used.
32949@end defun
32950
32951@defun calc-normalize n
32952This function takes a Calc object and ``normalizes'' it. At the very
32953least this involves re-rounding floating-point values according to the
32954current precision and other similar jobs. Also, unless the user has
32955selected No-Simplify mode (@pxref{Simplification Modes}), this involves
32956actually evaluating a formula object by executing the function calls
32957it contains, and possibly also doing algebraic simplification, etc.
32958@end defun
32959
32960@defun calc-top-list-n n m
32961This function is identical to @code{calc-top-list}, except that it calls
32962@code{calc-normalize} on the values that it takes from the stack. They
32963are also passed through @code{check-complete}, so that incomplete
32964objects will be rejected with an error message. All computational
32965commands should use this in preference to @code{calc-top-list}; the only
32966standard Calc commands that operate on the stack without normalizing
32967are stack management commands like @code{calc-enter} and @code{calc-roll-up}.
32968This function accepts the same optional selection-mode argument as
32969@code{calc-top-list}.
32970@end defun
32971
32972@defun calc-top-n m
32973This function is a convenient form of @code{calc-top-list-n} in which only
32974a single element of the stack is taken and returned, rather than a list
32975of elements. This also accepts an optional selection-mode argument.
32976@end defun
32977
32978@defun calc-enter-result n tag vals
32979This function is a convenient interface to most of the above functions.
32980The @var{vals} argument should be either a single Calc object, or a list
32981of Calc objects; the object or objects are normalized, and the top @var{n}
32982stack entries are replaced by the normalized objects. If @var{tag} is
32983non-@code{nil}, the normalized objects are also recorded in the trail.
32984A typical stack-based computational command would take the form,
32985
32986@smallexample
32987(calc-enter-result @var{n} @var{tag} (cons 'calcFunc-@var{func}
32988 (calc-top-list-n @var{n})))
32989@end smallexample
32990
32991If any of the @var{n} stack elements replaced contain sub-formula
32992selections, and selections have not been disabled by @kbd{j e},
32993this function takes one of two courses of action. If @var{n} is
32994equal to the number of elements in @var{vals}, then each element of
32995@var{vals} is spliced into the corresponding selection; this is what
32996happens when you use the @key{TAB} key, or when you use a unary
32997arithmetic operation like @code{sqrt}. If @var{vals} has only one
32998element but @var{n} is greater than one, there must be only one
32999selection among the top @var{n} stack elements; the element from
33000@var{vals} is spliced into that selection. This is what happens when
33001you use a binary arithmetic operation like @kbd{+}. Any other
33002combination of @var{n} and @var{vals} is an error when selections
33003are present.
33004@end defun
33005
33006@defun calc-unary-op tag func arg
33007This function implements a unary operator that allows a numeric prefix
33008argument to apply the operator over many stack entries. If the prefix
33009argument @var{arg} is @code{nil}, this uses @code{calc-enter-result}
33010as outlined above. Otherwise, it maps the function over several stack
33011elements; @pxref{Prefix Arguments}. For example,
33012
33013@smallexample
33014(defun calc-zeta (arg)
33015 (interactive "P")
33016 (calc-unary-op "zeta" 'calcFunc-zeta arg))
33017@end smallexample
33018@end defun
33019
33020@defun calc-binary-op tag func arg ident unary
33021This function implements a binary operator, analogously to
33022@code{calc-unary-op}. The optional @var{ident} and @var{unary}
33023arguments specify the behavior when the prefix argument is zero or
33024one, respectively. If the prefix is zero, the value @var{ident}
33025is pushed onto the stack, if specified, otherwise an error message
33026is displayed. If the prefix is one, the unary function @var{unary}
33027is applied to the top stack element, or, if @var{unary} is not
33028specified, nothing happens. When the argument is two or more,
33029the binary function @var{func} is reduced across the top @var{arg}
33030stack elements; when the argument is negative, the function is
33031mapped between the next-to-top @mathit{-@var{arg}} stack elements and the
33032top element.
33033@end defun
33034
33035@defun calc-stack-size
33036Return the number of elements on the stack as an integer. This count
33037does not include elements that have been temporarily hidden by stack
33038truncation; @pxref{Truncating the Stack}.
33039@end defun
33040
33041@defun calc-cursor-stack-index n
33042Move the point to the @var{n}th stack entry. If @var{n} is zero, this
33043will be the @samp{.} line. If @var{n} is from 1 to the current stack size,
33044this will be the beginning of the first line of that stack entry's display.
33045If line numbers are enabled, this will move to the first character of the
33046line number, not the stack entry itself.
33047@end defun
33048
33049@defun calc-substack-height n
33050Return the number of lines between the beginning of the @var{n}th stack
33051entry and the bottom of the buffer. If @var{n} is zero, this
33052will be one (assuming no stack truncation). If all stack entries are
33053one line long (i.e., no matrices are displayed), the return value will
33054be equal @var{n}+1 as long as @var{n} is in range. (Note that in Big
33055mode, the return value includes the blank lines that separate stack
33056entries.)
33057@end defun
33058
33059@defun calc-refresh
33060Erase the @code{*Calculator*} buffer and reformat its contents from memory.
33061This must be called after changing any parameter, such as the current
33062display radix, which might change the appearance of existing stack
33063entries. (During a keyboard macro invoked by the @kbd{X} key, refreshing
33064is suppressed, but a flag is set so that the entire stack will be refreshed
33065rather than just the top few elements when the macro finishes.)
33066@end defun
33067
33068@node Predicates, Computational Lisp Functions, Stack Lisp Functions, Internals
33069@subsubsection Predicates
33070
33071@noindent
33072The functions described here are predicates, that is, they return a
33073true/false value where @code{nil} means false and anything else means
33074true. These predicates are expanded by @code{defmath}, for example,
33075from @code{zerop} to @code{math-zerop}. In many cases they correspond
33076to native Lisp functions by the same name, but are extended to cover
33077the full range of Calc data types.
33078
33079@defun zerop x
33080Returns true if @var{x} is numerically zero, in any of the Calc data
33081types. (Note that for some types, such as error forms and intervals,
33082it never makes sense to return true.) In @code{defmath}, the expression
33083@samp{(= x 0)} will automatically be converted to @samp{(math-zerop x)},
33084and @samp{(/= x 0)} will be converted to @samp{(not (math-zerop x))}.
33085@end defun
33086
33087@defun negp x
33088Returns true if @var{x} is negative. This accepts negative real numbers
33089of various types, negative HMS and date forms, and intervals in which
33090all included values are negative. In @code{defmath}, the expression
33091@samp{(< x 0)} will automatically be converted to @samp{(math-negp x)},
33092and @samp{(>= x 0)} will be converted to @samp{(not (math-negp x))}.
33093@end defun
33094
33095@defun posp x
33096Returns true if @var{x} is positive (and non-zero). For complex
33097numbers, none of these three predicates will return true.
33098@end defun
33099
33100@defun looks-negp x
33101Returns true if @var{x} is ``negative-looking.'' This returns true if
33102@var{x} is a negative number, or a formula with a leading minus sign
33103such as @samp{-a/b}. In other words, this is an object which can be
33104made simpler by calling @code{(- @var{x})}.
33105@end defun
33106
33107@defun integerp x
33108Returns true if @var{x} is an integer of any size.
33109@end defun
33110
33111@defun fixnump x
33112Returns true if @var{x} is a native Lisp integer.
33113@end defun
33114
33115@defun natnump x
33116Returns true if @var{x} is a nonnegative integer of any size.
33117@end defun
33118
33119@defun fixnatnump x
33120Returns true if @var{x} is a nonnegative Lisp integer.
33121@end defun
33122
33123@defun num-integerp x
33124Returns true if @var{x} is numerically an integer, i.e., either a
33125true integer or a float with no significant digits to the right of
33126the decimal point.
33127@end defun
33128
33129@defun messy-integerp x
33130Returns true if @var{x} is numerically, but not literally, an integer.
33131A value is @code{num-integerp} if it is @code{integerp} or
33132@code{messy-integerp} (but it is never both at once).
33133@end defun
33134
33135@defun num-natnump x
33136Returns true if @var{x} is numerically a nonnegative integer.
33137@end defun
33138
33139@defun evenp x
33140Returns true if @var{x} is an even integer.
33141@end defun
33142
33143@defun looks-evenp x
33144Returns true if @var{x} is an even integer, or a formula with a leading
33145multiplicative coefficient which is an even integer.
33146@end defun
33147
33148@defun oddp x
33149Returns true if @var{x} is an odd integer.
33150@end defun
33151
33152@defun ratp x
33153Returns true if @var{x} is a rational number, i.e., an integer or a
33154fraction.
33155@end defun
33156
33157@defun realp x
33158Returns true if @var{x} is a real number, i.e., an integer, fraction,
33159or floating-point number.
33160@end defun
33161
33162@defun anglep x
33163Returns true if @var{x} is a real number or HMS form.
33164@end defun
33165
33166@defun floatp x
33167Returns true if @var{x} is a float, or a complex number, error form,
33168interval, date form, or modulo form in which at least one component
33169is a float.
33170@end defun
33171
33172@defun complexp x
33173Returns true if @var{x} is a rectangular or polar complex number
33174(but not a real number).
33175@end defun
33176
33177@defun rect-complexp x
33178Returns true if @var{x} is a rectangular complex number.
33179@end defun
33180
33181@defun polar-complexp x
33182Returns true if @var{x} is a polar complex number.
33183@end defun
33184
33185@defun numberp x
33186Returns true if @var{x} is a real number or a complex number.
33187@end defun
33188
33189@defun scalarp x
33190Returns true if @var{x} is a real or complex number or an HMS form.
33191@end defun
33192
33193@defun vectorp x
33194Returns true if @var{x} is a vector (this simply checks if its argument
33195is a list whose first element is the symbol @code{vec}).
33196@end defun
33197
33198@defun numvecp x
33199Returns true if @var{x} is a number or vector.
33200@end defun
33201
33202@defun matrixp x
33203Returns true if @var{x} is a matrix, i.e., a vector of one or more vectors,
33204all of the same size.
33205@end defun
33206
33207@defun square-matrixp x
33208Returns true if @var{x} is a square matrix.
33209@end defun
33210
33211@defun objectp x
33212Returns true if @var{x} is any numeric Calc object, including real and
33213complex numbers, HMS forms, date forms, error forms, intervals, and
33214modulo forms. (Note that error forms and intervals may include formulas
33215as their components; see @code{constp} below.)
33216@end defun
33217
33218@defun objvecp x
33219Returns true if @var{x} is an object or a vector. This also accepts
33220incomplete objects, but it rejects variables and formulas (except as
33221mentioned above for @code{objectp}).
33222@end defun
33223
33224@defun primp x
33225Returns true if @var{x} is a ``primitive'' or ``atomic'' Calc object,
33226i.e., one whose components cannot be regarded as sub-formulas. This
33227includes variables, and all @code{objectp} types except error forms
33228and intervals.
33229@end defun
33230
33231@defun constp x
33232Returns true if @var{x} is constant, i.e., a real or complex number,
33233HMS form, date form, or error form, interval, or vector all of whose
33234components are @code{constp}.
33235@end defun
33236
33237@defun lessp x y
33238Returns true if @var{x} is numerically less than @var{y}. Returns false
33239if @var{x} is greater than or equal to @var{y}, or if the order is
33240undefined or cannot be determined. Generally speaking, this works
33241by checking whether @samp{@var{x} - @var{y}} is @code{negp}. In
33242@code{defmath}, the expression @samp{(< x y)} will automatically be
33243converted to @samp{(lessp x y)}; expressions involving @code{>}, @code{<=},
33244and @code{>=} are similarly converted in terms of @code{lessp}.
33245@end defun
33246
33247@defun beforep x y
33248Returns true if @var{x} comes before @var{y} in a canonical ordering
33249of Calc objects. If @var{x} and @var{y} are both real numbers, this
33250will be the same as @code{lessp}. But whereas @code{lessp} considers
33251other types of objects to be unordered, @code{beforep} puts any two
33252objects into a definite, consistent order. The @code{beforep}
33253function is used by the @kbd{V S} vector-sorting command, and also
33254by @kbd{a s} to put the terms of a product into canonical order:
33255This allows @samp{x y + y x} to be simplified easily to @samp{2 x y}.
33256@end defun
33257
33258@defun equal x y
33259This is the standard Lisp @code{equal} predicate; it returns true if
33260@var{x} and @var{y} are structurally identical. This is the usual way
33261to compare numbers for equality, but note that @code{equal} will treat
332620 and 0.0 as different.
33263@end defun
33264
33265@defun math-equal x y
33266Returns true if @var{x} and @var{y} are numerically equal, either because
33267they are @code{equal}, or because their difference is @code{zerop}. In
33268@code{defmath}, the expression @samp{(= x y)} will automatically be
33269converted to @samp{(math-equal x y)}.
33270@end defun
33271
33272@defun equal-int x n
33273Returns true if @var{x} and @var{n} are numerically equal, where @var{n}
33274is a fixnum which is not a multiple of 10. This will automatically be
33275used by @code{defmath} in place of the more general @code{math-equal}
33276whenever possible.
33277@end defun
33278
33279@defun nearly-equal x y
33280Returns true if @var{x} and @var{y}, as floating-point numbers, are
33281equal except possibly in the last decimal place. For example,
33282314.159 and 314.166 are considered nearly equal if the current
33283precision is 6 (since they differ by 7 units), but not if the current
33284precision is 7 (since they differ by 70 units). Most functions which
33285use series expansions use @code{with-extra-prec} to evaluate the
33286series with 2 extra digits of precision, then use @code{nearly-equal}
33287to decide when the series has converged; this guards against cumulative
33288error in the series evaluation without doing extra work which would be
33289lost when the result is rounded back down to the current precision.
33290In @code{defmath}, this can be written @samp{(~= @var{x} @var{y})}.
33291The @var{x} and @var{y} can be numbers of any kind, including complex.
33292@end defun
33293
33294@defun nearly-zerop x y
33295Returns true if @var{x} is nearly zero, compared to @var{y}. This
33296checks whether @var{x} plus @var{y} would by be @code{nearly-equal}
33297to @var{y} itself, to within the current precision, in other words,
33298if adding @var{x} to @var{y} would have a negligible effect on @var{y}
33299due to roundoff error. @var{X} may be a real or complex number, but
33300@var{y} must be real.
33301@end defun
33302
33303@defun is-true x
33304Return true if the formula @var{x} represents a true value in
33305Calc, not Lisp, terms. It tests if @var{x} is a non-zero number
33306or a provably non-zero formula.
33307@end defun
33308
33309@defun reject-arg val pred
33310Abort the current function evaluation due to unacceptable argument values.
33311This calls @samp{(calc-record-why @var{pred} @var{val})}, then signals a
33312Lisp error which @code{normalize} will trap. The net effect is that the
33313function call which led here will be left in symbolic form.
33314@end defun
33315
33316@defun inexact-value
33317If Symbolic mode is enabled, this will signal an error that causes
33318@code{normalize} to leave the formula in symbolic form, with the message
33319``Inexact result.'' (This function has no effect when not in Symbolic mode.)
33320Note that if your function calls @samp{(sin 5)} in Symbolic mode, the
33321@code{sin} function will call @code{inexact-value}, which will cause your
33322function to be left unsimplified. You may instead wish to call
33323@samp{(normalize (list 'calcFunc-sin 5))}, which in Symbolic mode will
33324return the formula @samp{sin(5)} to your function.
33325@end defun
33326
33327@defun overflow
33328This signals an error that will be reported as a floating-point overflow.
33329@end defun
33330
33331@defun underflow
33332This signals a floating-point underflow.
33333@end defun
33334
33335@node Computational Lisp Functions, Vector Lisp Functions, Predicates, Internals
33336@subsubsection Computational Functions
33337
33338@noindent
33339The functions described here do the actual computational work of the
33340Calculator. In addition to these, note that any function described in
33341the main body of this manual may be called from Lisp; for example, if
33342the documentation refers to the @code{calc-sqrt} [@code{sqrt}] command,
33343this means @code{calc-sqrt} is an interactive stack-based square-root
33344command and @code{sqrt} (which @code{defmath} expands to @code{calcFunc-sqrt})
33345is the actual Lisp function for taking square roots.
33346
33347The functions @code{math-add}, @code{math-sub}, @code{math-mul},
33348@code{math-div}, @code{math-mod}, and @code{math-neg} are not included
33349in this list, since @code{defmath} allows you to write native Lisp
33350@code{+}, @code{-}, @code{*}, @code{/}, @code{%}, and unary @code{-},
33351respectively, instead.
33352
33353@defun normalize val
33354(Full form: @code{math-normalize}.)
33355Reduce the value @var{val} to standard form. For example, if @var{val}
33356is a fixnum, it will be converted to a bignum if it is too large, and
33357if @var{val} is a bignum it will be normalized by clipping off trailing
33358(i.e., most-significant) zero digits and converting to a fixnum if it is
33359small. All the various data types are similarly converted to their standard
33360forms. Variables are left alone, but function calls are actually evaluated
33361in formulas. For example, normalizing @samp{(+ 2 (calcFunc-abs -4))} will
33362return 6.
33363
33364If a function call fails, because the function is void or has the wrong
33365number of parameters, or because it returns @code{nil} or calls
33366@code{reject-arg} or @code{inexact-result}, @code{normalize} returns
33367the formula still in symbolic form.
33368
33369If the current simplification mode is ``none'' or ``numeric arguments
33370only,'' @code{normalize} will act appropriately. However, the more
33371powerful simplification modes (like Algebraic Simplification) are
33372not handled by @code{normalize}. They are handled by @code{calc-normalize},
33373which calls @code{normalize} and possibly some other routines, such
33374as @code{simplify} or @code{simplify-units}. Programs generally will
33375never call @code{calc-normalize} except when popping or pushing values
33376on the stack.
33377@end defun
33378
33379@defun evaluate-expr expr
33380Replace all variables in @var{expr} that have values with their values,
33381then use @code{normalize} to simplify the result. This is what happens
33382when you press the @kbd{=} key interactively.
33383@end defun
33384
33385@defmac with-extra-prec n body
33386Evaluate the Lisp forms in @var{body} with precision increased by @var{n}
33387digits. This is a macro which expands to
33388
33389@smallexample
33390(math-normalize
33391 (let ((calc-internal-prec (+ calc-internal-prec @var{n})))
33392 @var{body}))
33393@end smallexample
33394
33395The surrounding call to @code{math-normalize} causes a floating-point
33396result to be rounded down to the original precision afterwards. This
33397is important because some arithmetic operations assume a number's
33398mantissa contains no more digits than the current precision allows.
33399@end defmac
33400
33401@defun make-frac n d
33402Build a fraction @samp{@var{n}:@var{d}}. This is equivalent to calling
33403@samp{(normalize (list 'frac @var{n} @var{d}))}, but more efficient.
33404@end defun
33405
33406@defun make-float mant exp
33407Build a floating-point value out of @var{mant} and @var{exp}, both
33408of which are arbitrary integers. This function will return a
33409properly normalized float value, or signal an overflow or underflow
33410if @var{exp} is out of range.
33411@end defun
33412
33413@defun make-sdev x sigma
33414Build an error form out of @var{x} and the absolute value of @var{sigma}.
33415If @var{sigma} is zero, the result is the number @var{x} directly.
33416If @var{sigma} is negative or complex, its absolute value is used.
33417If @var{x} or @var{sigma} is not a valid type of object for use in
33418error forms, this calls @code{reject-arg}.
33419@end defun
33420
33421@defun make-intv mask lo hi
33422Build an interval form out of @var{mask} (which is assumed to be an
33423integer from 0 to 3), and the limits @var{lo} and @var{hi}. If
33424@var{lo} is greater than @var{hi}, an empty interval form is returned.
33425This calls @code{reject-arg} if @var{lo} or @var{hi} is unsuitable.
33426@end defun
33427
33428@defun sort-intv mask lo hi
33429Build an interval form, similar to @code{make-intv}, except that if
33430@var{lo} is less than @var{hi} they are simply exchanged, and the
33431bits of @var{mask} are swapped accordingly.
33432@end defun
33433
33434@defun make-mod n m
33435Build a modulo form out of @var{n} and the modulus @var{m}. Since modulo
33436forms do not allow formulas as their components, if @var{n} or @var{m}
33437is not a real number or HMS form the result will be a formula which
33438is a call to @code{makemod}, the algebraic version of this function.
33439@end defun
33440
33441@defun float x
33442Convert @var{x} to floating-point form. Integers and fractions are
33443converted to numerically equivalent floats; components of complex
33444numbers, vectors, HMS forms, date forms, error forms, intervals, and
33445modulo forms are recursively floated. If the argument is a variable
33446or formula, this calls @code{reject-arg}.
33447@end defun
33448
33449@defun compare x y
33450Compare the numbers @var{x} and @var{y}, and return @mathit{-1} if
33451@samp{(lessp @var{x} @var{y})}, 1 if @samp{(lessp @var{y} @var{x})},
334520 if @samp{(math-equal @var{x} @var{y})}, or 2 if the order is
33453undefined or cannot be determined.
33454@end defun
33455
33456@defun numdigs n
33457Return the number of digits of integer @var{n}, effectively
33458@samp{ceil(log10(@var{n}))}, but much more efficient. Zero is
33459considered to have zero digits.
33460@end defun
33461
33462@defun scale-int x n
33463Shift integer @var{x} left @var{n} decimal digits, or right @mathit{-@var{n}}
33464digits with truncation toward zero.
33465@end defun
33466
33467@defun scale-rounding x n
33468Like @code{scale-int}, except that a right shift rounds to the nearest
33469integer rather than truncating.
33470@end defun
33471
33472@defun fixnum n
33473Return the integer @var{n} as a fixnum, i.e., a native Lisp integer.
33474If @var{n} is outside the permissible range for Lisp integers (usually
3347524 binary bits) the result is undefined.
33476@end defun
33477
33478@defun sqr x
33479Compute the square of @var{x}; short for @samp{(* @var{x} @var{x})}.
33480@end defun
33481
33482@defun quotient x y
33483Divide integer @var{x} by integer @var{y}; return an integer quotient
33484and discard the remainder. If @var{x} or @var{y} is negative, the
33485direction of rounding is undefined.
33486@end defun
33487
33488@defun idiv x y
33489Perform an integer division; if @var{x} and @var{y} are both nonnegative
33490integers, this uses the @code{quotient} function, otherwise it computes
33491@samp{floor(@var{x}/@var{y})}. Thus the result is well-defined but
33492slower than for @code{quotient}.
33493@end defun
33494
33495@defun imod x y
33496Divide integer @var{x} by integer @var{y}; return the integer remainder
33497and discard the quotient. Like @code{quotient}, this works only for
33498integer arguments and is not well-defined for negative arguments.
33499For a more well-defined result, use @samp{(% @var{x} @var{y})}.
33500@end defun
33501
33502@defun idivmod x y
33503Divide integer @var{x} by integer @var{y}; return a cons cell whose
33504@code{car} is @samp{(quotient @var{x} @var{y})} and whose @code{cdr}
33505is @samp{(imod @var{x} @var{y})}.
33506@end defun
33507
33508@defun pow x y
33509Compute @var{x} to the power @var{y}. In @code{defmath} code, this can
33510also be written @samp{(^ @var{x} @var{y})} or
33511@w{@samp{(expt @var{x} @var{y})}}.
33512@end defun
33513
33514@defun abs-approx x
33515Compute a fast approximation to the absolute value of @var{x}. For
33516example, for a rectangular complex number the result is the sum of
33517the absolute values of the components.
33518@end defun
33519
33520@findex e
33521@findex gamma-const
33522@findex ln-2
33523@findex ln-10
33524@findex phi
33525@findex pi-over-2
33526@findex pi-over-4
33527@findex pi-over-180
33528@findex sqrt-two-pi
33529@findex sqrt-e
33530@findex two-pi
33531@defun pi
33532The function @samp{(pi)} computes @samp{pi} to the current precision.
33533Other related constant-generating functions are @code{two-pi},
33534@code{pi-over-2}, @code{pi-over-4}, @code{pi-over-180}, @code{sqrt-two-pi},
33535@code{e}, @code{sqrt-e}, @code{ln-2}, @code{ln-10}, @code{phi} and
33536@code{gamma-const}. Each function returns a floating-point value in the
33537current precision, and each uses caching so that all calls after the
33538first are essentially free.
33539@end defun
33540
33541@defmac math-defcache @var{func} @var{initial} @var{form}
33542This macro, usually used as a top-level call like @code{defun} or
33543@code{defvar}, defines a new cached constant analogous to @code{pi}, etc.
33544It defines a function @code{func} which returns the requested value;
33545if @var{initial} is non-@code{nil} it must be a @samp{(float @dots{})}
33546form which serves as an initial value for the cache. If @var{func}
33547is called when the cache is empty or does not have enough digits to
33548satisfy the current precision, the Lisp expression @var{form} is evaluated
33549with the current precision increased by four, and the result minus its
33550two least significant digits is stored in the cache. For example,
33551calling @samp{(pi)} with a precision of 30 computes @samp{pi} to 34
33552digits, rounds it down to 32 digits for future use, then rounds it
33553again to 30 digits for use in the present request.
33554@end defmac
33555
33556@findex half-circle
33557@findex quarter-circle
33558@defun full-circle symb
33559If the current angular mode is Degrees or HMS, this function returns the
33560integer 360. In Radians mode, this function returns either the
33561corresponding value in radians to the current precision, or the formula
33562@samp{2*pi}, depending on the Symbolic mode. There are also similar
33563function @code{half-circle} and @code{quarter-circle}.
33564@end defun
33565
33566@defun power-of-2 n
33567Compute two to the integer power @var{n}, as a (potentially very large)
33568integer. Powers of two are cached, so only the first call for a
33569particular @var{n} is expensive.
33570@end defun
33571
33572@defun integer-log2 n
33573Compute the base-2 logarithm of @var{n}, which must be an integer which
33574is a power of two. If @var{n} is not a power of two, this function will
33575return @code{nil}.
33576@end defun
33577
33578@defun div-mod a b m
33579Divide @var{a} by @var{b}, modulo @var{m}. This returns @code{nil} if
33580there is no solution, or if any of the arguments are not integers.
33581@end defun
33582
33583@defun pow-mod a b m
33584Compute @var{a} to the power @var{b}, modulo @var{m}. If @var{a},
33585@var{b}, and @var{m} are integers, this uses an especially efficient
33586algorithm. Otherwise, it simply computes @samp{(% (^ a b) m)}.
33587@end defun
33588
33589@defun isqrt n
33590Compute the integer square root of @var{n}. This is the square root
33591of @var{n} rounded down toward zero, i.e., @samp{floor(sqrt(@var{n}))}.
33592If @var{n} is itself an integer, the computation is especially efficient.
33593@end defun
33594
33595@defun to-hms a ang
33596Convert the argument @var{a} into an HMS form. If @var{ang} is specified,
33597it is the angular mode in which to interpret @var{a}, either @code{deg}
33598or @code{rad}. Otherwise, the current angular mode is used. If @var{a}
33599is already an HMS form it is returned as-is.
33600@end defun
33601
33602@defun from-hms a ang
33603Convert the HMS form @var{a} into a real number. If @var{ang} is specified,
33604it is the angular mode in which to express the result, otherwise the
33605current angular mode is used. If @var{a} is already a real number, it
33606is returned as-is.
33607@end defun
33608
33609@defun to-radians a
33610Convert the number or HMS form @var{a} to radians from the current
33611angular mode.
33612@end defun
33613
33614@defun from-radians a
33615Convert the number @var{a} from radians to the current angular mode.
33616If @var{a} is a formula, this returns the formula @samp{deg(@var{a})}.
33617@end defun
33618
33619@defun to-radians-2 a
33620Like @code{to-radians}, except that in Symbolic mode a degrees to
33621radians conversion yields a formula like @samp{@var{a}*pi/180}.
33622@end defun
33623
33624@defun from-radians-2 a
33625Like @code{from-radians}, except that in Symbolic mode a radians to
33626degrees conversion yields a formula like @samp{@var{a}*180/pi}.
33627@end defun
33628
33629@defun random-digit
33630Produce a random base-1000 digit in the range 0 to 999.
33631@end defun
33632
33633@defun random-digits n
33634Produce a random @var{n}-digit integer; this will be an integer
33635in the interval @samp{[0, 10^@var{n})}.
33636@end defun
33637
33638@defun random-float
33639Produce a random float in the interval @samp{[0, 1)}.
33640@end defun
33641
33642@defun prime-test n iters
33643Determine whether the integer @var{n} is prime. Return a list which has
33644one of these forms: @samp{(nil @var{f})} means the number is non-prime
33645because it was found to be divisible by @var{f}; @samp{(nil)} means it
33646was found to be non-prime by table look-up (so no factors are known);
33647@samp{(nil unknown)} means it is definitely non-prime but no factors
33648are known because @var{n} was large enough that Fermat's probabilistic
33649test had to be used; @samp{(t)} means the number is definitely prime;
33650and @samp{(maybe @var{i} @var{p})} means that Fermat's test, after @var{i}
33651iterations, is @var{p} percent sure that the number is prime. The
33652@var{iters} parameter is the number of Fermat iterations to use, in the
33653case that this is necessary. If @code{prime-test} returns ``maybe,''
33654you can call it again with the same @var{n} to get a greater certainty;
33655@code{prime-test} remembers where it left off.
33656@end defun
33657
33658@defun to-simple-fraction f
33659If @var{f} is a floating-point number which can be represented exactly
33660as a small rational number. return that number, else return @var{f}.
33661For example, 0.75 would be converted to 3:4. This function is very
33662fast.
33663@end defun
33664
33665@defun to-fraction f tol
33666Find a rational approximation to floating-point number @var{f} to within
33667a specified tolerance @var{tol}; this corresponds to the algebraic
33668function @code{frac}, and can be rather slow.
33669@end defun
33670
33671@defun quarter-integer n
33672If @var{n} is an integer or integer-valued float, this function
33673returns zero. If @var{n} is a half-integer (i.e., an integer plus
33674@mathit{1:2} or 0.5), it returns 2. If @var{n} is a quarter-integer,
33675it returns 1 or 3. If @var{n} is anything else, this function
33676returns @code{nil}.
33677@end defun
33678
33679@node Vector Lisp Functions, Symbolic Lisp Functions, Computational Lisp Functions, Internals
33680@subsubsection Vector Functions
33681
33682@noindent
33683The functions described here perform various operations on vectors and
33684matrices.
33685
33686@defun math-concat x y
33687Do a vector concatenation; this operation is written @samp{@var{x} | @var{y}}
33688in a symbolic formula. @xref{Building Vectors}.
33689@end defun
33690
33691@defun vec-length v
33692Return the length of vector @var{v}. If @var{v} is not a vector, the
33693result is zero. If @var{v} is a matrix, this returns the number of
33694rows in the matrix.
33695@end defun
33696
33697@defun mat-dimens m
33698Determine the dimensions of vector or matrix @var{m}. If @var{m} is not
33699a vector, the result is an empty list. If @var{m} is a plain vector
33700but not a matrix, the result is a one-element list containing the length
33701of the vector. If @var{m} is a matrix with @var{r} rows and @var{c} columns,
33702the result is the list @samp{(@var{r} @var{c})}. Higher-order tensors
33703produce lists of more than two dimensions. Note that the object
33704@samp{[[1, 2, 3], [4, 5]]} is a vector of vectors not all the same size,
33705and is treated by this and other Calc routines as a plain vector of two
33706elements.
33707@end defun
33708
33709@defun dimension-error
33710Abort the current function with a message of ``Dimension error.''
33711The Calculator will leave the function being evaluated in symbolic
33712form; this is really just a special case of @code{reject-arg}.
33713@end defun
33714
33715@defun build-vector args
33716Return a Calc vector with @var{args} as elements.
33717For example, @samp{(build-vector 1 2 3)} returns the Calc vector
33718@samp{[1, 2, 3]}, stored internally as the list @samp{(vec 1 2 3)}.
33719@end defun
33720
33721@defun make-vec obj dims
33722Return a Calc vector or matrix all of whose elements are equal to
33723@var{obj}. For example, @samp{(make-vec 27 3 4)} returns a 3x4 matrix
33724filled with 27's.
33725@end defun
33726
33727@defun row-matrix v
33728If @var{v} is a plain vector, convert it into a row matrix, i.e.,
33729a matrix whose single row is @var{v}. If @var{v} is already a matrix,
33730leave it alone.
33731@end defun
33732
33733@defun col-matrix v
33734If @var{v} is a plain vector, convert it into a column matrix, i.e., a
33735matrix with each element of @var{v} as a separate row. If @var{v} is
33736already a matrix, leave it alone.
33737@end defun
33738
33739@defun map-vec f v
33740Map the Lisp function @var{f} over the Calc vector @var{v}. For example,
33741@samp{(map-vec 'math-floor v)} returns a vector of the floored components
33742of vector @var{v}.
33743@end defun
33744
33745@defun map-vec-2 f a b
33746Map the Lisp function @var{f} over the two vectors @var{a} and @var{b}.
33747If @var{a} and @var{b} are vectors of equal length, the result is a
33748vector of the results of calling @samp{(@var{f} @var{ai} @var{bi})}
33749for each pair of elements @var{ai} and @var{bi}. If either @var{a} or
33750@var{b} is a scalar, it is matched with each value of the other vector.
33751For example, @samp{(map-vec-2 'math-add v 1)} returns the vector @var{v}
33752with each element increased by one. Note that using @samp{'+} would not
33753work here, since @code{defmath} does not expand function names everywhere,
33754just where they are in the function position of a Lisp expression.
33755@end defun
33756
33757@defun reduce-vec f v
33758Reduce the function @var{f} over the vector @var{v}. For example, if
33759@var{v} is @samp{[10, 20, 30, 40]}, this calls @samp{(f (f (f 10 20) 30) 40)}.
33760If @var{v} is a matrix, this reduces over the rows of @var{v}.
33761@end defun
33762
33763@defun reduce-cols f m
33764Reduce the function @var{f} over the columns of matrix @var{m}. For
33765example, if @var{m} is @samp{[[1, 2], [3, 4], [5, 6]]}, the result
33766is a vector of the two elements @samp{(f (f 1 3) 5)} and @samp{(f (f 2 4) 6)}.
33767@end defun
33768
33769@defun mat-row m n
33770Return the @var{n}th row of matrix @var{m}. This is equivalent to
33771@samp{(elt m n)}. For a slower but safer version, use @code{mrow}.
33772(@xref{Extracting Elements}.)
33773@end defun
33774
33775@defun mat-col m n
33776Return the @var{n}th column of matrix @var{m}, in the form of a vector.
33777The arguments are not checked for correctness.
33778@end defun
33779
33780@defun mat-less-row m n
33781Return a copy of matrix @var{m} with its @var{n}th row deleted. The
33782number @var{n} must be in range from 1 to the number of rows in @var{m}.
33783@end defun
33784
33785@defun mat-less-col m n
33786Return a copy of matrix @var{m} with its @var{n}th column deleted.
33787@end defun
33788
33789@defun transpose m
33790Return the transpose of matrix @var{m}.
33791@end defun
33792
33793@defun flatten-vector v
33794Flatten nested vector @var{v} into a vector of scalars. For example,
33795if @var{v} is @samp{[[1, 2, 3], [4, 5]]} the result is @samp{[1, 2, 3, 4, 5]}.
33796@end defun
33797
33798@defun copy-matrix m
33799If @var{m} is a matrix, return a copy of @var{m}. This maps
33800@code{copy-sequence} over the rows of @var{m}; in Lisp terms, each
33801element of the result matrix will be @code{eq} to the corresponding
33802element of @var{m}, but none of the @code{cons} cells that make up
33803the structure of the matrix will be @code{eq}. If @var{m} is a plain
33804vector, this is the same as @code{copy-sequence}.
33805@end defun
33806
33807@defun swap-rows m r1 r2
33808Exchange rows @var{r1} and @var{r2} of matrix @var{m} in-place. In
33809other words, unlike most of the other functions described here, this
33810function changes @var{m} itself rather than building up a new result
33811matrix. The return value is @var{m}, i.e., @samp{(eq (swap-rows m 1 2) m)}
33812is true, with the side effect of exchanging the first two rows of
33813@var{m}.
33814@end defun
33815
33816@node Symbolic Lisp Functions, Formatting Lisp Functions, Vector Lisp Functions, Internals
33817@subsubsection Symbolic Functions
33818
33819@noindent
33820The functions described here operate on symbolic formulas in the
33821Calculator.
33822
33823@defun calc-prepare-selection num
33824Prepare a stack entry for selection operations. If @var{num} is
33825omitted, the stack entry containing the cursor is used; otherwise,
33826it is the number of the stack entry to use. This function stores
33827useful information about the current stack entry into a set of
33828variables. @code{calc-selection-cache-num} contains the number of
33829the stack entry involved (equal to @var{num} if you specified it);
33830@code{calc-selection-cache-entry} contains the stack entry as a
33831list (such as @code{calc-top-list} would return with @code{entry}
33832as the selection mode); and @code{calc-selection-cache-comp} contains
33833a special ``tagged'' composition (@pxref{Formatting Lisp Functions})
33834which allows Calc to relate cursor positions in the buffer with
33835their corresponding sub-formulas.
33836
33837A slight complication arises in the selection mechanism because
33838formulas may contain small integers. For example, in the vector
33839@samp{[1, 2, 1]} the first and last elements are @code{eq} to each
33840other; selections are recorded as the actual Lisp object that
33841appears somewhere in the tree of the whole formula, but storing
33842@code{1} would falsely select both @code{1}'s in the vector. So
33843@code{calc-prepare-selection} also checks the stack entry and
33844replaces any plain integers with ``complex number'' lists of the form
33845@samp{(cplx @var{n} 0)}. This list will be displayed the same as a
33846plain @var{n} and the change will be completely invisible to the
33847user, but it will guarantee that no two sub-formulas of the stack
33848entry will be @code{eq} to each other. Next time the stack entry
33849is involved in a computation, @code{calc-normalize} will replace
33850these lists with plain numbers again, again invisibly to the user.
33851@end defun
33852
33853@defun calc-encase-atoms x
33854This modifies the formula @var{x} to ensure that each part of the
33855formula is a unique atom, using the @samp{(cplx @var{n} 0)} trick
33856described above. This function may use @code{setcar} to modify
33857the formula in-place.
33858@end defun
33859
33860@defun calc-find-selected-part
33861Find the smallest sub-formula of the current formula that contains
33862the cursor. This assumes @code{calc-prepare-selection} has been
33863called already. If the cursor is not actually on any part of the
33864formula, this returns @code{nil}.
33865@end defun
33866
33867@defun calc-change-current-selection selection
33868Change the currently prepared stack element's selection to
33869@var{selection}, which should be @code{eq} to some sub-formula
33870of the stack element, or @code{nil} to unselect the formula.
33871The stack element's appearance in the Calc buffer is adjusted
33872to reflect the new selection.
33873@end defun
33874
33875@defun calc-find-nth-part expr n
33876Return the @var{n}th sub-formula of @var{expr}. This function is used
33877by the selection commands, and (unless @kbd{j b} has been used) treats
33878sums and products as flat many-element formulas. Thus if @var{expr}
33879is @samp{((a + b) - c) + d}, calling @code{calc-find-nth-part} with
33880@var{n} equal to four will return @samp{d}.
33881@end defun
33882
33883@defun calc-find-parent-formula expr part
33884Return the sub-formula of @var{expr} which immediately contains
33885@var{part}. If @var{expr} is @samp{a*b + (c+1)*d} and @var{part}
33886is @code{eq} to the @samp{c+1} term of @var{expr}, then this function
33887will return @samp{(c+1)*d}. If @var{part} turns out not to be a
33888sub-formula of @var{expr}, the function returns @code{nil}. If
33889@var{part} is @code{eq} to @var{expr}, the function returns @code{t}.
33890This function does not take associativity into account.
33891@end defun
33892
33893@defun calc-find-assoc-parent-formula expr part
33894This is the same as @code{calc-find-parent-formula}, except that
33895(unless @kbd{j b} has been used) it continues widening the selection
33896to contain a complete level of the formula. Given @samp{a} from
33897@samp{((a + b) - c) + d}, @code{calc-find-parent-formula} will
33898return @samp{a + b} but @code{calc-find-assoc-parent-formula} will
33899return the whole expression.
33900@end defun
33901
33902@defun calc-grow-assoc-formula expr part
33903This expands sub-formula @var{part} of @var{expr} to encompass a
33904complete level of the formula. If @var{part} and its immediate
33905parent are not compatible associative operators, or if @kbd{j b}
33906has been used, this simply returns @var{part}.
33907@end defun
33908
33909@defun calc-find-sub-formula expr part
33910This finds the immediate sub-formula of @var{expr} which contains
33911@var{part}. It returns an index @var{n} such that
33912@samp{(calc-find-nth-part @var{expr} @var{n})} would return @var{part}.
33913If @var{part} is not a sub-formula of @var{expr}, it returns @code{nil}.
33914If @var{part} is @code{eq} to @var{expr}, it returns @code{t}. This
33915function does not take associativity into account.
33916@end defun
33917
33918@defun calc-replace-sub-formula expr old new
33919This function returns a copy of formula @var{expr}, with the
33920sub-formula that is @code{eq} to @var{old} replaced by @var{new}.
33921@end defun
33922
33923@defun simplify expr
33924Simplify the expression @var{expr} by applying various algebraic rules.
33925This is what the @w{@kbd{a s}} (@code{calc-simplify}) command uses. This
33926always returns a copy of the expression; the structure @var{expr} points
33927to remains unchanged in memory.
33928
33929More precisely, here is what @code{simplify} does: The expression is
33930first normalized and evaluated by calling @code{normalize}. If any
33931@code{AlgSimpRules} have been defined, they are then applied. Then
33932the expression is traversed in a depth-first, bottom-up fashion; at
33933each level, any simplifications that can be made are made until no
33934further changes are possible. Once the entire formula has been
33935traversed in this way, it is compared with the original formula (from
33936before the call to @code{normalize}) and, if it has changed,
33937the entire procedure is repeated (starting with @code{normalize})
33938until no further changes occur. Usually only two iterations are
33939needed:@: one to simplify the formula, and another to verify that no
33940further simplifications were possible.
33941@end defun
33942
33943@defun simplify-extended expr
33944Simplify the expression @var{expr}, with additional rules enabled that
33945help do a more thorough job, while not being entirely ``safe'' in all
33946circumstances. (For example, this mode will simplify @samp{sqrt(x^2)}
33947to @samp{x}, which is only valid when @var{x} is positive.) This is
33948implemented by temporarily binding the variable @code{math-living-dangerously}
33949to @code{t} (using a @code{let} form) and calling @code{simplify}.
33950Dangerous simplification rules are written to check this variable
33951before taking any action.
33952@end defun
33953
33954@defun simplify-units expr
33955Simplify the expression @var{expr}, treating variable names as units
33956whenever possible. This works by binding the variable
33957@code{math-simplifying-units} to @code{t} while calling @code{simplify}.
33958@end defun
33959
33960@defmac math-defsimplify funcs body
33961Register a new simplification rule; this is normally called as a top-level
33962form, like @code{defun} or @code{defmath}. If @var{funcs} is a symbol
33963(like @code{+} or @code{calcFunc-sqrt}), this simplification rule is
33964applied to the formulas which are calls to the specified function. Or,
33965@var{funcs} can be a list of such symbols; the rule applies to all
33966functions on the list. The @var{body} is written like the body of a
33967function with a single argument called @code{expr}. The body will be
33968executed with @code{expr} bound to a formula which is a call to one of
33969the functions @var{funcs}. If the function body returns @code{nil}, or
33970if it returns a result @code{equal} to the original @code{expr}, it is
33971ignored and Calc goes on to try the next simplification rule that applies.
33972If the function body returns something different, that new formula is
33973substituted for @var{expr} in the original formula.
33974
33975At each point in the formula, rules are tried in the order of the
33976original calls to @code{math-defsimplify}; the search stops after the
33977first rule that makes a change. Thus later rules for that same
33978function will not have a chance to trigger until the next iteration
33979of the main @code{simplify} loop.
33980
33981Note that, since @code{defmath} is not being used here, @var{body} must
33982be written in true Lisp code without the conveniences that @code{defmath}
33983provides. If you prefer, you can have @var{body} simply call another
33984function (defined with @code{defmath}) which does the real work.
33985
33986The arguments of a function call will already have been simplified
33987before any rules for the call itself are invoked. Since a new argument
33988list is consed up when this happens, this means that the rule's body is
33989allowed to rearrange the function's arguments destructively if that is
33990convenient. Here is a typical example of a simplification rule:
33991
33992@smallexample
33993(math-defsimplify calcFunc-arcsinh
33994 (or (and (math-looks-negp (nth 1 expr))
33995 (math-neg (list 'calcFunc-arcsinh
33996 (math-neg (nth 1 expr)))))
33997 (and (eq (car-safe (nth 1 expr)) 'calcFunc-sinh)
33998 (or math-living-dangerously
33999 (math-known-realp (nth 1 (nth 1 expr))))
34000 (nth 1 (nth 1 expr)))))
34001@end smallexample
34002
34003This is really a pair of rules written with one @code{math-defsimplify}
34004for convenience; the first replaces @samp{arcsinh(-x)} with
34005@samp{-arcsinh(x)}, and the second, which is safe only for real @samp{x},
34006replaces @samp{arcsinh(sinh(x))} with @samp{x}.
34007@end defmac
34008
34009@defun common-constant-factor expr
34010Check @var{expr} to see if it is a sum of terms all multiplied by the
34011same rational value. If so, return this value. If not, return @code{nil}.
34012For example, if called on @samp{6x + 9y + 12z}, it would return 3, since
340133 is a common factor of all the terms.
34014@end defun
34015
34016@defun cancel-common-factor expr factor
34017Assuming @var{expr} is a sum with @var{factor} as a common factor,
34018divide each term of the sum by @var{factor}. This is done by
34019destructively modifying parts of @var{expr}, on the assumption that
34020it is being used by a simplification rule (where such things are
34021allowed; see above). For example, consider this built-in rule for
34022square roots:
34023
34024@smallexample
34025(math-defsimplify calcFunc-sqrt
34026 (let ((fac (math-common-constant-factor (nth 1 expr))))
34027 (and fac (not (eq fac 1))
34028 (math-mul (math-normalize (list 'calcFunc-sqrt fac))
34029 (math-normalize
34030 (list 'calcFunc-sqrt
34031 (math-cancel-common-factor
34032 (nth 1 expr) fac)))))))
34033@end smallexample
34034@end defun
34035
34036@defun frac-gcd a b
34037Compute a ``rational GCD'' of @var{a} and @var{b}, which must both be
34038rational numbers. This is the fraction composed of the GCD of the
34039numerators of @var{a} and @var{b}, over the GCD of the denominators.
34040It is used by @code{common-constant-factor}. Note that the standard
34041@code{gcd} function uses the LCM to combine the denominators.
34042@end defun
34043
34044@defun map-tree func expr many
34045Try applying Lisp function @var{func} to various sub-expressions of
34046@var{expr}. Initially, call @var{func} with @var{expr} itself as an
34047argument. If this returns an expression which is not @code{equal} to
34048@var{expr}, apply @var{func} again until eventually it does return
34049@var{expr} with no changes. Then, if @var{expr} is a function call,
34050recursively apply @var{func} to each of the arguments. This keeps going
34051until no changes occur anywhere in the expression; this final expression
34052is returned by @code{map-tree}. Note that, unlike simplification rules,
34053@var{func} functions may @emph{not} make destructive changes to
34054@var{expr}. If a third argument @var{many} is provided, it is an
34055integer which says how many times @var{func} may be applied; the
34056default, as described above, is infinitely many times.
34057@end defun
34058
34059@defun compile-rewrites rules
34060Compile the rewrite rule set specified by @var{rules}, which should
34061be a formula that is either a vector or a variable name. If the latter,
34062the compiled rules are saved so that later @code{compile-rules} calls
34063for that same variable can return immediately. If there are problems
34064with the rules, this function calls @code{error} with a suitable
34065message.
34066@end defun
34067
34068@defun apply-rewrites expr crules heads
34069Apply the compiled rewrite rule set @var{crules} to the expression
34070@var{expr}. This will make only one rewrite and only checks at the
34071top level of the expression. The result @code{nil} if no rules
34072matched, or if the only rules that matched did not actually change
34073the expression. The @var{heads} argument is optional; if is given,
34074it should be a list of all function names that (may) appear in
34075@var{expr}. The rewrite compiler tags each rule with the
34076rarest-looking function name in the rule; if you specify @var{heads},
34077@code{apply-rewrites} can use this information to narrow its search
34078down to just a few rules in the rule set.
34079@end defun
34080
34081@defun rewrite-heads expr
34082Compute a @var{heads} list for @var{expr} suitable for use with
34083@code{apply-rewrites}, as discussed above.
34084@end defun
34085
34086@defun rewrite expr rules many
34087This is an all-in-one rewrite function. It compiles the rule set
34088specified by @var{rules}, then uses @code{map-tree} to apply the
34089rules throughout @var{expr} up to @var{many} (default infinity)
34090times.
34091@end defun
34092
34093@defun match-patterns pat vec not-flag
34094Given a Calc vector @var{vec} and an uncompiled pattern set or
34095pattern set variable @var{pat}, this function returns a new vector
34096of all elements of @var{vec} which do (or don't, if @var{not-flag} is
34097non-@code{nil}) match any of the patterns in @var{pat}.
34098@end defun
34099
34100@defun deriv expr var value symb
34101Compute the derivative of @var{expr} with respect to variable @var{var}
34102(which may actually be any sub-expression). If @var{value} is specified,
34103the derivative is evaluated at the value of @var{var}; otherwise, the
34104derivative is left in terms of @var{var}. If the expression contains
34105functions for which no derivative formula is known, new derivative
34106functions are invented by adding primes to the names; @pxref{Calculus}.
34107However, if @var{symb} is non-@code{nil}, the presence of undifferentiable
34108functions in @var{expr} instead cancels the whole differentiation, and
34109@code{deriv} returns @code{nil} instead.
34110
34111Derivatives of an @var{n}-argument function can be defined by
34112adding a @code{math-derivative-@var{n}} property to the property list
34113of the symbol for the function's derivative, which will be the
34114function name followed by an apostrophe. The value of the property
34115should be a Lisp function; it is called with the same arguments as the
34116original function call that is being differentiated. It should return
34117a formula for the derivative. For example, the derivative of @code{ln}
34118is defined by
34119
34120@smallexample
34121(put 'calcFunc-ln\' 'math-derivative-1
34122 (function (lambda (u) (math-div 1 u))))
34123@end smallexample
34124
34125The two-argument @code{log} function has two derivatives,
34126@smallexample
34127(put 'calcFunc-log\' 'math-derivative-2 ; d(log(x,b)) / dx
34128 (function (lambda (x b) ... )))
34129(put 'calcFunc-log\'2 'math-derivative-2 ; d(log(x,b)) / db
34130 (function (lambda (x b) ... )))
34131@end smallexample
34132@end defun
34133
34134@defun tderiv expr var value symb
34135Compute the total derivative of @var{expr}. This is the same as
34136@code{deriv}, except that variables other than @var{var} are not
34137assumed to be constant with respect to @var{var}.
34138@end defun
34139
34140@defun integ expr var low high
34141Compute the integral of @var{expr} with respect to @var{var}.
34142@xref{Calculus}, for further details.
34143@end defun
34144
34145@defmac math-defintegral funcs body
34146Define a rule for integrating a function or functions of one argument;
34147this macro is very similar in format to @code{math-defsimplify}.
34148The main difference is that here @var{body} is the body of a function
34149with a single argument @code{u} which is bound to the argument to the
34150function being integrated, not the function call itself. Also, the
34151variable of integration is available as @code{math-integ-var}. If
34152evaluation of the integral requires doing further integrals, the body
34153should call @samp{(math-integral @var{x})} to find the integral of
34154@var{x} with respect to @code{math-integ-var}; this function returns
34155@code{nil} if the integral could not be done. Some examples:
34156
34157@smallexample
34158(math-defintegral calcFunc-conj
34159 (let ((int (math-integral u)))
34160 (and int
34161 (list 'calcFunc-conj int))))
34162
34163(math-defintegral calcFunc-cos
34164 (and (equal u math-integ-var)
34165 (math-from-radians-2 (list 'calcFunc-sin u))))
34166@end smallexample
34167
34168In the @code{cos} example, we define only the integral of @samp{cos(x) dx},
34169relying on the general integration-by-substitution facility to handle
34170cosines of more complicated arguments. An integration rule should return
34171@code{nil} if it can't do the integral; if several rules are defined for
34172the same function, they are tried in order until one returns a non-@code{nil}
34173result.
34174@end defmac
34175
34176@defmac math-defintegral-2 funcs body
34177Define a rule for integrating a function or functions of two arguments.
34178This is exactly analogous to @code{math-defintegral}, except that @var{body}
34179is written as the body of a function with two arguments, @var{u} and
34180@var{v}.
34181@end defmac
34182
34183@defun solve-for lhs rhs var full
34184Attempt to solve the equation @samp{@var{lhs} = @var{rhs}} by isolating
34185the variable @var{var} on the lefthand side; return the resulting righthand
34186side, or @code{nil} if the equation cannot be solved. The variable
34187@var{var} must appear at least once in @var{lhs} or @var{rhs}. Note that
34188the return value is a formula which does not contain @var{var}; this is
34189different from the user-level @code{solve} and @code{finv} functions,
34190which return a rearranged equation or a functional inverse, respectively.
34191If @var{full} is non-@code{nil}, a full solution including dummy signs
34192and dummy integers will be produced. User-defined inverses are provided
34193as properties in a manner similar to derivatives:
34194
34195@smallexample
34196(put 'calcFunc-ln 'math-inverse
34197 (function (lambda (x) (list 'calcFunc-exp x))))
34198@end smallexample
34199
34200This function can call @samp{(math-solve-get-sign @var{x})} to create
34201a new arbitrary sign variable, returning @var{x} times that sign, and
34202@samp{(math-solve-get-int @var{x})} to create a new arbitrary integer
34203variable multiplied by @var{x}. These functions simply return @var{x}
34204if the caller requested a non-``full'' solution.
34205@end defun
34206
34207@defun solve-eqn expr var full
34208This version of @code{solve-for} takes an expression which will
34209typically be an equation or inequality. (If it is not, it will be
34210interpreted as the equation @samp{@var{expr} = 0}.) It returns an
34211equation or inequality, or @code{nil} if no solution could be found.
34212@end defun
34213
34214@defun solve-system exprs vars full
34215This function solves a system of equations. Generally, @var{exprs}
34216and @var{vars} will be vectors of equal length.
34217@xref{Solving Systems of Equations}, for other options.
34218@end defun
34219
34220@defun expr-contains expr var
34221Returns a non-@code{nil} value if @var{var} occurs as a subexpression
34222of @var{expr}.
34223
34224This function might seem at first to be identical to
34225@code{calc-find-sub-formula}. The key difference is that
34226@code{expr-contains} uses @code{equal} to test for matches, whereas
34227@code{calc-find-sub-formula} uses @code{eq}. In the formula
34228@samp{f(a, a)}, the two @samp{a}s will be @code{equal} but not
34229@code{eq} to each other.
34230@end defun
34231
34232@defun expr-contains-count expr var
34233Returns the number of occurrences of @var{var} as a subexpression
34234of @var{expr}, or @code{nil} if there are no occurrences.
34235@end defun
34236
34237@defun expr-depends expr var
34238Returns true if @var{expr} refers to any variable the occurs in @var{var}.
34239In other words, it checks if @var{expr} and @var{var} have any variables
34240in common.
34241@end defun
34242
34243@defun expr-contains-vars expr
34244Return true if @var{expr} contains any variables, or @code{nil} if @var{expr}
34245contains only constants and functions with constant arguments.
34246@end defun
34247
34248@defun expr-subst expr old new
34249Returns a copy of @var{expr}, with all occurrences of @var{old} replaced
34250by @var{new}. This treats @code{lambda} forms specially with respect
34251to the dummy argument variables, so that the effect is always to return
34252@var{expr} evaluated at @var{old} = @var{new}.
34253@end defun
34254
34255@defun multi-subst expr old new
34256This is like @code{expr-subst}, except that @var{old} and @var{new}
34257are lists of expressions to be substituted simultaneously. If one
34258list is shorter than the other, trailing elements of the longer list
34259are ignored.
34260@end defun
34261
34262@defun expr-weight expr
34263Returns the ``weight'' of @var{expr}, basically a count of the total
34264number of objects and function calls that appear in @var{expr}. For
34265``primitive'' objects, this will be one.
34266@end defun
34267
34268@defun expr-height expr
34269Returns the ``height'' of @var{expr}, which is the deepest level to
34270which function calls are nested. (Note that @samp{@var{a} + @var{b}}
34271counts as a function call.) For primitive objects, this returns zero.
34272@end defun
34273
34274@defun polynomial-p expr var
34275Check if @var{expr} is a polynomial in variable (or sub-expression)
34276@var{var}. If so, return the degree of the polynomial, that is, the
34277highest power of @var{var} that appears in @var{expr}. For example,
34278for @samp{(x^2 + 3)^3 + 4} this would return 6. This function returns
34279@code{nil} unless @var{expr}, when expanded out by @kbd{a x}
34280(@code{calc-expand}), would consist of a sum of terms in which @var{var}
34281appears only raised to nonnegative integer powers. Note that if
34282@var{var} does not occur in @var{expr}, then @var{expr} is considered
34283a polynomial of degree 0.
34284@end defun
34285
34286@defun is-polynomial expr var degree loose
34287Check if @var{expr} is a polynomial in variable or sub-expression
34288@var{var}, and, if so, return a list representation of the polynomial
34289where the elements of the list are coefficients of successive powers of
34290@var{var}: @samp{@var{a} + @var{b} x + @var{c} x^3} would produce the
34291list @samp{(@var{a} @var{b} 0 @var{c})}, and @samp{(x + 1)^2} would
34292produce the list @samp{(1 2 1)}. The highest element of the list will
34293be non-zero, with the special exception that if @var{expr} is the
34294constant zero, the returned value will be @samp{(0)}. Return @code{nil}
34295if @var{expr} is not a polynomial in @var{var}. If @var{degree} is
34296specified, this will not consider polynomials of degree higher than that
34297value. This is a good precaution because otherwise an input of
34298@samp{(x+1)^1000} will cause a huge coefficient list to be built. If
34299@var{loose} is non-@code{nil}, then a looser definition of a polynomial
34300is used in which coefficients are no longer required not to depend on
34301@var{var}, but are only required not to take the form of polynomials
34302themselves. For example, @samp{sin(x) x^2 + cos(x)} is a loose
34303polynomial with coefficients @samp{((calcFunc-cos x) 0 (calcFunc-sin
34304x))}. The result will never be @code{nil} in loose mode, since any
34305expression can be interpreted as a ``constant'' loose polynomial.
34306@end defun
34307
34308@defun polynomial-base expr pred
34309Check if @var{expr} is a polynomial in any variable that occurs in it;
34310if so, return that variable. (If @var{expr} is a multivariate polynomial,
34311this chooses one variable arbitrarily.) If @var{pred} is specified, it should
34312be a Lisp function which is called as @samp{(@var{pred} @var{subexpr})},
34313and which should return true if @code{mpb-top-expr} (a global name for
34314the original @var{expr}) is a suitable polynomial in @var{subexpr}.
34315The default predicate uses @samp{(polynomial-p mpb-top-expr @var{subexpr})};
34316you can use @var{pred} to specify additional conditions. Or, you could
34317have @var{pred} build up a list of every suitable @var{subexpr} that
34318is found.
34319@end defun
34320
34321@defun poly-simplify poly
34322Simplify polynomial coefficient list @var{poly} by (destructively)
34323clipping off trailing zeros.
34324@end defun
34325
34326@defun poly-mix a ac b bc
34327Mix two polynomial lists @var{a} and @var{b} (in the form returned by
34328@code{is-polynomial}) in a linear combination with coefficient expressions
34329@var{ac} and @var{bc}. The result is a (not necessarily simplified)
34330polynomial list representing @samp{@var{ac} @var{a} + @var{bc} @var{b}}.
34331@end defun
34332
34333@defun poly-mul a b
34334Multiply two polynomial coefficient lists @var{a} and @var{b}. The
34335result will be in simplified form if the inputs were simplified.
34336@end defun
34337
34338@defun build-polynomial-expr poly var
34339Construct a Calc formula which represents the polynomial coefficient
34340list @var{poly} applied to variable @var{var}. The @kbd{a c}
34341(@code{calc-collect}) command uses @code{is-polynomial} to turn an
34342expression into a coefficient list, then @code{build-polynomial-expr}
34343to turn the list back into an expression in regular form.
34344@end defun
34345
34346@defun check-unit-name var
34347Check if @var{var} is a variable which can be interpreted as a unit
34348name. If so, return the units table entry for that unit. This
34349will be a list whose first element is the unit name (not counting
34350prefix characters) as a symbol and whose second element is the
34351Calc expression which defines the unit. (Refer to the Calc sources
34352for details on the remaining elements of this list.) If @var{var}
34353is not a variable or is not a unit name, return @code{nil}.
34354@end defun
34355
34356@defun units-in-expr-p expr sub-exprs
34357Return true if @var{expr} contains any variables which can be
34358interpreted as units. If @var{sub-exprs} is @code{t}, the entire
34359expression is searched. If @var{sub-exprs} is @code{nil}, this
34360checks whether @var{expr} is directly a units expression.
34361@end defun
34362
34363@defun single-units-in-expr-p expr
34364Check whether @var{expr} contains exactly one units variable. If so,
34365return the units table entry for the variable. If @var{expr} does
34366not contain any units, return @code{nil}. If @var{expr} contains
34367two or more units, return the symbol @code{wrong}.
34368@end defun
34369
34370@defun to-standard-units expr which
34371Convert units expression @var{expr} to base units. If @var{which}
34372is @code{nil}, use Calc's native base units. Otherwise, @var{which}
34373can specify a units system, which is a list of two-element lists,
34374where the first element is a Calc base symbol name and the second
34375is an expression to substitute for it.
34376@end defun
34377
34378@defun remove-units expr
34379Return a copy of @var{expr} with all units variables replaced by ones.
34380This expression is generally normalized before use.
34381@end defun
34382
34383@defun extract-units expr
34384Return a copy of @var{expr} with everything but units variables replaced
34385by ones.
34386@end defun
34387
34388@node Formatting Lisp Functions, Hooks, Symbolic Lisp Functions, Internals
34389@subsubsection I/O and Formatting Functions
34390
34391@noindent
34392The functions described here are responsible for parsing and formatting
34393Calc numbers and formulas.
34394
34395@defun calc-eval str sep arg1 arg2 @dots{}
34396This is the simplest interface to the Calculator from another Lisp program.
34397@xref{Calling Calc from Your Programs}.
34398@end defun
34399
34400@defun read-number str
34401If string @var{str} contains a valid Calc number, either integer,
34402fraction, float, or HMS form, this function parses and returns that
34403number. Otherwise, it returns @code{nil}.
34404@end defun
34405
34406@defun read-expr str
34407Read an algebraic expression from string @var{str}. If @var{str} does
34408not have the form of a valid expression, return a list of the form
34409@samp{(error @var{pos} @var{msg})} where @var{pos} is an integer index
34410into @var{str} of the general location of the error, and @var{msg} is
34411a string describing the problem.
34412@end defun
34413
34414@defun read-exprs str
34415Read a list of expressions separated by commas, and return it as a
34416Lisp list. If an error occurs in any expressions, an error list as
34417shown above is returned instead.
34418@end defun
34419
34420@defun calc-do-alg-entry initial prompt no-norm
34421Read an algebraic formula or formulas using the minibuffer. All
34422conventions of regular algebraic entry are observed. The return value
34423is a list of Calc formulas; there will be more than one if the user
34424entered a list of values separated by commas. The result is @code{nil}
34425if the user presses Return with a blank line. If @var{initial} is
34426given, it is a string which the minibuffer will initially contain.
34427If @var{prompt} is given, it is the prompt string to use; the default
34428is ``Algebraic:''. If @var{no-norm} is @code{t}, the formulas will
34429be returned exactly as parsed; otherwise, they will be passed through
34430@code{calc-normalize} first.
34431
34432To support the use of @kbd{$} characters in the algebraic entry, use
34433@code{let} to bind @code{calc-dollar-values} to a list of the values
34434to be substituted for @kbd{$}, @kbd{$$}, and so on, and bind
34435@code{calc-dollar-used} to 0. Upon return, @code{calc-dollar-used}
34436will have been changed to the highest number of consecutive @kbd{$}s
34437that actually appeared in the input.
34438@end defun
34439
34440@defun format-number a
34441Convert the real or complex number or HMS form @var{a} to string form.
34442@end defun
34443
34444@defun format-flat-expr a prec
34445Convert the arbitrary Calc number or formula @var{a} to string form,
34446in the style used by the trail buffer and the @code{calc-edit} command.
34447This is a simple format designed
34448mostly to guarantee the string is of a form that can be re-parsed by
34449@code{read-expr}. Most formatting modes, such as digit grouping,
34450complex number format, and point character, are ignored to ensure the
34451result will be re-readable. The @var{prec} parameter is normally 0; if
34452you pass a large integer like 1000 instead, the expression will be
34453surrounded by parentheses unless it is a plain number or variable name.
34454@end defun
34455
34456@defun format-nice-expr a width
34457This is like @code{format-flat-expr} (with @var{prec} equal to 0),
34458except that newlines will be inserted to keep lines down to the
34459specified @var{width}, and vectors that look like matrices or rewrite
34460rules are written in a pseudo-matrix format. The @code{calc-edit}
34461command uses this when only one stack entry is being edited.
34462@end defun
34463
34464@defun format-value a width
34465Convert the Calc number or formula @var{a} to string form, using the
34466format seen in the stack buffer. Beware the string returned may
34467not be re-readable by @code{read-expr}, for example, because of digit
34468grouping. Multi-line objects like matrices produce strings that
34469contain newline characters to separate the lines. The @var{w}
34470parameter, if given, is the target window size for which to format
34471the expressions. If @var{w} is omitted, the width of the Calculator
34472window is used.
34473@end defun
34474
34475@defun compose-expr a prec
34476Format the Calc number or formula @var{a} according to the current
34477language mode, returning a ``composition.'' To learn about the
34478structure of compositions, see the comments in the Calc source code.
34479You can specify the format of a given type of function call by putting
34480a @code{math-compose-@var{lang}} property on the function's symbol,
34481whose value is a Lisp function that takes @var{a} and @var{prec} as
34482arguments and returns a composition. Here @var{lang} is a language
34483mode name, one of @code{normal}, @code{big}, @code{c}, @code{pascal},
34484@code{fortran}, @code{tex}, @code{eqn}, @code{math}, or @code{maple}.
34485In Big mode, Calc actually tries @code{math-compose-big} first, then
34486tries @code{math-compose-normal}. If this property does not exist,
34487or if the function returns @code{nil}, the function is written in the
34488normal function-call notation for that language.
34489@end defun
34490
34491@defun composition-to-string c w
34492Convert a composition structure returned by @code{compose-expr} into
34493a string. Multi-line compositions convert to strings containing
34494newline characters. The target window size is given by @var{w}.
34495The @code{format-value} function basically calls @code{compose-expr}
34496followed by @code{composition-to-string}.
34497@end defun
34498
34499@defun comp-width c
34500Compute the width in characters of composition @var{c}.
34501@end defun
34502
34503@defun comp-height c
34504Compute the height in lines of composition @var{c}.
34505@end defun
34506
34507@defun comp-ascent c
34508Compute the portion of the height of composition @var{c} which is on or
34509above the baseline. For a one-line composition, this will be one.
34510@end defun
34511
34512@defun comp-descent c
34513Compute the portion of the height of composition @var{c} which is below
34514the baseline. For a one-line composition, this will be zero.
34515@end defun
34516
34517@defun comp-first-char c
34518If composition @var{c} is a ``flat'' composition, return the first
34519(leftmost) character of the composition as an integer. Otherwise,
34520return @code{nil}.
34521@end defun
34522
34523@defun comp-last-char c
34524If composition @var{c} is a ``flat'' composition, return the last
34525(rightmost) character, otherwise return @code{nil}.
34526@end defun
34527
34528@comment @node Lisp Variables, Hooks, Formatting Lisp Functions, Internals
34529@comment @subsubsection Lisp Variables
34530@comment
34531@comment @noindent
34532@comment (This section is currently unfinished.)
34533
34534@node Hooks, , Formatting Lisp Functions, Internals
34535@subsubsection Hooks
34536
34537@noindent
34538Hooks are variables which contain Lisp functions (or lists of functions)
34539which are called at various times. Calc defines a number of hooks
34540that help you to customize it in various ways. Calc uses the Lisp
34541function @code{run-hooks} to invoke the hooks shown below. Several
34542other customization-related variables are also described here.
34543
34544@defvar calc-load-hook
34545This hook is called at the end of @file{calc.el}, after the file has
34546been loaded, before any functions in it have been called, but after
34547@code{calc-mode-map} and similar variables have been set up.
34548@end defvar
34549
34550@defvar calc-ext-load-hook
34551This hook is called at the end of @file{calc-ext.el}.
34552@end defvar
34553
34554@defvar calc-start-hook
34555This hook is called as the last step in a @kbd{M-x calc} command.
34556At this point, the Calc buffer has been created and initialized if
34557necessary, the Calc window and trail window have been created,
34558and the ``Welcome to Calc'' message has been displayed.
34559@end defvar
34560
34561@defvar calc-mode-hook
34562This hook is called when the Calc buffer is being created. Usually
34563this will only happen once per Emacs session. The hook is called
34564after Emacs has switched to the new buffer, the mode-settings file
34565has been read if necessary, and all other buffer-local variables
34566have been set up. After this hook returns, Calc will perform a
34567@code{calc-refresh} operation, set up the mode line display, then
34568evaluate any deferred @code{calc-define} properties that have not
34569been evaluated yet.
34570@end defvar
34571
34572@defvar calc-trail-mode-hook
34573This hook is called when the Calc Trail buffer is being created.
34574It is called as the very last step of setting up the Trail buffer.
34575Like @code{calc-mode-hook}, this will normally happen only once
34576per Emacs session.
34577@end defvar
34578
34579@defvar calc-end-hook
34580This hook is called by @code{calc-quit}, generally because the user
34581presses @kbd{q} or @kbd{C-x * c} while in Calc. The Calc buffer will
34582be the current buffer. The hook is called as the very first
34583step, before the Calc window is destroyed.
34584@end defvar
34585
34586@defvar calc-window-hook
34587If this hook is non-@code{nil}, it is called to create the Calc window.
34588Upon return, this new Calc window should be the current window.
34589(The Calc buffer will already be the current buffer when the
34590hook is called.) If the hook is not defined, Calc will
34591generally use @code{split-window}, @code{set-window-buffer},
34592and @code{select-window} to create the Calc window.
34593@end defvar
34594
34595@defvar calc-trail-window-hook
34596If this hook is non-@code{nil}, it is called to create the Calc Trail
34597window. The variable @code{calc-trail-buffer} will contain the buffer
34598which the window should use. Unlike @code{calc-window-hook}, this hook
34599must @emph{not} switch into the new window.
34600@end defvar
34601
34602@defvar calc-embedded-mode-hook
34603This hook is called the first time that Embedded mode is entered.
34604@end defvar
34605
34606@defvar calc-embedded-new-buffer-hook
34607This hook is called each time that Embedded mode is entered in a
34608new buffer.
34609@end defvar
34610
34611@defvar calc-embedded-new-formula-hook
34612This hook is called each time that Embedded mode is enabled for a
34613new formula.
34614@end defvar
34615
34616@defvar calc-edit-mode-hook
34617This hook is called by @code{calc-edit} (and the other ``edit''
34618commands) when the temporary editing buffer is being created.
34619The buffer will have been selected and set up to be in
34620@code{calc-edit-mode}, but will not yet have been filled with
34621text. (In fact it may still have leftover text from a previous
34622@code{calc-edit} command.)
34623@end defvar
34624
34625@defvar calc-mode-save-hook
34626This hook is called by the @code{calc-save-modes} command,
34627after Calc's own mode features have been inserted into the
34628Calc init file and just before the ``End of mode settings''
34629message is inserted.
34630@end defvar
34631
34632@defvar calc-reset-hook
34633This hook is called after @kbd{C-x * 0} (@code{calc-reset}) has
34634reset all modes. The Calc buffer will be the current buffer.
34635@end defvar
34636
34637@defvar calc-other-modes
34638This variable contains a list of strings. The strings are
34639concatenated at the end of the modes portion of the Calc
34640mode line (after standard modes such as ``Deg'', ``Inv'' and
34641``Hyp''). Each string should be a short, single word followed
34642by a space. The variable is @code{nil} by default.
34643@end defvar
34644
34645@defvar calc-mode-map
34646This is the keymap that is used by Calc mode. The best time
34647to adjust it is probably in a @code{calc-mode-hook}. If the
34648Calc extensions package (@file{calc-ext.el}) has not yet been
34649loaded, many of these keys will be bound to @code{calc-missing-key},
34650which is a command that loads the extensions package and
34651``retypes'' the key. If your @code{calc-mode-hook} rebinds
34652one of these keys, it will probably be overridden when the
34653extensions are loaded.
34654@end defvar
34655
34656@defvar calc-digit-map
34657This is the keymap that is used during numeric entry. Numeric
34658entry uses the minibuffer, but this map binds every non-numeric
34659key to @code{calcDigit-nondigit} which generally calls
34660@code{exit-minibuffer} and ``retypes'' the key.
34661@end defvar
34662
34663@defvar calc-alg-ent-map
34664This is the keymap that is used during algebraic entry. This is
34665mostly a copy of @code{minibuffer-local-map}.
34666@end defvar
34667
34668@defvar calc-store-var-map
34669This is the keymap that is used during entry of variable names for
34670commands like @code{calc-store} and @code{calc-recall}. This is
34671mostly a copy of @code{minibuffer-local-completion-map}.
34672@end defvar
34673
34674@defvar calc-edit-mode-map
34675This is the (sparse) keymap used by @code{calc-edit} and other
34676temporary editing commands. It binds @key{RET}, @key{LFD},
34677and @kbd{C-c C-c} to @code{calc-edit-finish}.
34678@end defvar
34679
34680@defvar calc-mode-var-list
34681This is a list of variables which are saved by @code{calc-save-modes}.
34682Each entry is a list of two items, the variable (as a Lisp symbol)
34683and its default value. When modes are being saved, each variable
34684is compared with its default value (using @code{equal}) and any
34685non-default variables are written out.
34686@end defvar
34687
34688@defvar calc-local-var-list
34689This is a list of variables which should be buffer-local to the
34690Calc buffer. Each entry is a variable name (as a Lisp symbol).
34691These variables also have their default values manipulated by
34692the @code{calc} and @code{calc-quit} commands; @pxref{Multiple Calculators}.
34693Since @code{calc-mode-hook} is called after this list has been
34694used the first time, your hook should add a variable to the
34695list and also call @code{make-local-variable} itself.
34696@end defvar
34697
34698@node Copying, GNU Free Documentation License, Programming, Top
34699@appendix GNU GENERAL PUBLIC LICENSE
34700@include gpl.texi
34701
34702@node GNU Free Documentation License, Customizing Calc, Copying, Top
34703@appendix GNU Free Documentation License
34704@include doclicense.texi
34705
34706@node Customizing Calc, Reporting Bugs, GNU Free Documentation License, Top
34707@appendix Customizing Calc
34708
34709The usual prefix for Calc is the key sequence @kbd{C-x *}. If you wish
34710to use a different prefix, you can put
34711
34712@example
34713(global-set-key "NEWPREFIX" 'calc-dispatch)
34714@end example
34715
34716@noindent
34717in your .emacs file.
34718(@xref{Key Bindings,,Customizing Key Bindings,emacs,
34719The GNU Emacs Manual}, for more information on binding keys.)
34720A convenient way to start Calc is with @kbd{C-x * *}; to make it equally
34721convenient for users who use a different prefix, the prefix can be
34722followed by @kbd{=}, @kbd{&}, @kbd{#}, @kbd{\}, @kbd{/}, @kbd{+} or
34723@kbd{-} as well as @kbd{*} to start Calc, and so in many cases the last
34724character of the prefix can simply be typed twice.
34725
34726Calc is controlled by many variables, most of which can be reset
34727from within Calc. Some variables are less involved with actual
34728calculation, and can be set outside of Calc using Emacs's
34729customization facilities. These variables are listed below.
34730Typing @kbd{M-x customize-variable RET @var{variable-name} RET}
34731will bring up a buffer in which the variable's value can be redefined.
34732Typing @kbd{M-x customize-group RET calc RET} will bring up a buffer which
34733contains all of Calc's customizable variables. (These variables can
34734also be reset by putting the appropriate lines in your .emacs file;
34735@xref{Init File, ,Init File, emacs, The GNU Emacs Manual}.)
34736
34737Some of the customizable variables are regular expressions. A regular
34738expression is basically a pattern that Calc can search for.
34739See @ref{Regexp Search,, Regular Expression Search, emacs, The GNU Emacs Manual}
34740to see how regular expressions work.
34741
34742@defvar calc-settings-file
34743The variable @code{calc-settings-file} holds the file name in
34744which commands like @kbd{m m} and @kbd{Z P} store ``permanent''
34745definitions.
34746If @code{calc-settings-file} is not your user init file (typically
34747@file{~/.emacs}) and if the variable @code{calc-loaded-settings-file} is
34748@code{nil}, then Calc will automatically load your settings file (if it
34749exists) the first time Calc is invoked.
34750
34751The default value for this variable is @code{"~/.calc.el"}.
34752@end defvar
34753
34754@defvar calc-gnuplot-name
34755See @ref{Graphics}.@*
34756The variable @code{calc-gnuplot-name} should be the name of the
34757GNUPLOT program (a string). If you have GNUPLOT installed on your
34758system but Calc is unable to find it, you may need to set this
34759variable. You may also need to set some Lisp variables to show Calc how
34760to run GNUPLOT on your system, see @ref{Devices, ,Graphical Devices} .
34761The default value of @code{calc-gnuplot-name} is @code{"gnuplot"}.
34762@end defvar
34763
34764@defvar calc-gnuplot-plot-command
34765@defvarx calc-gnuplot-print-command
34766See @ref{Devices, ,Graphical Devices}.@*
34767The variables @code{calc-gnuplot-plot-command} and
34768@code{calc-gnuplot-print-command} represent system commands to
34769display and print the output of GNUPLOT, respectively. These may be
34770@code{nil} if no command is necessary, or strings which can include
34771@samp{%s} to signify the name of the file to be displayed or printed.
34772Or, these variables may contain Lisp expressions which are evaluated
34773to display or print the output.
34774
34775The default value of @code{calc-gnuplot-plot-command} is @code{nil},
34776and the default value of @code{calc-gnuplot-print-command} is
34777@code{"lp %s"}.
34778@end defvar
34779
34780@defvar calc-language-alist
34781See @ref{Basic Embedded Mode}.@*
34782The variable @code{calc-language-alist} controls the languages that
34783Calc will associate with major modes. When Calc embedded mode is
34784enabled, it will try to use the current major mode to
34785determine what language should be used. (This can be overridden using
34786Calc's mode changing commands, @xref{Mode Settings in Embedded Mode}.)
34787The variable @code{calc-language-alist} consists of a list of pairs of
34788the form @code{(@var{MAJOR-MODE} . @var{LANGUAGE})}; for example,
34789@code{(latex-mode . latex)} is one such pair. If Calc embedded is
34790activated in a buffer whose major mode is @var{MAJOR-MODE}, it will set itself
34791to use the language @var{LANGUAGE}.
34792
34793The default value of @code{calc-language-alist} is
34794@example
34795 ((latex-mode . latex)
34796 (tex-mode . tex)
34797 (plain-tex-mode . tex)
34798 (context-mode . tex)
34799 (nroff-mode . eqn)
34800 (pascal-mode . pascal)
34801 (c-mode . c)
34802 (c++-mode . c)
34803 (fortran-mode . fortran)
34804 (f90-mode . fortran))
34805@end example
34806@end defvar
34807
34808@defvar calc-embedded-announce-formula
34809@defvarx calc-embedded-announce-formula-alist
34810See @ref{Customizing Embedded Mode}.@*
34811The variable @code{calc-embedded-announce-formula} helps determine
34812what formulas @kbd{C-x * a} will activate in a buffer. It is a
34813regular expression, and when activating embedded formulas with
34814@kbd{C-x * a}, it will tell Calc that what follows is a formula to be
34815activated. (Calc also uses other patterns to find formulas, such as
34816@samp{=>} and @samp{:=}.)
34817
34818The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, which checks
34819for @samp{%Embed} followed by any number of lines beginning with
34820@samp{%} and a space.
34821
34822The variable @code{calc-embedded-announce-formula-alist} is used to
34823set @code{calc-embedded-announce-formula} to different regular
34824expressions depending on the major mode of the editing buffer.
34825It consists of a list of pairs of the form @code{(@var{MAJOR-MODE} .
34826@var{REGEXP})}, and its default value is
34827@example
34828 ((c++-mode . "//Embed\n\\(// .*\n\\)*")
34829 (c-mode . "/\\*Embed\\*/\n\\(/\\* .*\\*/\n\\)*")
34830 (f90-mode . "!Embed\n\\(! .*\n\\)*")
34831 (fortran-mode . "C Embed\n\\(C .*\n\\)*")
34832 (html-helper-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
34833 (html-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
34834 (nroff-mode . "\\\\\"Embed\n\\(\\\\\" .*\n\\)*")
34835 (pascal-mode . "@{Embed@}\n\\(@{.*@}\n\\)*")
34836 (sgml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
34837 (xml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
34838 (texinfo-mode . "@@c Embed\n\\(@@c .*\n\\)*"))
34839@end example
34840Any major modes added to @code{calc-embedded-announce-formula-alist}
34841should also be added to @code{calc-embedded-open-close-plain-alist}
34842and @code{calc-embedded-open-close-mode-alist}.
34843@end defvar
34844
34845@defvar calc-embedded-open-formula
34846@defvarx calc-embedded-close-formula
34847@defvarx calc-embedded-open-close-formula-alist
34848See @ref{Customizing Embedded Mode}.@*
34849The variables @code{calc-embedded-open-formula} and
8dc6104d 34850@code{calc-embedded-close-formula} control the region that Calc will
4009494e
GM
34851activate as a formula when Embedded mode is entered with @kbd{C-x * e}.
34852They are regular expressions;
34853Calc normally scans backward and forward in the buffer for the
34854nearest text matching these regular expressions to be the ``formula
34855delimiters''.
34856
34857The simplest delimiters are blank lines. Other delimiters that
34858Embedded mode understands by default are:
34859@enumerate
34860@item
34861The @TeX{} and La@TeX{} math delimiters @samp{$ $}, @samp{$$ $$},
34862@samp{\[ \]}, and @samp{\( \)};
34863@item
34864Lines beginning with @samp{\begin} and @samp{\end} (except matrix delimiters);
34865@item
34866Lines beginning with @samp{@@} (Texinfo delimiters).
34867@item
34868Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
34869@item
34870Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
34871@end enumerate
34872
34873The variable @code{calc-embedded-open-close-formula-alist} is used to
34874set @code{calc-embedded-open-formula} and
34875@code{calc-embedded-close-formula} to different regular
34876expressions depending on the major mode of the editing buffer.
34877It consists of a list of lists of the form
34878@code{(@var{MAJOR-MODE} @var{OPEN-FORMULA-REGEXP}
34879@var{CLOSE-FORMULA-REGEXP})}, and its default value is
34880@code{nil}.
34881@end defvar
34882
34883@defvar calc-embedded-open-word
34884@defvarx calc-embedded-close-word
34885@defvarx calc-embedded-open-close-word-alist
34886See @ref{Customizing Embedded Mode}.@*
34887The variables @code{calc-embedded-open-word} and
34888@code{calc-embedded-close-word} control the region that Calc will
34889activate when Embedded mode is entered with @kbd{C-x * w}. They are
34890regular expressions.
34891
34892The default values of @code{calc-embedded-open-word} and
34893@code{calc-embedded-close-word} are @code{"^\\|[^-+0-9.eE]"} and
34894@code{"$\\|[^-+0-9.eE]"} respectively.
34895
34896The variable @code{calc-embedded-open-close-word-alist} is used to
34897set @code{calc-embedded-open-word} and
34898@code{calc-embedded-close-word} to different regular
34899expressions depending on the major mode of the editing buffer.
34900It consists of a list of lists of the form
34901@code{(@var{MAJOR-MODE} @var{OPEN-WORD-REGEXP}
34902@var{CLOSE-WORD-REGEXP})}, and its default value is
34903@code{nil}.
34904@end defvar
34905
34906@defvar calc-embedded-open-plain
34907@defvarx calc-embedded-close-plain
34908@defvarx calc-embedded-open-close-plain-alist
34909See @ref{Customizing Embedded Mode}.@*
34910The variables @code{calc-embedded-open-plain} and
34911@code{calc-embedded-open-plain} are used to delimit ``plain''
34912formulas. Note that these are actual strings, not regular
34913expressions, because Calc must be able to write these string into a
34914buffer as well as to recognize them.
34915
34916The default string for @code{calc-embedded-open-plain} is
34917@code{"%%% "}, note the trailing space. The default string for
34918@code{calc-embedded-close-plain} is @code{" %%%\n"}, without
34919the trailing newline here, the first line of a Big mode formula
34920that followed might be shifted over with respect to the other lines.
34921
34922The variable @code{calc-embedded-open-close-plain-alist} is used to
34923set @code{calc-embedded-open-plain} and
34924@code{calc-embedded-close-plain} to different strings
34925depending on the major mode of the editing buffer.
34926It consists of a list of lists of the form
34927@code{(@var{MAJOR-MODE} @var{OPEN-PLAIN-STRING}
34928@var{CLOSE-PLAIN-STRING})}, and its default value is
34929@example
34930 ((c++-mode "// %% " " %%\n")
34931 (c-mode "/* %% " " %% */\n")
34932 (f90-mode "! %% " " %%\n")
34933 (fortran-mode "C %% " " %%\n")
34934 (html-helper-mode "<!-- %% " " %% -->\n")
34935 (html-mode "<!-- %% " " %% -->\n")
34936 (nroff-mode "\\\" %% " " %%\n")
34937 (pascal-mode "@{%% " " %%@}\n")
34938 (sgml-mode "<!-- %% " " %% -->\n")
34939 (xml-mode "<!-- %% " " %% -->\n")
34940 (texinfo-mode "@@c %% " " %%\n"))
34941@end example
34942Any major modes added to @code{calc-embedded-open-close-plain-alist}
34943should also be added to @code{calc-embedded-announce-formula-alist}
34944and @code{calc-embedded-open-close-mode-alist}.
34945@end defvar
34946
34947@defvar calc-embedded-open-new-formula
34948@defvarx calc-embedded-close-new-formula
34949@defvarx calc-embedded-open-close-new-formula-alist
34950See @ref{Customizing Embedded Mode}.@*
34951The variables @code{calc-embedded-open-new-formula} and
34952@code{calc-embedded-close-new-formula} are strings which are
34953inserted before and after a new formula when you type @kbd{C-x * f}.
34954
34955The default value of @code{calc-embedded-open-new-formula} is
34956@code{"\n\n"}. If this string begins with a newline character and the
34957@kbd{C-x * f} is typed at the beginning of a line, @kbd{C-x * f} will skip
34958this first newline to avoid introducing unnecessary blank lines in the
34959file. The default value of @code{calc-embedded-close-new-formula} is
34960also @code{"\n\n"}. The final newline is omitted by @w{@kbd{C-x * f}}
34961if typed at the end of a line. (It follows that if @kbd{C-x * f} is
34962typed on a blank line, both a leading opening newline and a trailing
34963closing newline are omitted.)
34964
34965The variable @code{calc-embedded-open-close-new-formula-alist} is used to
34966set @code{calc-embedded-open-new-formula} and
34967@code{calc-embedded-close-new-formula} to different strings
34968depending on the major mode of the editing buffer.
34969It consists of a list of lists of the form
34970@code{(@var{MAJOR-MODE} @var{OPEN-NEW-FORMULA-STRING}
34971@var{CLOSE-NEW-FORMULA-STRING})}, and its default value is
34972@code{nil}.
34973@end defvar
34974
34975@defvar calc-embedded-open-mode
34976@defvarx calc-embedded-close-mode
34977@defvarx calc-embedded-open-close-mode-alist
34978See @ref{Customizing Embedded Mode}.@*
34979The variables @code{calc-embedded-open-mode} and
34980@code{calc-embedded-close-mode} are strings which Calc will place before
34981and after any mode annotations that it inserts. Calc never scans for
34982these strings; Calc always looks for the annotation itself, so it is not
34983necessary to add them to user-written annotations.
34984
34985The default value of @code{calc-embedded-open-mode} is @code{"% "}
34986and the default value of @code{calc-embedded-close-mode} is
34987@code{"\n"}.
34988If you change the value of @code{calc-embedded-close-mode}, it is a good
34989idea still to end with a newline so that mode annotations will appear on
34990lines by themselves.
34991
34992The variable @code{calc-embedded-open-close-mode-alist} is used to
34993set @code{calc-embedded-open-mode} and
34994@code{calc-embedded-close-mode} to different strings
34995expressions depending on the major mode of the editing buffer.
34996It consists of a list of lists of the form
34997@code{(@var{MAJOR-MODE} @var{OPEN-MODE-STRING}
34998@var{CLOSE-MODE-STRING})}, and its default value is
34999@example
35000 ((c++-mode "// " "\n")
35001 (c-mode "/* " " */\n")
35002 (f90-mode "! " "\n")
35003 (fortran-mode "C " "\n")
35004 (html-helper-mode "<!-- " " -->\n")
35005 (html-mode "<!-- " " -->\n")
35006 (nroff-mode "\\\" " "\n")
35007 (pascal-mode "@{ " " @}\n")
35008 (sgml-mode "<!-- " " -->\n")
35009 (xml-mode "<!-- " " -->\n")
35010 (texinfo-mode "@@c " "\n"))
35011@end example
35012Any major modes added to @code{calc-embedded-open-close-mode-alist}
35013should also be added to @code{calc-embedded-announce-formula-alist}
35014and @code{calc-embedded-open-close-plain-alist}.
35015@end defvar
35016
35017@defvar calc-multiplication-has-precedence
35018The variable @code{calc-multiplication-has-precedence} determines
45b778a6
JB
35019whether multiplication has precedence over division in algebraic
35020formulas in normal language modes. If
35021@code{calc-multiplication-has-precedence} is non-@code{nil}, then
35022multiplication has precedence (and, for certain obscure reasons, is
35023right associative), and so for example @samp{a/b*c} will be interpreted
35024as @samp{a/(b*c)}. If @code{calc-multiplication-has-precedence} is
35025@code{nil}, then multiplication has the same precedence as division
35026(and, like division, is left associative), and so for example
4009494e
GM
35027@samp{a/b*c} will be interpreted as @samp{(a/b)*c}. The default value
35028of @code{calc-multiplication-has-precedence} is @code{t}.
35029@end defvar
35030
35031@node Reporting Bugs, Summary, Customizing Calc, Top
35032@appendix Reporting Bugs
35033
35034@noindent
35035If you find a bug in Calc, send e-mail to Jay Belanger,
35036
35037@example
35038jay.p.belanger@@gmail.com
35039@end example
35040
35041@noindent
35042There is an automatic command @kbd{M-x report-calc-bug} which helps
35043you to report bugs. This command prompts you for a brief subject
35044line, then leaves you in a mail editing buffer. Type @kbd{C-c C-c} to
35045send your mail. Make sure your subject line indicates that you are
35046reporting a Calc bug; this command sends mail to the maintainer's
35047regular mailbox.
35048
35049If you have suggestions for additional features for Calc, please send
35050them. Some have dared to suggest that Calc is already top-heavy with
35051features; this obviously cannot be the case, so if you have ideas, send
35052them right in.
35053
35054At the front of the source file, @file{calc.el}, is a list of ideas for
35055future work. If any enthusiastic souls wish to take it upon themselves
35056to work on these, please send a message (using @kbd{M-x report-calc-bug})
35057so any efforts can be coordinated.
35058
35059The latest version of Calc is available from Savannah, in the Emacs
35060CVS tree. See @uref{http://savannah.gnu.org/projects/emacs}.
35061
35062@c [summary]
35063@node Summary, Key Index, Reporting Bugs, Top
35064@appendix Calc Summary
35065
35066@noindent
35067This section includes a complete list of Calc 2.1 keystroke commands.
35068Each line lists the stack entries used by the command (top-of-stack
35069last), the keystrokes themselves, the prompts asked by the command,
35070and the result of the command (also with top-of-stack last).
35071The result is expressed using the equivalent algebraic function.
35072Commands which put no results on the stack show the full @kbd{M-x}
35073command name in that position. Numbers preceding the result or
35074command name refer to notes at the end.
35075
35076Algebraic functions and @kbd{M-x} commands that don't have corresponding
35077keystrokes are not listed in this summary.
35078@xref{Command Index}. @xref{Function Index}.
35079
35080@iftex
35081@begingroup
35082@tex
35083\vskip-2\baselineskip \null
35084\gdef\sumrow#1{\sumrowx#1\relax}%
35085\gdef\sumrowx#1\:#2\:#3\:#4\:#5\:#6\relax{%
35086\leavevmode%
35087{\smallfonts
35088\hbox to5em{\sl\hss#1}%
35089\hbox to5em{\tt#2\hss}%
35090\hbox to4em{\sl#3\hss}%
35091\hbox to5em{\rm\hss#4}%
35092\thinspace%
35093{\tt#5}%
35094{\sl#6}%
35095}}%
35096\gdef\sumlpar{{\rm(}}%
35097\gdef\sumrpar{{\rm)}}%
35098\gdef\sumcomma{{\rm,\thinspace}}%
35099\gdef\sumexcl{{\rm!}}%
35100\gdef\sumbreak{\vskip-2.5\baselineskip\goodbreak}%
35101\gdef\minus#1{{\tt-}}%
35102@end tex
35103@let@:=@sumsep
35104@let@r=@sumrow
35105@catcode`@(=@active @let(=@sumlpar
35106@catcode`@)=@active @let)=@sumrpar
35107@catcode`@,=@active @let,=@sumcomma
35108@catcode`@!=@active @let!=@sumexcl
35109@end iftex
35110@format
35111@iftex
35112@advance@baselineskip-2.5pt
35113@let@c@sumbreak
35114@end iftex
35115@r{ @: C-x * a @: @: 33 @:calc-embedded-activate@:}
35116@r{ @: C-x * b @: @: @:calc-big-or-small@:}
35117@r{ @: C-x * c @: @: @:calc@:}
35118@r{ @: C-x * d @: @: @:calc-embedded-duplicate@:}
35119@r{ @: C-x * e @: @: 34 @:calc-embedded@:}
35120@r{ @: C-x * f @:formula @: @:calc-embedded-new-formula@:}
35121@r{ @: C-x * g @: @: 35 @:calc-grab-region@:}
35122@r{ @: C-x * i @: @: @:calc-info@:}
35123@r{ @: C-x * j @: @: @:calc-embedded-select@:}
35124@r{ @: C-x * k @: @: @:calc-keypad@:}
35125@r{ @: C-x * l @: @: @:calc-load-everything@:}
35126@r{ @: C-x * m @: @: @:read-kbd-macro@:}
35127@r{ @: C-x * n @: @: 4 @:calc-embedded-next@:}
35128@r{ @: C-x * o @: @: @:calc-other-window@:}
35129@r{ @: C-x * p @: @: 4 @:calc-embedded-previous@:}
35130@r{ @: C-x * q @:formula @: @:quick-calc@:}
35131@r{ @: C-x * r @: @: 36 @:calc-grab-rectangle@:}
35132@r{ @: C-x * s @: @: @:calc-info-summary@:}
35133@r{ @: C-x * t @: @: @:calc-tutorial@:}
35134@r{ @: C-x * u @: @: @:calc-embedded-update-formula@:}
35135@r{ @: C-x * w @: @: @:calc-embedded-word@:}
35136@r{ @: C-x * x @: @: @:calc-quit@:}
35137@r{ @: C-x * y @: @:1,28,49 @:calc-copy-to-buffer@:}
35138@r{ @: C-x * z @: @: @:calc-user-invocation@:}
35139@r{ @: C-x * : @: @: 36 @:calc-grab-sum-down@:}
35140@r{ @: C-x * _ @: @: 36 @:calc-grab-sum-across@:}
35141@r{ @: C-x * ` @:editing @: 30 @:calc-embedded-edit@:}
35142@r{ @: C-x * 0 @:(zero) @: @:calc-reset@:}
35143
35144@c
35145@r{ @: 0-9 @:number @: @:@:number}
35146@r{ @: . @:number @: @:@:0.number}
35147@r{ @: _ @:number @: @:-@:number}
35148@r{ @: e @:number @: @:@:1e number}
35149@r{ @: # @:number @: @:@:current-radix@tfn{#}number}
35150@r{ @: P @:(in number) @: @:+/-@:}
35151@r{ @: M @:(in number) @: @:mod@:}
35152@r{ @: @@ ' " @: (in number)@: @:@:HMS form}
35153@r{ @: h m s @: (in number)@: @:@:HMS form}
35154
35155@c
35156@r{ @: ' @:formula @: 37,46 @:@:formula}
35157@r{ @: $ @:formula @: 37,46 @:$@:formula}
35158@r{ @: " @:string @: 37,46 @:@:string}
35159
35160@c
35161@r{ a b@: + @: @: 2 @:add@:(a,b) a+b}
35162@r{ a b@: - @: @: 2 @:sub@:(a,b) a@minus{}b}
35163@r{ a b@: * @: @: 2 @:mul@:(a,b) a b, a*b}
35164@r{ a b@: / @: @: 2 @:div@:(a,b) a/b}
35165@r{ a b@: ^ @: @: 2 @:pow@:(a,b) a^b}
35166@r{ a b@: I ^ @: @: 2 @:nroot@:(a,b) a^(1/b)}
35167@r{ a b@: % @: @: 2 @:mod@:(a,b) a%b}
35168@r{ a b@: \ @: @: 2 @:idiv@:(a,b) a\b}
35169@r{ a b@: : @: @: 2 @:fdiv@:(a,b)}
35170@r{ a b@: | @: @: 2 @:vconcat@:(a,b) a|b}
35171@r{ a b@: I | @: @: @:vconcat@:(b,a) b|a}
35172@r{ a b@: H | @: @: 2 @:append@:(a,b)}
35173@r{ a b@: I H | @: @: @:append@:(b,a)}
35174@r{ a@: & @: @: 1 @:inv@:(a) 1/a}
35175@r{ a@: ! @: @: 1 @:fact@:(a) a!}
35176@r{ a@: = @: @: 1 @:evalv@:(a)}
35177@r{ a@: M-% @: @: @:percent@:(a) a%}
35178
35179@c
8dc6104d
JB
35180@r{ ... a@: @summarykey{RET} @: @: 1 @:@:... a a}
35181@r{ ... a@: @summarykey{SPC} @: @: 1 @:@:... a a}
35182@r{... a b@: @summarykey{TAB} @: @: 3 @:@:... b a}
35183@r{. a b c@: M-@summarykey{TAB} @: @: 3 @:@:... b c a}
35184@r{... a b@: @summarykey{LFD} @: @: 1 @:@:... a b a}
35185@r{ ... a@: @summarykey{DEL} @: @: 1 @:@:...}
35186@r{... a b@: M-@summarykey{DEL} @: @: 1 @:@:... b}
35187@r{ @: M-@summarykey{RET} @: @: 4 @:calc-last-args@:}
4009494e
GM
35188@r{ a@: ` @:editing @: 1,30 @:calc-edit@:}
35189
35190@c
35191@r{ ... a@: C-d @: @: 1 @:@:...}
35192@r{ @: C-k @: @: 27 @:calc-kill@:}
35193@r{ @: C-w @: @: 27 @:calc-kill-region@:}
35194@r{ @: C-y @: @: @:calc-yank@:}
35195@r{ @: C-_ @: @: 4 @:calc-undo@:}
35196@r{ @: M-k @: @: 27 @:calc-copy-as-kill@:}
35197@r{ @: M-w @: @: 27 @:calc-copy-region-as-kill@:}
35198
35199@c
35200@r{ @: [ @: @: @:@:[...}
35201@r{[.. a b@: ] @: @: @:@:[a,b]}
35202@r{ @: ( @: @: @:@:(...}
35203@r{(.. a b@: ) @: @: @:@:(a,b)}
35204@r{ @: , @: @: @:@:vector or rect complex}
35205@r{ @: ; @: @: @:@:matrix or polar complex}
35206@r{ @: .. @: @: @:@:interval}
35207
35208@c
35209@r{ @: ~ @: @: @:calc-num-prefix@:}
35210@r{ @: < @: @: 4 @:calc-scroll-left@:}
35211@r{ @: > @: @: 4 @:calc-scroll-right@:}
35212@r{ @: @{ @: @: 4 @:calc-scroll-down@:}
35213@r{ @: @} @: @: 4 @:calc-scroll-up@:}
35214@r{ @: ? @: @: @:calc-help@:}
35215
35216@c
35217@r{ a@: n @: @: 1 @:neg@:(a) @minus{}a}
35218@r{ @: o @: @: 4 @:calc-realign@:}
35219@r{ @: p @:precision @: 31 @:calc-precision@:}
35220@r{ @: q @: @: @:calc-quit@:}
35221@r{ @: w @: @: @:calc-why@:}
35222@r{ @: x @:command @: @:M-x calc-@:command}
35223@r{ a@: y @: @:1,28,49 @:calc-copy-to-buffer@:}
35224
35225@c
35226@r{ a@: A @: @: 1 @:abs@:(a)}
35227@r{ a b@: B @: @: 2 @:log@:(a,b)}
35228@r{ a b@: I B @: @: 2 @:alog@:(a,b) b^a}
35229@r{ a@: C @: @: 1 @:cos@:(a)}
35230@r{ a@: I C @: @: 1 @:arccos@:(a)}
35231@r{ a@: H C @: @: 1 @:cosh@:(a)}
35232@r{ a@: I H C @: @: 1 @:arccosh@:(a)}
35233@r{ @: D @: @: 4 @:calc-redo@:}
35234@r{ a@: E @: @: 1 @:exp@:(a)}
35235@r{ a@: H E @: @: 1 @:exp10@:(a) 10.^a}
35236@r{ a@: F @: @: 1,11 @:floor@:(a,d)}
35237@r{ a@: I F @: @: 1,11 @:ceil@:(a,d)}
35238@r{ a@: H F @: @: 1,11 @:ffloor@:(a,d)}
35239@r{ a@: I H F @: @: 1,11 @:fceil@:(a,d)}
35240@r{ a@: G @: @: 1 @:arg@:(a)}
35241@r{ @: H @:command @: 32 @:@:Hyperbolic}
35242@r{ @: I @:command @: 32 @:@:Inverse}
35243@r{ a@: J @: @: 1 @:conj@:(a)}
35244@r{ @: K @:command @: 32 @:@:Keep-args}
35245@r{ a@: L @: @: 1 @:ln@:(a)}
35246@r{ a@: H L @: @: 1 @:log10@:(a)}
35247@r{ @: M @: @: @:calc-more-recursion-depth@:}
35248@r{ @: I M @: @: @:calc-less-recursion-depth@:}
35249@r{ a@: N @: @: 5 @:evalvn@:(a)}
35250@r{ @: P @: @: @:@:pi}
35251@r{ @: I P @: @: @:@:gamma}
35252@r{ @: H P @: @: @:@:e}
35253@r{ @: I H P @: @: @:@:phi}
35254@r{ a@: Q @: @: 1 @:sqrt@:(a)}
35255@r{ a@: I Q @: @: 1 @:sqr@:(a) a^2}
35256@r{ a@: R @: @: 1,11 @:round@:(a,d)}
35257@r{ a@: I R @: @: 1,11 @:trunc@:(a,d)}
35258@r{ a@: H R @: @: 1,11 @:fround@:(a,d)}
35259@r{ a@: I H R @: @: 1,11 @:ftrunc@:(a,d)}
35260@r{ a@: S @: @: 1 @:sin@:(a)}
35261@r{ a@: I S @: @: 1 @:arcsin@:(a)}
35262@r{ a@: H S @: @: 1 @:sinh@:(a)}
35263@r{ a@: I H S @: @: 1 @:arcsinh@:(a)}
35264@r{ a@: T @: @: 1 @:tan@:(a)}
35265@r{ a@: I T @: @: 1 @:arctan@:(a)}
35266@r{ a@: H T @: @: 1 @:tanh@:(a)}
35267@r{ a@: I H T @: @: 1 @:arctanh@:(a)}
35268@r{ @: U @: @: 4 @:calc-undo@:}
35269@r{ @: X @: @: 4 @:calc-call-last-kbd-macro@:}
35270
35271@c
35272@r{ a b@: a = @: @: 2 @:eq@:(a,b) a=b}
35273@r{ a b@: a # @: @: 2 @:neq@:(a,b) a!=b}
35274@r{ a b@: a < @: @: 2 @:lt@:(a,b) a<b}
35275@r{ a b@: a > @: @: 2 @:gt@:(a,b) a>b}
35276@r{ a b@: a [ @: @: 2 @:leq@:(a,b) a<=b}
35277@r{ a b@: a ] @: @: 2 @:geq@:(a,b) a>=b}
35278@r{ a b@: a @{ @: @: 2 @:in@:(a,b)}
35279@r{ a b@: a & @: @: 2,45 @:land@:(a,b) a&&b}
35280@r{ a b@: a | @: @: 2,45 @:lor@:(a,b) a||b}
35281@r{ a@: a ! @: @: 1,45 @:lnot@:(a) !a}
35282@r{ a b c@: a : @: @: 45 @:if@:(a,b,c) a?b:c}
35283@r{ a@: a . @: @: 1 @:rmeq@:(a)}
35284@r{ a@: a " @: @: 7,8 @:calc-expand-formula@:}
35285
35286@c
35287@r{ a@: a + @:i, l, h @: 6,38 @:sum@:(a,i,l,h)}
35288@r{ a@: a - @:i, l, h @: 6,38 @:asum@:(a,i,l,h)}
35289@r{ a@: a * @:i, l, h @: 6,38 @:prod@:(a,i,l,h)}
35290@r{ a b@: a _ @: @: 2 @:subscr@:(a,b) a_b}
35291
35292@c
35293@r{ a b@: a \ @: @: 2 @:pdiv@:(a,b)}
35294@r{ a b@: a % @: @: 2 @:prem@:(a,b)}
35295@r{ a b@: a / @: @: 2 @:pdivrem@:(a,b) [q,r]}
35296@r{ a b@: H a / @: @: 2 @:pdivide@:(a,b) q+r/b}
35297
35298@c
35299@r{ a@: a a @: @: 1 @:apart@:(a)}
35300@r{ a@: a b @:old, new @: 38 @:subst@:(a,old,new)}
35301@r{ a@: a c @:v @: 38 @:collect@:(a,v)}
35302@r{ a@: a d @:v @: 4,38 @:deriv@:(a,v)}
35303@r{ a@: H a d @:v @: 4,38 @:tderiv@:(a,v)}
35304@r{ a@: a e @: @: @:esimplify@:(a)}
35305@r{ a@: a f @: @: 1 @:factor@:(a)}
35306@r{ a@: H a f @: @: 1 @:factors@:(a)}
35307@r{ a b@: a g @: @: 2 @:pgcd@:(a,b)}
35308@r{ a@: a i @:v @: 38 @:integ@:(a,v)}
35309@r{ a@: a m @:pats @: 38 @:match@:(a,pats)}
35310@r{ a@: I a m @:pats @: 38 @:matchnot@:(a,pats)}
35311@r{ data x@: a p @: @: 28 @:polint@:(data,x)}
35312@r{ data x@: H a p @: @: 28 @:ratint@:(data,x)}
35313@r{ a@: a n @: @: 1 @:nrat@:(a)}
35314@r{ a@: a r @:rules @:4,8,38 @:rewrite@:(a,rules,n)}
35315@r{ a@: a s @: @: @:simplify@:(a)}
35316@r{ a@: a t @:v, n @: 31,39 @:taylor@:(a,v,n)}
35317@r{ a@: a v @: @: 7,8 @:calc-alg-evaluate@:}
35318@r{ a@: a x @: @: 4,8 @:expand@:(a)}
35319
35320@c
35321@r{ data@: a F @:model, vars @: 48 @:fit@:(m,iv,pv,data)}
35322@r{ data@: I a F @:model, vars @: 48 @:xfit@:(m,iv,pv,data)}
35323@r{ data@: H a F @:model, vars @: 48 @:efit@:(m,iv,pv,data)}
35324@r{ a@: a I @:v, l, h @: 38 @:ninteg@:(a,v,l,h)}
35325@r{ a b@: a M @:op @: 22 @:mapeq@:(op,a,b)}
35326@r{ a b@: I a M @:op @: 22 @:mapeqr@:(op,a,b)}
35327@r{ a b@: H a M @:op @: 22 @:mapeqp@:(op,a,b)}
35328@r{ a g@: a N @:v @: 38 @:minimize@:(a,v,g)}
35329@r{ a g@: H a N @:v @: 38 @:wminimize@:(a,v,g)}
35330@r{ a@: a P @:v @: 38 @:roots@:(a,v)}
35331@r{ a g@: a R @:v @: 38 @:root@:(a,v,g)}
35332@r{ a g@: H a R @:v @: 38 @:wroot@:(a,v,g)}
35333@r{ a@: a S @:v @: 38 @:solve@:(a,v)}
35334@r{ a@: I a S @:v @: 38 @:finv@:(a,v)}
35335@r{ a@: H a S @:v @: 38 @:fsolve@:(a,v)}
35336@r{ a@: I H a S @:v @: 38 @:ffinv@:(a,v)}
35337@r{ a@: a T @:i, l, h @: 6,38 @:table@:(a,i,l,h)}
35338@r{ a g@: a X @:v @: 38 @:maximize@:(a,v,g)}
35339@r{ a g@: H a X @:v @: 38 @:wmaximize@:(a,v,g)}
35340
35341@c
35342@r{ a b@: b a @: @: 9 @:and@:(a,b,w)}
35343@r{ a@: b c @: @: 9 @:clip@:(a,w)}
35344@r{ a b@: b d @: @: 9 @:diff@:(a,b,w)}
35345@r{ a@: b l @: @: 10 @:lsh@:(a,n,w)}
35346@r{ a n@: H b l @: @: 9 @:lsh@:(a,n,w)}
35347@r{ a@: b n @: @: 9 @:not@:(a,w)}
35348@r{ a b@: b o @: @: 9 @:or@:(a,b,w)}
35349@r{ v@: b p @: @: 1 @:vpack@:(v)}
35350@r{ a@: b r @: @: 10 @:rsh@:(a,n,w)}
35351@r{ a n@: H b r @: @: 9 @:rsh@:(a,n,w)}
35352@r{ a@: b t @: @: 10 @:rot@:(a,n,w)}
35353@r{ a n@: H b t @: @: 9 @:rot@:(a,n,w)}
35354@r{ a@: b u @: @: 1 @:vunpack@:(a)}
35355@r{ @: b w @:w @: 9,50 @:calc-word-size@:}
35356@r{ a b@: b x @: @: 9 @:xor@:(a,b,w)}
35357
35358@c
35359@r{c s l p@: b D @: @: @:ddb@:(c,s,l,p)}
35360@r{ r n p@: b F @: @: @:fv@:(r,n,p)}
35361@r{ r n p@: I b F @: @: @:fvb@:(r,n,p)}
35362@r{ r n p@: H b F @: @: @:fvl@:(r,n,p)}
35363@r{ v@: b I @: @: 19 @:irr@:(v)}
35364@r{ v@: I b I @: @: 19 @:irrb@:(v)}
35365@r{ a@: b L @: @: 10 @:ash@:(a,n,w)}
35366@r{ a n@: H b L @: @: 9 @:ash@:(a,n,w)}
35367@r{ r n a@: b M @: @: @:pmt@:(r,n,a)}
35368@r{ r n a@: I b M @: @: @:pmtb@:(r,n,a)}
35369@r{ r n a@: H b M @: @: @:pmtl@:(r,n,a)}
35370@r{ r v@: b N @: @: 19 @:npv@:(r,v)}
35371@r{ r v@: I b N @: @: 19 @:npvb@:(r,v)}
35372@r{ r n p@: b P @: @: @:pv@:(r,n,p)}
35373@r{ r n p@: I b P @: @: @:pvb@:(r,n,p)}
35374@r{ r n p@: H b P @: @: @:pvl@:(r,n,p)}
35375@r{ a@: b R @: @: 10 @:rash@:(a,n,w)}
35376@r{ a n@: H b R @: @: 9 @:rash@:(a,n,w)}
35377@r{ c s l@: b S @: @: @:sln@:(c,s,l)}
35378@r{ n p a@: b T @: @: @:rate@:(n,p,a)}
35379@r{ n p a@: I b T @: @: @:rateb@:(n,p,a)}
35380@r{ n p a@: H b T @: @: @:ratel@:(n,p,a)}
35381@r{c s l p@: b Y @: @: @:syd@:(c,s,l,p)}
35382
35383@r{ r p a@: b # @: @: @:nper@:(r,p,a)}
35384@r{ r p a@: I b # @: @: @:nperb@:(r,p,a)}
35385@r{ r p a@: H b # @: @: @:nperl@:(r,p,a)}
35386@r{ a b@: b % @: @: @:relch@:(a,b)}
35387
35388@c
35389@r{ a@: c c @: @: 5 @:pclean@:(a,p)}
35390@r{ a@: c 0-9 @: @: @:pclean@:(a,p)}
35391@r{ a@: H c c @: @: 5 @:clean@:(a,p)}
35392@r{ a@: H c 0-9 @: @: @:clean@:(a,p)}
35393@r{ a@: c d @: @: 1 @:deg@:(a)}
35394@r{ a@: c f @: @: 1 @:pfloat@:(a)}
35395@r{ a@: H c f @: @: 1 @:float@:(a)}
35396@r{ a@: c h @: @: 1 @:hms@:(a)}
35397@r{ a@: c p @: @: @:polar@:(a)}
35398@r{ a@: I c p @: @: @:rect@:(a)}
35399@r{ a@: c r @: @: 1 @:rad@:(a)}
35400
35401@c
35402@r{ a@: c F @: @: 5 @:pfrac@:(a,p)}
35403@r{ a@: H c F @: @: 5 @:frac@:(a,p)}
35404
35405@c
35406@r{ a@: c % @: @: @:percent@:(a*100)}
35407
35408@c
35409@r{ @: d . @:char @: 50 @:calc-point-char@:}
35410@r{ @: d , @:char @: 50 @:calc-group-char@:}
35411@r{ @: d < @: @: 13,50 @:calc-left-justify@:}
35412@r{ @: d = @: @: 13,50 @:calc-center-justify@:}
35413@r{ @: d > @: @: 13,50 @:calc-right-justify@:}
35414@r{ @: d @{ @:label @: 50 @:calc-left-label@:}
35415@r{ @: d @} @:label @: 50 @:calc-right-label@:}
35416@r{ @: d [ @: @: 4 @:calc-truncate-up@:}
35417@r{ @: d ] @: @: 4 @:calc-truncate-down@:}
35418@r{ @: d " @: @: 12,50 @:calc-display-strings@:}
8dc6104d
JB
35419@r{ @: d @summarykey{SPC} @: @: @:calc-refresh@:}
35420@r{ @: d @summarykey{RET} @: @: 1 @:calc-refresh-top@:}
4009494e
GM
35421
35422@c
35423@r{ @: d 0 @: @: 50 @:calc-decimal-radix@:}
35424@r{ @: d 2 @: @: 50 @:calc-binary-radix@:}
35425@r{ @: d 6 @: @: 50 @:calc-hex-radix@:}
35426@r{ @: d 8 @: @: 50 @:calc-octal-radix@:}
35427
35428@c
35429@r{ @: d b @: @:12,13,50 @:calc-line-breaking@:}
35430@r{ @: d c @: @: 50 @:calc-complex-notation@:}
35431@r{ @: d d @:format @: 50 @:calc-date-notation@:}
35432@r{ @: d e @: @: 5,50 @:calc-eng-notation@:}
35433@r{ @: d f @:num @: 31,50 @:calc-fix-notation@:}
35434@r{ @: d g @: @:12,13,50 @:calc-group-digits@:}
35435@r{ @: d h @:format @: 50 @:calc-hms-notation@:}
35436@r{ @: d i @: @: 50 @:calc-i-notation@:}
35437@r{ @: d j @: @: 50 @:calc-j-notation@:}
35438@r{ @: d l @: @: 12,50 @:calc-line-numbering@:}
35439@r{ @: d n @: @: 5,50 @:calc-normal-notation@:}
35440@r{ @: d o @:format @: 50 @:calc-over-notation@:}
35441@r{ @: d p @: @: 12,50 @:calc-show-plain@:}
35442@r{ @: d r @:radix @: 31,50 @:calc-radix@:}
35443@r{ @: d s @: @: 5,50 @:calc-sci-notation@:}
35444@r{ @: d t @: @: 27 @:calc-truncate-stack@:}
35445@r{ @: d w @: @: 12,13 @:calc-auto-why@:}
35446@r{ @: d z @: @: 12,50 @:calc-leading-zeros@:}
35447
35448@c
35449@r{ @: d B @: @: 50 @:calc-big-language@:}
35450@r{ @: d C @: @: 50 @:calc-c-language@:}
35451@r{ @: d E @: @: 50 @:calc-eqn-language@:}
35452@r{ @: d F @: @: 50 @:calc-fortran-language@:}
35453@r{ @: d M @: @: 50 @:calc-mathematica-language@:}
35454@r{ @: d N @: @: 50 @:calc-normal-language@:}
35455@r{ @: d O @: @: 50 @:calc-flat-language@:}
35456@r{ @: d P @: @: 50 @:calc-pascal-language@:}
35457@r{ @: d T @: @: 50 @:calc-tex-language@:}
35458@r{ @: d L @: @: 50 @:calc-latex-language@:}
35459@r{ @: d U @: @: 50 @:calc-unformatted-language@:}
35460@r{ @: d W @: @: 50 @:calc-maple-language@:}
35461
35462@c
35463@r{ a@: f [ @: @: 4 @:decr@:(a,n)}
35464@r{ a@: f ] @: @: 4 @:incr@:(a,n)}
35465
35466@c
35467@r{ a b@: f b @: @: 2 @:beta@:(a,b)}
35468@r{ a@: f e @: @: 1 @:erf@:(a)}
35469@r{ a@: I f e @: @: 1 @:erfc@:(a)}
35470@r{ a@: f g @: @: 1 @:gamma@:(a)}
35471@r{ a b@: f h @: @: 2 @:hypot@:(a,b)}
35472@r{ a@: f i @: @: 1 @:im@:(a)}
35473@r{ n a@: f j @: @: 2 @:besJ@:(n,a)}
35474@r{ a b@: f n @: @: 2 @:min@:(a,b)}
35475@r{ a@: f r @: @: 1 @:re@:(a)}
35476@r{ a@: f s @: @: 1 @:sign@:(a)}
35477@r{ a b@: f x @: @: 2 @:max@:(a,b)}
35478@r{ n a@: f y @: @: 2 @:besY@:(n,a)}
35479
35480@c
35481@r{ a@: f A @: @: 1 @:abssqr@:(a)}
35482@r{ x a b@: f B @: @: @:betaI@:(x,a,b)}
35483@r{ x a b@: H f B @: @: @:betaB@:(x,a,b)}
35484@r{ a@: f E @: @: 1 @:expm1@:(a)}
35485@r{ a x@: f G @: @: 2 @:gammaP@:(a,x)}
35486@r{ a x@: I f G @: @: 2 @:gammaQ@:(a,x)}
35487@r{ a x@: H f G @: @: 2 @:gammag@:(a,x)}
35488@r{ a x@: I H f G @: @: 2 @:gammaG@:(a,x)}
35489@r{ a b@: f I @: @: 2 @:ilog@:(a,b)}
35490@r{ a b@: I f I @: @: 2 @:alog@:(a,b) b^a}
35491@r{ a@: f L @: @: 1 @:lnp1@:(a)}
35492@r{ a@: f M @: @: 1 @:mant@:(a)}
35493@r{ a@: f Q @: @: 1 @:isqrt@:(a)}
35494@r{ a@: I f Q @: @: 1 @:sqr@:(a) a^2}
35495@r{ a n@: f S @: @: 2 @:scf@:(a,n)}
35496@r{ y x@: f T @: @: @:arctan2@:(y,x)}
35497@r{ a@: f X @: @: 1 @:xpon@:(a)}
35498
35499@c
35500@r{ x y@: g a @: @: 28,40 @:calc-graph-add@:}
35501@r{ @: g b @: @: 12 @:calc-graph-border@:}
35502@r{ @: g c @: @: @:calc-graph-clear@:}
35503@r{ @: g d @: @: 41 @:calc-graph-delete@:}
35504@r{ x y@: g f @: @: 28,40 @:calc-graph-fast@:}
35505@r{ @: g g @: @: 12 @:calc-graph-grid@:}
35506@r{ @: g h @:title @: @:calc-graph-header@:}
35507@r{ @: g j @: @: 4 @:calc-graph-juggle@:}
35508@r{ @: g k @: @: 12 @:calc-graph-key@:}
35509@r{ @: g l @: @: 12 @:calc-graph-log-x@:}
35510@r{ @: g n @:name @: @:calc-graph-name@:}
35511@r{ @: g p @: @: 42 @:calc-graph-plot@:}
35512@r{ @: g q @: @: @:calc-graph-quit@:}
35513@r{ @: g r @:range @: @:calc-graph-range-x@:}
35514@r{ @: g s @: @: 12,13 @:calc-graph-line-style@:}
35515@r{ @: g t @:title @: @:calc-graph-title-x@:}
35516@r{ @: g v @: @: @:calc-graph-view-commands@:}
35517@r{ @: g x @:display @: @:calc-graph-display@:}
35518@r{ @: g z @: @: 12 @:calc-graph-zero-x@:}
35519
35520@c
35521@r{ x y z@: g A @: @: 28,40 @:calc-graph-add-3d@:}
35522@r{ @: g C @:command @: @:calc-graph-command@:}
35523@r{ @: g D @:device @: 43,44 @:calc-graph-device@:}
35524@r{ x y z@: g F @: @: 28,40 @:calc-graph-fast-3d@:}
35525@r{ @: g H @: @: 12 @:calc-graph-hide@:}
35526@r{ @: g K @: @: @:calc-graph-kill@:}
35527@r{ @: g L @: @: 12 @:calc-graph-log-y@:}
35528@r{ @: g N @:number @: 43,51 @:calc-graph-num-points@:}
35529@r{ @: g O @:filename @: 43,44 @:calc-graph-output@:}
35530@r{ @: g P @: @: 42 @:calc-graph-print@:}
35531@r{ @: g R @:range @: @:calc-graph-range-y@:}
35532@r{ @: g S @: @: 12,13 @:calc-graph-point-style@:}
35533@r{ @: g T @:title @: @:calc-graph-title-y@:}
35534@r{ @: g V @: @: @:calc-graph-view-trail@:}
35535@r{ @: g X @:format @: @:calc-graph-geometry@:}
35536@r{ @: g Z @: @: 12 @:calc-graph-zero-y@:}
35537
35538@c
35539@r{ @: g C-l @: @: 12 @:calc-graph-log-z@:}
35540@r{ @: g C-r @:range @: @:calc-graph-range-z@:}
35541@r{ @: g C-t @:title @: @:calc-graph-title-z@:}
35542
35543@c
35544@r{ @: h b @: @: @:calc-describe-bindings@:}
35545@r{ @: h c @:key @: @:calc-describe-key-briefly@:}
35546@r{ @: h f @:function @: @:calc-describe-function@:}
35547@r{ @: h h @: @: @:calc-full-help@:}
35548@r{ @: h i @: @: @:calc-info@:}
35549@r{ @: h k @:key @: @:calc-describe-key@:}
35550@r{ @: h n @: @: @:calc-view-news@:}
35551@r{ @: h s @: @: @:calc-info-summary@:}
35552@r{ @: h t @: @: @:calc-tutorial@:}
35553@r{ @: h v @:var @: @:calc-describe-variable@:}
35554
35555@c
35556@r{ @: j 1-9 @: @: @:calc-select-part@:}
8dc6104d
JB
35557@r{ @: j @summarykey{RET} @: @: 27 @:calc-copy-selection@:}
35558@r{ @: j @summarykey{DEL} @: @: 27 @:calc-del-selection@:}
4009494e
GM
35559@r{ @: j ' @:formula @: 27 @:calc-enter-selection@:}
35560@r{ @: j ` @:editing @: 27,30 @:calc-edit-selection@:}
35561@r{ @: j " @: @: 7,27 @:calc-sel-expand-formula@:}
35562
35563@c
35564@r{ @: j + @:formula @: 27 @:calc-sel-add-both-sides@:}
35565@r{ @: j - @:formula @: 27 @:calc-sel-sub-both-sides@:}
35566@r{ @: j * @:formula @: 27 @:calc-sel-mul-both-sides@:}
35567@r{ @: j / @:formula @: 27 @:calc-sel-div-both-sides@:}
35568@r{ @: j & @: @: 27 @:calc-sel-invert@:}
35569
35570@c
35571@r{ @: j a @: @: 27 @:calc-select-additional@:}
35572@r{ @: j b @: @: 12 @:calc-break-selections@:}
35573@r{ @: j c @: @: @:calc-clear-selections@:}
35574@r{ @: j d @: @: 12,50 @:calc-show-selections@:}
35575@r{ @: j e @: @: 12 @:calc-enable-selections@:}
35576@r{ @: j l @: @: 4,27 @:calc-select-less@:}
35577@r{ @: j m @: @: 4,27 @:calc-select-more@:}
35578@r{ @: j n @: @: 4 @:calc-select-next@:}
35579@r{ @: j o @: @: 4,27 @:calc-select-once@:}
35580@r{ @: j p @: @: 4 @:calc-select-previous@:}
35581@r{ @: j r @:rules @:4,8,27 @:calc-rewrite-selection@:}
35582@r{ @: j s @: @: 4,27 @:calc-select-here@:}
35583@r{ @: j u @: @: 27 @:calc-unselect@:}
35584@r{ @: j v @: @: 7,27 @:calc-sel-evaluate@:}
35585
35586@c
35587@r{ @: j C @: @: 27 @:calc-sel-commute@:}
35588@r{ @: j D @: @: 4,27 @:calc-sel-distribute@:}
35589@r{ @: j E @: @: 27 @:calc-sel-jump-equals@:}
35590@r{ @: j I @: @: 27 @:calc-sel-isolate@:}
35591@r{ @: H j I @: @: 27 @:calc-sel-isolate@: (full)}
35592@r{ @: j L @: @: 4,27 @:calc-commute-left@:}
35593@r{ @: j M @: @: 27 @:calc-sel-merge@:}
35594@r{ @: j N @: @: 27 @:calc-sel-negate@:}
35595@r{ @: j O @: @: 4,27 @:calc-select-once-maybe@:}
35596@r{ @: j R @: @: 4,27 @:calc-commute-right@:}
35597@r{ @: j S @: @: 4,27 @:calc-select-here-maybe@:}
35598@r{ @: j U @: @: 27 @:calc-sel-unpack@:}
35599
35600@c
35601@r{ @: k a @: @: @:calc-random-again@:}
35602@r{ n@: k b @: @: 1 @:bern@:(n)}
35603@r{ n x@: H k b @: @: 2 @:bern@:(n,x)}
35604@r{ n m@: k c @: @: 2 @:choose@:(n,m)}
35605@r{ n m@: H k c @: @: 2 @:perm@:(n,m)}
35606@r{ n@: k d @: @: 1 @:dfact@:(n) n!!}
35607@r{ n@: k e @: @: 1 @:euler@:(n)}
35608@r{ n x@: H k e @: @: 2 @:euler@:(n,x)}
35609@r{ n@: k f @: @: 4 @:prfac@:(n)}
35610@r{ n m@: k g @: @: 2 @:gcd@:(n,m)}
35611@r{ m n@: k h @: @: 14 @:shuffle@:(n,m)}
35612@r{ n m@: k l @: @: 2 @:lcm@:(n,m)}
35613@r{ n@: k m @: @: 1 @:moebius@:(n)}
35614@r{ n@: k n @: @: 4 @:nextprime@:(n)}
35615@r{ n@: I k n @: @: 4 @:prevprime@:(n)}
35616@r{ n@: k p @: @: 4,28 @:calc-prime-test@:}
35617@r{ m@: k r @: @: 14 @:random@:(m)}
35618@r{ n m@: k s @: @: 2 @:stir1@:(n,m)}
35619@r{ n m@: H k s @: @: 2 @:stir2@:(n,m)}
35620@r{ n@: k t @: @: 1 @:totient@:(n)}
35621
35622@c
35623@r{ n p x@: k B @: @: @:utpb@:(x,n,p)}
35624@r{ n p x@: I k B @: @: @:ltpb@:(x,n,p)}
35625@r{ v x@: k C @: @: @:utpc@:(x,v)}
35626@r{ v x@: I k C @: @: @:ltpc@:(x,v)}
35627@r{ n m@: k E @: @: @:egcd@:(n,m)}
35628@r{v1 v2 x@: k F @: @: @:utpf@:(x,v1,v2)}
35629@r{v1 v2 x@: I k F @: @: @:ltpf@:(x,v1,v2)}
35630@r{ m s x@: k N @: @: @:utpn@:(x,m,s)}
35631@r{ m s x@: I k N @: @: @:ltpn@:(x,m,s)}
35632@r{ m x@: k P @: @: @:utpp@:(x,m)}
35633@r{ m x@: I k P @: @: @:ltpp@:(x,m)}
35634@r{ v x@: k T @: @: @:utpt@:(x,v)}
35635@r{ v x@: I k T @: @: @:ltpt@:(x,v)}
35636
35637@c
35638@r{ @: m a @: @: 12,13 @:calc-algebraic-mode@:}
35639@r{ @: m d @: @: @:calc-degrees-mode@:}
35640@r{ @: m e @: @: @:calc-embedded-preserve-modes@:}
35641@r{ @: m f @: @: 12 @:calc-frac-mode@:}
35642@r{ @: m g @: @: 52 @:calc-get-modes@:}
35643@r{ @: m h @: @: @:calc-hms-mode@:}
35644@r{ @: m i @: @: 12,13 @:calc-infinite-mode@:}
35645@r{ @: m m @: @: @:calc-save-modes@:}
35646@r{ @: m p @: @: 12 @:calc-polar-mode@:}
35647@r{ @: m r @: @: @:calc-radians-mode@:}
35648@r{ @: m s @: @: 12 @:calc-symbolic-mode@:}
35649@r{ @: m t @: @: 12 @:calc-total-algebraic-mode@:}
35650@r{ @: m v @: @: 12,13 @:calc-matrix-mode@:}
35651@r{ @: m w @: @: 13 @:calc-working@:}
35652@r{ @: m x @: @: @:calc-always-load-extensions@:}
35653
35654@c
35655@r{ @: m A @: @: 12 @:calc-alg-simplify-mode@:}
35656@r{ @: m B @: @: 12 @:calc-bin-simplify-mode@:}
35657@r{ @: m C @: @: 12 @:calc-auto-recompute@:}
35658@r{ @: m D @: @: @:calc-default-simplify-mode@:}
35659@r{ @: m E @: @: 12 @:calc-ext-simplify-mode@:}
35660@r{ @: m F @:filename @: 13 @:calc-settings-file-name@:}
35661@r{ @: m N @: @: 12 @:calc-num-simplify-mode@:}
35662@r{ @: m O @: @: 12 @:calc-no-simplify-mode@:}
35663@r{ @: m R @: @: 12,13 @:calc-mode-record-mode@:}
35664@r{ @: m S @: @: 12 @:calc-shift-prefix@:}
35665@r{ @: m U @: @: 12 @:calc-units-simplify-mode@:}
35666
538c2573
JB
35667@c
35668@r{ @: r s @:register @: 27 @:calc-copy-to-register@:}
35669@r{ @: r i @:register @: @:calc-insert-register@:}
35670
4009494e
GM
35671@c
35672@r{ @: s c @:var1, var2 @: 29 @:calc-copy-variable@:}
35673@r{ @: s d @:var, decl @: @:calc-declare-variable@:}
35674@r{ @: s e @:var, editing @: 29,30 @:calc-edit-variable@:}
35675@r{ @: s i @:buffer @: @:calc-insert-variables@:}
35676@r{ @: s k @:const, var @: 29 @:calc-copy-special-constant@:}
35677@r{ a b@: s l @:var @: 29 @:@:a (letting var=b)}
35678@r{ a ...@: s m @:op, var @: 22,29 @:calc-store-map@:}
35679@r{ @: s n @:var @: 29,47 @:calc-store-neg@: (v/-1)}
35680@r{ @: s p @:var @: 29 @:calc-permanent-variable@:}
35681@r{ @: s r @:var @: 29 @:@:v (recalled value)}
35682@r{ @: r 0-9 @: @: @:calc-recall-quick@:}
35683@r{ a@: s s @:var @: 28,29 @:calc-store@:}
35684@r{ a@: s 0-9 @: @: @:calc-store-quick@:}
35685@r{ a@: s t @:var @: 29 @:calc-store-into@:}
35686@r{ a@: t 0-9 @: @: @:calc-store-into-quick@:}
35687@r{ @: s u @:var @: 29 @:calc-unstore@:}
35688@r{ a@: s x @:var @: 29 @:calc-store-exchange@:}
35689
35690@c
35691@r{ @: s A @:editing @: 30 @:calc-edit-AlgSimpRules@:}
35692@r{ @: s D @:editing @: 30 @:calc-edit-Decls@:}
35693@r{ @: s E @:editing @: 30 @:calc-edit-EvalRules@:}
35694@r{ @: s F @:editing @: 30 @:calc-edit-FitRules@:}
35695@r{ @: s G @:editing @: 30 @:calc-edit-GenCount@:}
35696@r{ @: s H @:editing @: 30 @:calc-edit-Holidays@:}
35697@r{ @: s I @:editing @: 30 @:calc-edit-IntegLimit@:}
35698@r{ @: s L @:editing @: 30 @:calc-edit-LineStyles@:}
35699@r{ @: s P @:editing @: 30 @:calc-edit-PointStyles@:}
35700@r{ @: s R @:editing @: 30 @:calc-edit-PlotRejects@:}
35701@r{ @: s T @:editing @: 30 @:calc-edit-TimeZone@:}
35702@r{ @: s U @:editing @: 30 @:calc-edit-Units@:}
35703@r{ @: s X @:editing @: 30 @:calc-edit-ExtSimpRules@:}
35704
35705@c
35706@r{ a@: s + @:var @: 29,47 @:calc-store-plus@: (v+a)}
35707@r{ a@: s - @:var @: 29,47 @:calc-store-minus@: (v-a)}
35708@r{ a@: s * @:var @: 29,47 @:calc-store-times@: (v*a)}
35709@r{ a@: s / @:var @: 29,47 @:calc-store-div@: (v/a)}
35710@r{ a@: s ^ @:var @: 29,47 @:calc-store-power@: (v^a)}
35711@r{ a@: s | @:var @: 29,47 @:calc-store-concat@: (v|a)}
35712@r{ @: s & @:var @: 29,47 @:calc-store-inv@: (v^-1)}
35713@r{ @: s [ @:var @: 29,47 @:calc-store-decr@: (v-1)}
35714@r{ @: s ] @:var @: 29,47 @:calc-store-incr@: (v-(-1))}
35715@r{ a b@: s : @: @: 2 @:assign@:(a,b) a @tfn{:=} b}
35716@r{ a@: s = @: @: 1 @:evalto@:(a,b) a @tfn{=>}}
35717
35718@c
35719@r{ @: t [ @: @: 4 @:calc-trail-first@:}
35720@r{ @: t ] @: @: 4 @:calc-trail-last@:}
35721@r{ @: t < @: @: 4 @:calc-trail-scroll-left@:}
35722@r{ @: t > @: @: 4 @:calc-trail-scroll-right@:}
35723@r{ @: t . @: @: 12 @:calc-full-trail-vectors@:}
35724
35725@c
35726@r{ @: t b @: @: 4 @:calc-trail-backward@:}
35727@r{ @: t d @: @: 12,50 @:calc-trail-display@:}
35728@r{ @: t f @: @: 4 @:calc-trail-forward@:}
35729@r{ @: t h @: @: @:calc-trail-here@:}
35730@r{ @: t i @: @: @:calc-trail-in@:}
35731@r{ @: t k @: @: 4 @:calc-trail-kill@:}
35732@r{ @: t m @:string @: @:calc-trail-marker@:}
35733@r{ @: t n @: @: 4 @:calc-trail-next@:}
35734@r{ @: t o @: @: @:calc-trail-out@:}
35735@r{ @: t p @: @: 4 @:calc-trail-previous@:}
35736@r{ @: t r @:string @: @:calc-trail-isearch-backward@:}
35737@r{ @: t s @:string @: @:calc-trail-isearch-forward@:}
35738@r{ @: t y @: @: 4 @:calc-trail-yank@:}
35739
35740@c
35741@r{ d@: t C @:oz, nz @: @:tzconv@:(d,oz,nz)}
35742@r{d oz nz@: t C @:$ @: @:tzconv@:(d,oz,nz)}
35743@r{ d@: t D @: @: 15 @:date@:(d)}
35744@r{ d@: t I @: @: 4 @:incmonth@:(d,n)}
35745@r{ d@: t J @: @: 16 @:julian@:(d,z)}
35746@r{ d@: t M @: @: 17 @:newmonth@:(d,n)}
35747@r{ @: t N @: @: 16 @:now@:(z)}
35748@r{ d@: t P @:1 @: 31 @:year@:(d)}
35749@r{ d@: t P @:2 @: 31 @:month@:(d)}
35750@r{ d@: t P @:3 @: 31 @:day@:(d)}
35751@r{ d@: t P @:4 @: 31 @:hour@:(d)}
35752@r{ d@: t P @:5 @: 31 @:minute@:(d)}
35753@r{ d@: t P @:6 @: 31 @:second@:(d)}
35754@r{ d@: t P @:7 @: 31 @:weekday@:(d)}
35755@r{ d@: t P @:8 @: 31 @:yearday@:(d)}
35756@r{ d@: t P @:9 @: 31 @:time@:(d)}
35757@r{ d@: t U @: @: 16 @:unixtime@:(d,z)}
35758@r{ d@: t W @: @: 17 @:newweek@:(d,w)}
35759@r{ d@: t Y @: @: 17 @:newyear@:(d,n)}
35760
35761@c
35762@r{ a b@: t + @: @: 2 @:badd@:(a,b)}
35763@r{ a b@: t - @: @: 2 @:bsub@:(a,b)}
35764
35765@c
35766@r{ @: u a @: @: 12 @:calc-autorange-units@:}
35767@r{ a@: u b @: @: @:calc-base-units@:}
35768@r{ a@: u c @:units @: 18 @:calc-convert-units@:}
35769@r{ defn@: u d @:unit, descr @: @:calc-define-unit@:}
35770@r{ @: u e @: @: @:calc-explain-units@:}
35771@r{ @: u g @:unit @: @:calc-get-unit-definition@:}
35772@r{ @: u p @: @: @:calc-permanent-units@:}
35773@r{ a@: u r @: @: @:calc-remove-units@:}
35774@r{ a@: u s @: @: @:usimplify@:(a)}
35775@r{ a@: u t @:units @: 18 @:calc-convert-temperature@:}
35776@r{ @: u u @:unit @: @:calc-undefine-unit@:}
35777@r{ @: u v @: @: @:calc-enter-units-table@:}
35778@r{ a@: u x @: @: @:calc-extract-units@:}
35779@r{ a@: u 0-9 @: @: @:calc-quick-units@:}
35780
35781@c
35782@r{ v1 v2@: u C @: @: 20 @:vcov@:(v1,v2)}
35783@r{ v1 v2@: I u C @: @: 20 @:vpcov@:(v1,v2)}
35784@r{ v1 v2@: H u C @: @: 20 @:vcorr@:(v1,v2)}
35785@r{ v@: u G @: @: 19 @:vgmean@:(v)}
35786@r{ a b@: H u G @: @: 2 @:agmean@:(a,b)}
35787@r{ v@: u M @: @: 19 @:vmean@:(v)}
35788@r{ v@: I u M @: @: 19 @:vmeane@:(v)}
35789@r{ v@: H u M @: @: 19 @:vmedian@:(v)}
35790@r{ v@: I H u M @: @: 19 @:vhmean@:(v)}
35791@r{ v@: u N @: @: 19 @:vmin@:(v)}
35792@r{ v@: u S @: @: 19 @:vsdev@:(v)}
35793@r{ v@: I u S @: @: 19 @:vpsdev@:(v)}
35794@r{ v@: H u S @: @: 19 @:vvar@:(v)}
35795@r{ v@: I H u S @: @: 19 @:vpvar@:(v)}
35796@r{ @: u V @: @: @:calc-view-units-table@:}
35797@r{ v@: u X @: @: 19 @:vmax@:(v)}
35798
35799@c
35800@r{ v@: u + @: @: 19 @:vsum@:(v)}
35801@r{ v@: u * @: @: 19 @:vprod@:(v)}
35802@r{ v@: u # @: @: 19 @:vcount@:(v)}
35803
35804@c
35805@r{ @: V ( @: @: 50 @:calc-vector-parens@:}
35806@r{ @: V @{ @: @: 50 @:calc-vector-braces@:}
35807@r{ @: V [ @: @: 50 @:calc-vector-brackets@:}
35808@r{ @: V ] @:ROCP @: 50 @:calc-matrix-brackets@:}
35809@r{ @: V , @: @: 50 @:calc-vector-commas@:}
35810@r{ @: V < @: @: 50 @:calc-matrix-left-justify@:}
35811@r{ @: V = @: @: 50 @:calc-matrix-center-justify@:}
35812@r{ @: V > @: @: 50 @:calc-matrix-right-justify@:}
35813@r{ @: V / @: @: 12,50 @:calc-break-vectors@:}
35814@r{ @: V . @: @: 12,50 @:calc-full-vectors@:}
35815
35816@c
35817@r{ s t@: V ^ @: @: 2 @:vint@:(s,t)}
35818@r{ s t@: V - @: @: 2 @:vdiff@:(s,t)}
35819@r{ s@: V ~ @: @: 1 @:vcompl@:(s)}
35820@r{ s@: V # @: @: 1 @:vcard@:(s)}
35821@r{ s@: V : @: @: 1 @:vspan@:(s)}
35822@r{ s@: V + @: @: 1 @:rdup@:(s)}
35823
35824@c
35825@r{ m@: V & @: @: 1 @:inv@:(m) 1/m}
35826
35827@c
35828@r{ v@: v a @:n @: @:arrange@:(v,n)}
35829@r{ a@: v b @:n @: @:cvec@:(a,n)}
35830@r{ v@: v c @:n >0 @: 21,31 @:mcol@:(v,n)}
35831@r{ v@: v c @:n <0 @: 31 @:mrcol@:(v,-n)}
35832@r{ m@: v c @:0 @: 31 @:getdiag@:(m)}
35833@r{ v@: v d @: @: 25 @:diag@:(v,n)}
35834@r{ v m@: v e @: @: 2 @:vexp@:(v,m)}
35835@r{ v m f@: H v e @: @: 2 @:vexp@:(v,m,f)}
35836@r{ v a@: v f @: @: 26 @:find@:(v,a,n)}
35837@r{ v@: v h @: @: 1 @:head@:(v)}
35838@r{ v@: I v h @: @: 1 @:tail@:(v)}
35839@r{ v@: H v h @: @: 1 @:rhead@:(v)}
35840@r{ v@: I H v h @: @: 1 @:rtail@:(v)}
35841@r{ @: v i @:n @: 31 @:idn@:(1,n)}
35842@r{ @: v i @:0 @: 31 @:idn@:(1)}
35843@r{ h t@: v k @: @: 2 @:cons@:(h,t)}
35844@r{ h t@: H v k @: @: 2 @:rcons@:(h,t)}
35845@r{ v@: v l @: @: 1 @:vlen@:(v)}
35846@r{ v@: H v l @: @: 1 @:mdims@:(v)}
35847@r{ v m@: v m @: @: 2 @:vmask@:(v,m)}
35848@r{ v@: v n @: @: 1 @:rnorm@:(v)}
35849@r{ a b c@: v p @: @: 24 @:calc-pack@:}
35850@r{ v@: v r @:n >0 @: 21,31 @:mrow@:(v,n)}
35851@r{ v@: v r @:n <0 @: 31 @:mrrow@:(v,-n)}
35852@r{ m@: v r @:0 @: 31 @:getdiag@:(m)}
35853@r{ v i j@: v s @: @: @:subvec@:(v,i,j)}
35854@r{ v i j@: I v s @: @: @:rsubvec@:(v,i,j)}
35855@r{ m@: v t @: @: 1 @:trn@:(m)}
35856@r{ v@: v u @: @: 24 @:calc-unpack@:}
35857@r{ v@: v v @: @: 1 @:rev@:(v)}
35858@r{ @: v x @:n @: 31 @:index@:(n)}
35859@r{ n s i@: C-u v x @: @: @:index@:(n,s,i)}
35860
35861@c
35862@r{ v@: V A @:op @: 22 @:apply@:(op,v)}
35863@r{ v1 v2@: V C @: @: 2 @:cross@:(v1,v2)}
35864@r{ m@: V D @: @: 1 @:det@:(m)}
35865@r{ s@: V E @: @: 1 @:venum@:(s)}
35866@r{ s@: V F @: @: 1 @:vfloor@:(s)}
35867@r{ v@: V G @: @: @:grade@:(v)}
35868@r{ v@: I V G @: @: @:rgrade@:(v)}
35869@r{ v@: V H @:n @: 31 @:histogram@:(v,n)}
35870@r{ v w@: H V H @:n @: 31 @:histogram@:(v,w,n)}
35871@r{ v1 v2@: V I @:mop aop @: 22 @:inner@:(mop,aop,v1,v2)}
35872@r{ m@: V J @: @: 1 @:ctrn@:(m)}
ee0fd0d8 35873@r{ m1 m2@: V K @: @: @:kron(m1,m2)}
4009494e
GM
35874@r{ m@: V L @: @: 1 @:lud@:(m)}
35875@r{ v@: V M @:op @: 22,23 @:map@:(op,v)}
35876@r{ v@: V N @: @: 1 @:cnorm@:(v)}
35877@r{ v1 v2@: V O @:op @: 22 @:outer@:(op,v1,v2)}
35878@r{ v@: V R @:op @: 22,23 @:reduce@:(op,v)}
35879@r{ v@: I V R @:op @: 22,23 @:rreduce@:(op,v)}
35880@r{ a n@: H V R @:op @: 22 @:nest@:(op,a,n)}
35881@r{ a@: I H V R @:op @: 22 @:fixp@:(op,a)}
35882@r{ v@: V S @: @: @:sort@:(v)}
35883@r{ v@: I V S @: @: @:rsort@:(v)}
35884@r{ m@: V T @: @: 1 @:tr@:(m)}
35885@r{ v@: V U @:op @: 22 @:accum@:(op,v)}
35886@r{ v@: I V U @:op @: 22 @:raccum@:(op,v)}
35887@r{ a n@: H V U @:op @: 22 @:anest@:(op,a,n)}
35888@r{ a@: I H V U @:op @: 22 @:afixp@:(op,a)}
35889@r{ s t@: V V @: @: 2 @:vunion@:(s,t)}
35890@r{ s t@: V X @: @: 2 @:vxor@:(s,t)}
35891
35892@c
35893@r{ @: Y @: @: @:@:user commands}
35894
35895@c
35896@r{ @: z @: @: @:@:user commands}
35897
35898@c
35899@r{ c@: Z [ @: @: 45 @:calc-kbd-if@:}
35900@r{ c@: Z | @: @: 45 @:calc-kbd-else-if@:}
35901@r{ @: Z : @: @: @:calc-kbd-else@:}
35902@r{ @: Z ] @: @: @:calc-kbd-end-if@:}
35903
35904@c
35905@r{ @: Z @{ @: @: 4 @:calc-kbd-loop@:}
35906@r{ c@: Z / @: @: 45 @:calc-kbd-break@:}
35907@r{ @: Z @} @: @: @:calc-kbd-end-loop@:}
35908@r{ n@: Z < @: @: @:calc-kbd-repeat@:}
35909@r{ @: Z > @: @: @:calc-kbd-end-repeat@:}
35910@r{ n m@: Z ( @: @: @:calc-kbd-for@:}
35911@r{ s@: Z ) @: @: @:calc-kbd-end-for@:}
35912
35913@c
35914@r{ @: Z C-g @: @: @:@:cancel if/loop command}
35915
35916@c
35917@r{ @: Z ` @: @: @:calc-kbd-push@:}
35918@r{ @: Z ' @: @: @:calc-kbd-pop@:}
35919@r{ @: Z # @: @: @:calc-kbd-query@:}
35920
35921@c
35922@r{ comp@: Z C @:func, args @: 50 @:calc-user-define-composition@:}
35923@r{ @: Z D @:key, command @: @:calc-user-define@:}
35924@r{ @: Z E @:key, editing @: 30 @:calc-user-define-edit@:}
35925@r{ defn@: Z F @:k, c, f, a, n@: 28 @:calc-user-define-formula@:}
35926@r{ @: Z G @:key @: @:calc-get-user-defn@:}
35927@r{ @: Z I @: @: @:calc-user-define-invocation@:}
35928@r{ @: Z K @:key, command @: @:calc-user-define-kbd-macro@:}
35929@r{ @: Z P @:key @: @:calc-user-define-permanent@:}
35930@r{ @: Z S @: @: 30 @:calc-edit-user-syntax@:}
35931@r{ @: Z T @: @: 12 @:calc-timing@:}
35932@r{ @: Z U @:key @: @:calc-user-undefine@:}
35933
35934@end format
35935
35936@noindent
35937NOTES
35938
35939@enumerate
35940@c 1
35941@item
35942Positive prefix arguments apply to @expr{n} stack entries.
35943Negative prefix arguments apply to the @expr{-n}th stack entry.
35944A prefix of zero applies to the entire stack. (For @key{LFD} and
35945@kbd{M-@key{DEL}}, the meaning of the sign is reversed.)
35946
35947@c 2
35948@item
35949Positive prefix arguments apply to @expr{n} stack entries.
35950Negative prefix arguments apply to the top stack entry
35951and the next @expr{-n} stack entries.
35952
35953@c 3
35954@item
35955Positive prefix arguments rotate top @expr{n} stack entries by one.
35956Negative prefix arguments rotate the entire stack by @expr{-n}.
35957A prefix of zero reverses the entire stack.
35958
35959@c 4
35960@item
35961Prefix argument specifies a repeat count or distance.
35962
35963@c 5
35964@item
35965Positive prefix arguments specify a precision @expr{p}.
35966Negative prefix arguments reduce the current precision by @expr{-p}.
35967
35968@c 6
35969@item
35970A prefix argument is interpreted as an additional step-size parameter.
35971A plain @kbd{C-u} prefix means to prompt for the step size.
35972
35973@c 7
35974@item
35975A prefix argument specifies simplification level and depth.
359761=Default, 2=like @kbd{a s}, 3=like @kbd{a e}.
35977
35978@c 8
35979@item
35980A negative prefix operates only on the top level of the input formula.
35981
35982@c 9
35983@item
35984Positive prefix arguments specify a word size of @expr{w} bits, unsigned.
35985Negative prefix arguments specify a word size of @expr{w} bits, signed.
35986
35987@c 10
35988@item
35989Prefix arguments specify the shift amount @expr{n}. The @expr{w} argument
35990cannot be specified in the keyboard version of this command.
35991
35992@c 11
35993@item
35994From the keyboard, @expr{d} is omitted and defaults to zero.
35995
35996@c 12
35997@item
35998Mode is toggled; a positive prefix always sets the mode, and a negative
35999prefix always clears the mode.
36000
36001@c 13
36002@item
36003Some prefix argument values provide special variations of the mode.
36004
36005@c 14
36006@item
36007A prefix argument, if any, is used for @expr{m} instead of taking
36008@expr{m} from the stack. @expr{M} may take any of these values:
36009@iftex
36010{@advance@tableindent10pt
36011@end iftex
36012@table @asis
36013@item Integer
36014Random integer in the interval @expr{[0 .. m)}.
36015@item Float
36016Random floating-point number in the interval @expr{[0 .. m)}.
36017@item 0.0
36018Gaussian with mean 1 and standard deviation 0.
36019@item Error form
36020Gaussian with specified mean and standard deviation.
36021@item Interval
36022Random integer or floating-point number in that interval.
36023@item Vector
36024Random element from the vector.
36025@end table
36026@iftex
36027}
36028@end iftex
36029
36030@c 15
36031@item
36032A prefix argument from 1 to 6 specifies number of date components
36033to remove from the stack. @xref{Date Conversions}.
36034
36035@c 16
36036@item
36037A prefix argument specifies a time zone; @kbd{C-u} says to take the
36038time zone number or name from the top of the stack. @xref{Time Zones}.
36039
36040@c 17
36041@item
36042A prefix argument specifies a day number (0-6, 0-31, or 0-366).
36043
36044@c 18
36045@item
36046If the input has no units, you will be prompted for both the old and
36047the new units.
36048
36049@c 19
36050@item
36051With a prefix argument, collect that many stack entries to form the
36052input data set. Each entry may be a single value or a vector of values.
36053
36054@c 20
36055@item
36056With a prefix argument of 1, take a single
36057@texline @var{n}@math{\times2}
36058@infoline @mathit{@var{N}x2}
36059matrix from the stack instead of two separate data vectors.
36060
36061@c 21
36062@item
36063The row or column number @expr{n} may be given as a numeric prefix
36064argument instead. A plain @kbd{C-u} prefix says to take @expr{n}
36065from the top of the stack. If @expr{n} is a vector or interval,
36066a subvector/submatrix of the input is created.
36067
36068@c 22
36069@item
36070The @expr{op} prompt can be answered with the key sequence for the
36071desired function, or with @kbd{x} or @kbd{z} followed by a function name,
36072or with @kbd{$} to take a formula from the top of the stack, or with
36073@kbd{'} and a typed formula. In the last two cases, the formula may
36074be a nameless function like @samp{<#1+#2>} or @samp{<x, y : x+y>}, or it
36075may include @kbd{$}, @kbd{$$}, etc. (where @kbd{$} will correspond to the
36076last argument of the created function), or otherwise you will be
36077prompted for an argument list. The number of vectors popped from the
36078stack by @kbd{V M} depends on the number of arguments of the function.
36079
36080@c 23
36081@item
36082One of the mapping direction keys @kbd{_} (horizontal, i.e., map
36083by rows or reduce across), @kbd{:} (vertical, i.e., map by columns or
36084reduce down), or @kbd{=} (map or reduce by rows) may be used before
36085entering @expr{op}; these modify the function name by adding the letter
36086@code{r} for ``rows,'' @code{c} for ``columns,'' @code{a} for ``across,''
36087or @code{d} for ``down.''
36088
36089@c 24
36090@item
36091The prefix argument specifies a packing mode. A nonnegative mode
36092is the number of items (for @kbd{v p}) or the number of levels
36093(for @kbd{v u}). A negative mode is as described below. With no
36094prefix argument, the mode is taken from the top of the stack and
36095may be an integer or a vector of integers.
36096@iftex
36097{@advance@tableindent-20pt
36098@end iftex
36099@table @cite
36100@item -1
36101(@var{2}) Rectangular complex number.
36102@item -2
36103(@var{2}) Polar complex number.
36104@item -3
36105(@var{3}) HMS form.
36106@item -4
36107(@var{2}) Error form.
36108@item -5
36109(@var{2}) Modulo form.
36110@item -6
36111(@var{2}) Closed interval.
36112@item -7
36113(@var{2}) Closed .. open interval.
36114@item -8
36115(@var{2}) Open .. closed interval.
36116@item -9
36117(@var{2}) Open interval.
36118@item -10
36119(@var{2}) Fraction.
36120@item -11
36121(@var{2}) Float with integer mantissa.
36122@item -12
36123(@var{2}) Float with mantissa in @expr{[1 .. 10)}.
36124@item -13
36125(@var{1}) Date form (using date numbers).
36126@item -14
36127(@var{3}) Date form (using year, month, day).
36128@item -15
36129(@var{6}) Date form (using year, month, day, hour, minute, second).
36130@end table
36131@iftex
36132}
36133@end iftex
36134
36135@c 25
36136@item
36137A prefix argument specifies the size @expr{n} of the matrix. With no
36138prefix argument, @expr{n} is omitted and the size is inferred from
36139the input vector.
36140
36141@c 26
36142@item
36143The prefix argument specifies the starting position @expr{n} (default 1).
36144
36145@c 27
36146@item
36147Cursor position within stack buffer affects this command.
36148
36149@c 28
36150@item
36151Arguments are not actually removed from the stack by this command.
36152
36153@c 29
36154@item
36155Variable name may be a single digit or a full name.
36156
36157@c 30
36158@item
36159Editing occurs in a separate buffer. Press @kbd{C-c C-c} (or
36160@key{LFD}, or in some cases @key{RET}) to finish the edit, or kill the
36161buffer with @kbd{C-x k} to cancel the edit. The @key{LFD} key prevents evaluation
36162of the result of the edit.
36163
36164@c 31
36165@item
36166The number prompted for can also be provided as a prefix argument.
36167
36168@c 32
36169@item
36170Press this key a second time to cancel the prefix.
36171
36172@c 33
36173@item
36174With a negative prefix, deactivate all formulas. With a positive
36175prefix, deactivate and then reactivate from scratch.
36176
36177@c 34
36178@item
36179Default is to scan for nearest formula delimiter symbols. With a
36180prefix of zero, formula is delimited by mark and point. With a
36181non-zero prefix, formula is delimited by scanning forward or
36182backward by that many lines.
36183
36184@c 35
36185@item
36186Parse the region between point and mark as a vector. A nonzero prefix
36187parses @var{n} lines before or after point as a vector. A zero prefix
36188parses the current line as a vector. A @kbd{C-u} prefix parses the
36189region between point and mark as a single formula.
36190
36191@c 36
36192@item
36193Parse the rectangle defined by point and mark as a matrix. A positive
36194prefix @var{n} divides the rectangle into columns of width @var{n}.
36195A zero or @kbd{C-u} prefix parses each line as one formula. A negative
36196prefix suppresses special treatment of bracketed portions of a line.
36197
36198@c 37
36199@item
36200A numeric prefix causes the current language mode to be ignored.
36201
36202@c 38
36203@item
36204Responding to a prompt with a blank line answers that and all
36205later prompts by popping additional stack entries.
36206
36207@c 39
36208@item
36209Answer for @expr{v} may also be of the form @expr{v = v_0} or
36210@expr{v - v_0}.
36211
36212@c 40
36213@item
36214With a positive prefix argument, stack contains many @expr{y}'s and one
36215common @expr{x}. With a zero prefix, stack contains a vector of
36216@expr{y}s and a common @expr{x}. With a negative prefix, stack
36217contains many @expr{[x,y]} vectors. (For 3D plots, substitute
36218@expr{z} for @expr{y} and @expr{x,y} for @expr{x}.)
36219
36220@c 41
36221@item
36222With any prefix argument, all curves in the graph are deleted.
36223
36224@c 42
36225@item
36226With a positive prefix, refines an existing plot with more data points.
36227With a negative prefix, forces recomputation of the plot data.
36228
36229@c 43
36230@item
36231With any prefix argument, set the default value instead of the
36232value for this graph.
36233
36234@c 44
36235@item
36236With a negative prefix argument, set the value for the printer.
36237
36238@c 45
36239@item
36240Condition is considered ``true'' if it is a nonzero real or complex
36241number, or a formula whose value is known to be nonzero; it is ``false''
36242otherwise.
36243
36244@c 46
36245@item
36246Several formulas separated by commas are pushed as multiple stack
36247entries. Trailing @kbd{)}, @kbd{]}, @kbd{@}}, @kbd{>}, and @kbd{"}
36248delimiters may be omitted. The notation @kbd{$$$} refers to the value
36249in stack level three, and causes the formula to replace the top three
36250stack levels. The notation @kbd{$3} refers to stack level three without
36251causing that value to be removed from the stack. Use @key{LFD} in place
36252of @key{RET} to prevent evaluation; use @kbd{M-=} in place of @key{RET}
36253to evaluate variables.
36254
36255@c 47
36256@item
36257The variable is replaced by the formula shown on the right. The
36258Inverse flag reverses the order of the operands, e.g., @kbd{I s - x}
36259assigns
36260@texline @math{x \coloneq a-x}.
36261@infoline @expr{x := a-x}.
36262
36263@c 48
36264@item
36265Press @kbd{?} repeatedly to see how to choose a model. Answer the
36266variables prompt with @expr{iv} or @expr{iv;pv} to specify
36267independent and parameter variables. A positive prefix argument
36268takes @mathit{@var{n}+1} vectors from the stack; a zero prefix takes a matrix
36269and a vector from the stack.
36270
36271@c 49
36272@item
36273With a plain @kbd{C-u} prefix, replace the current region of the
36274destination buffer with the yanked text instead of inserting.
36275
36276@c 50
36277@item
36278All stack entries are reformatted; the @kbd{H} prefix inhibits this.
36279The @kbd{I} prefix sets the mode temporarily, redraws the top stack
36280entry, then restores the original setting of the mode.
36281
36282@c 51
36283@item
36284A negative prefix sets the default 3D resolution instead of the
36285default 2D resolution.
36286
36287@c 52
36288@item
36289This grabs a vector of the form [@var{prec}, @var{wsize}, @var{ssize},
36290@var{radix}, @var{flfmt}, @var{ang}, @var{frac}, @var{symb}, @var{polar},
36291@var{matrix}, @var{simp}, @var{inf}]. A prefix argument from 1 to 12
36292grabs the @var{n}th mode value only.
36293@end enumerate
36294
36295@iftex
36296(Space is provided below for you to keep your own written notes.)
36297@page
36298@endgroup
36299@end iftex
36300
36301
36302@c [end-summary]
36303
36304@node Key Index, Command Index, Summary, Top
36305@unnumbered Index of Key Sequences
36306
36307@printindex ky
36308
36309@node Command Index, Function Index, Key Index, Top
36310@unnumbered Index of Calculator Commands
36311
36312Since all Calculator commands begin with the prefix @samp{calc-}, the
36313@kbd{x} key has been provided as a variant of @kbd{M-x} which automatically
36314types @samp{calc-} for you. Thus, @kbd{x last-args} is short for
36315@kbd{M-x calc-last-args}.
36316
36317@printindex pg
36318
36319@node Function Index, Concept Index, Command Index, Top
36320@unnumbered Index of Algebraic Functions
36321
36322This is a list of built-in functions and operators usable in algebraic
36323expressions. Their full Lisp names are derived by adding the prefix
36324@samp{calcFunc-}, as in @code{calcFunc-sqrt}.
36325@iftex
36326All functions except those noted with ``*'' have corresponding
36327Calc keystrokes and can also be found in the Calc Summary.
36328@end iftex
36329
36330@printindex tp
36331
36332@node Concept Index, Variable Index, Function Index, Top
36333@unnumbered Concept Index
36334
36335@printindex cp
36336
36337@node Variable Index, Lisp Function Index, Concept Index, Top
36338@unnumbered Index of Variables
36339
36340The variables in this list that do not contain dashes are accessible
36341as Calc variables. Add a @samp{var-} prefix to get the name of the
36342corresponding Lisp variable.
36343
36344The remaining variables are Lisp variables suitable for @code{setq}ing
36345in your Calc init file or @file{.emacs} file.
36346
36347@printindex vr
36348
36349@node Lisp Function Index, , Variable Index, Top
36350@unnumbered Index of Lisp Math Functions
36351
36352The following functions are meant to be used with @code{defmath}, not
36353@code{defun} definitions. For names that do not start with @samp{calc-},
36354the corresponding full Lisp name is derived by adding a prefix of
36355@samp{math-}.
36356
36357@printindex fn
36358
36359@bye
36360
36361
36362@ignore
36363 arch-tag: 77a71809-fa4d-40be-b2cc-da3e8fb137c0
36364@end ignore