* calc/calc.el (calc-gregorian-switch): In menu, put dates before regions.
[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 5@c [title]
5a83c46e 6@settitle GNU Emacs Calc Manual
4009494e
GM
7@setchapternewpage odd
8@comment %**end of header (This is for running Texinfo on a region.)
9
8289f37b 10@include emacsver.texi
9f534a47 11
4009494e
GM
12@c The following macros are used for conditional output for single lines.
13@c @texline foo
14@c `foo' will appear only in TeX output
15@c @infoline foo
16@c `foo' will appear only in non-TeX output
17
18@c @expr{expr} will typeset an expression;
19@c $x$ in TeX, @samp{x} otherwise.
20
21@iftex
22@macro texline
23@end macro
24@alias infoline=comment
25@alias expr=math
26@alias tfn=code
27@alias mathit=expr
8dc6104d 28@alias summarykey=key
4009494e
GM
29@macro cpi{}
30@math{@pi{}}
31@end macro
32@macro cpiover{den}
33@math{@pi/\den\}
34@end macro
35@end iftex
36
37@ifnottex
38@alias texline=comment
39@macro infoline{stuff}
40\stuff\
41@end macro
42@alias expr=samp
43@alias tfn=t
44@alias mathit=i
8dc6104d
JB
45@macro summarykey{ky}
46\ky\
47@end macro
4009494e
GM
48@macro cpi{}
49@expr{pi}
50@end macro
51@macro cpiover{den}
52@expr{pi/\den\}
53@end macro
54@end ifnottex
55
56
57@tex
58% Suggested by Karl Berry <karl@@freefriends.org>
59\gdef\!{\mskip-\thinmuskip}
60@end tex
61
62@c Fix some other things specifically for this manual.
63@iftex
64@finalout
65@mathcode`@:=`@: @c Make Calc fractions come out right in math mode
66@tex
67\gdef\coloneq{\mathrel{\mathord:\mathord=}}
68
69\gdef\beforedisplay{\vskip-10pt}
70\gdef\afterdisplay{\vskip-5pt}
71\gdef\beforedisplayh{\vskip-25pt}
72\gdef\afterdisplayh{\vskip-10pt}
73@end tex
74@newdimen@kyvpos @kyvpos=0pt
75@newdimen@kyhpos @kyhpos=0pt
76@newcount@calcclubpenalty @calcclubpenalty=1000
77@ignore
78@newcount@calcpageno
79@newtoks@calcoldeverypar @calcoldeverypar=@everypar
80@everypar={@calceverypar@the@calcoldeverypar}
4009494e
GM
81@ifx@ninett@undefinedzzz@font@ninett=cmtt9@fi
82@catcode`@\=0 \catcode`\@=11
83\r@ggedbottomtrue
84\catcode`\@=0 @catcode`@\=@active
85@end ignore
86@end iftex
87
88@copying
5a83c46e 89@ifinfo
4009494e 90This file documents Calc, the GNU Emacs calculator.
5a83c46e
JB
91@end ifinfo
92@ifnotinfo
40ba43b4 93This file documents Calc, the GNU Emacs calculator, included with
9f534a47 94GNU Emacs @value{EMACSVER}.
5a83c46e 95@end ifnotinfo
4009494e 96
acaf905b 97Copyright @copyright{} 1990-1991, 2001-2012 Free Software Foundation, Inc.
4009494e
GM
98
99@quotation
100Permission is granted to copy, distribute and/or modify this document
6a2c4aec 101under the terms of the GNU Free Documentation License, Version 1.3 or
4009494e
GM
102any later version published by the Free Software Foundation; with the
103Invariant Sections being just ``GNU GENERAL PUBLIC LICENSE'', with the
104Front-Cover texts being ``A GNU Manual,'' and with the Back-Cover
105Texts as in (a) below. A copy of the license is included in the section
106entitled ``GNU Free Documentation License.''
107
6f093307
GM
108(a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
109modify this GNU manual. Buying copies from the FSF supports it in
110developing GNU and promoting software freedom.''
4009494e
GM
111@end quotation
112@end copying
113
0c973505 114@dircategory Emacs misc features
4009494e 115@direntry
62e034c2 116* Calc: (calc). Advanced desk calculator and mathematical tool.
4009494e
GM
117@end direntry
118
119@titlepage
120@sp 6
121@center @titlefont{Calc Manual}
122@sp 4
5a83c46e 123@center GNU Emacs Calc
4009494e
GM
124@c [volume]
125@sp 5
126@center Dave Gillespie
127@center daveg@@synaptics.com
128@page
129
130@vskip 0pt plus 1filll
4009494e
GM
131@insertcopying
132@end titlepage
133
134
135@summarycontents
136
137@c [end]
138
139@contents
140
141@c [begin]
142@ifnottex
143@node Top, Getting Started, (dir), (dir)
144@chapter The GNU Emacs Calculator
145
146@noindent
147@dfn{Calc} is an advanced desk calculator and mathematical tool
148written by Dave Gillespie that runs as part of the GNU Emacs environment.
149
150This manual, also written (mostly) by Dave Gillespie, is divided into
151three major parts: ``Getting Started,'' the ``Calc Tutorial,'' and the
152``Calc Reference.'' The Tutorial introduces all the major aspects of
153Calculator use in an easy, hands-on way. The remainder of the manual is
154a complete reference to the features of the Calculator.
155@end ifnottex
156
157@ifinfo
158For help in the Emacs Info system (which you are using to read this
159file), type @kbd{?}. (You can also type @kbd{h} to run through a
160longer Info tutorial.)
161@end ifinfo
162
5dc584b5
KB
163@insertcopying
164
4009494e
GM
165@menu
166* Getting Started:: General description and overview.
167@ifinfo
168* Interactive Tutorial::
169@end ifinfo
170* Tutorial:: A step-by-step introduction for beginners.
171
172* Introduction:: Introduction to the Calc reference manual.
173* Data Types:: Types of objects manipulated by Calc.
174* Stack and Trail:: Manipulating the stack and trail buffers.
175* Mode Settings:: Adjusting display format and other modes.
176* Arithmetic:: Basic arithmetic functions.
177* Scientific Functions:: Transcendentals and other scientific functions.
178* Matrix Functions:: Operations on vectors and matrices.
179* Algebra:: Manipulating expressions algebraically.
180* Units:: Operations on numbers with units.
181* Store and Recall:: Storing and recalling variables.
182* Graphics:: Commands for making graphs of data.
183* Kill and Yank:: Moving data into and out of Calc.
184* Keypad Mode:: Operating Calc from a keypad.
185* Embedded Mode:: Working with formulas embedded in a file.
186* Programming:: Calc as a programmable calculator.
187
188* Copying:: How you can copy and share Calc.
189* GNU Free Documentation License:: The license for this documentation.
190* Customizing Calc:: Customizing Calc.
191* Reporting Bugs:: How to report bugs and make suggestions.
192
193* Summary:: Summary of Calc commands and functions.
194
195* Key Index:: The standard Calc key sequences.
196* Command Index:: The interactive Calc commands.
197* Function Index:: Functions (in algebraic formulas).
198* Concept Index:: General concepts.
199* Variable Index:: Variables used by Calc (both user and internal).
200* Lisp Function Index:: Internal Lisp math functions.
201@end menu
202
203@ifinfo
204@node Getting Started, Interactive Tutorial, Top, Top
205@end ifinfo
206@ifnotinfo
207@node Getting Started, Tutorial, Top, Top
208@end ifnotinfo
209@chapter Getting Started
210@noindent
211This chapter provides a general overview of Calc, the GNU Emacs
212Calculator: What it is, how to start it and how to exit from it,
213and what are the various ways that it can be used.
214
215@menu
216* What is Calc::
217* About This Manual::
218* Notations Used in This Manual::
219* Demonstration of Calc::
220* Using Calc::
09ae5da1 221* History and Acknowledgments::
4009494e
GM
222@end menu
223
224@node What is Calc, About This Manual, Getting Started, Getting Started
225@section What is Calc?
226
227@noindent
228@dfn{Calc} is an advanced calculator and mathematical tool that runs as
229part of the GNU Emacs environment. Very roughly based on the HP-28/48
230series of calculators, its many features include:
231
232@itemize @bullet
233@item
234Choice of algebraic or RPN (stack-based) entry of calculations.
235
236@item
237Arbitrary precision integers and floating-point numbers.
238
239@item
240Arithmetic on rational numbers, complex numbers (rectangular and polar),
241error forms with standard deviations, open and closed intervals, vectors
242and matrices, dates and times, infinities, sets, quantities with units,
243and algebraic formulas.
244
245@item
246Mathematical operations such as logarithms and trigonometric functions.
247
248@item
249Programmer's features (bitwise operations, non-decimal numbers).
250
251@item
252Financial functions such as future value and internal rate of return.
253
254@item
255Number theoretical features such as prime factorization and arithmetic
256modulo @var{m} for any @var{m}.
257
258@item
259Algebraic manipulation features, including symbolic calculus.
260
261@item
262Moving data to and from regular editing buffers.
263
264@item
265Embedded mode for manipulating Calc formulas and data directly
266inside any editing buffer.
267
268@item
269Graphics using GNUPLOT, a versatile (and free) plotting program.
270
271@item
272Easy programming using keyboard macros, algebraic formulas,
273algebraic rewrite rules, or extended Emacs Lisp.
274@end itemize
275
276Calc tries to include a little something for everyone; as a result it is
277large and might be intimidating to the first-time user. If you plan to
278use Calc only as a traditional desk calculator, all you really need to
279read is the ``Getting Started'' chapter of this manual and possibly the
280first few sections of the tutorial. As you become more comfortable with
281the program you can learn its additional features. Calc does not
282have the scope and depth of a fully-functional symbolic math package,
283but Calc has the advantages of convenience, portability, and freedom.
284
285@node About This Manual, Notations Used in This Manual, What is Calc, Getting Started
286@section About This Manual
287
288@noindent
289This document serves as a complete description of the GNU Emacs
3bf8054f 290Calculator. It works both as an introduction for novices and as
4009494e
GM
291a reference for experienced users. While it helps to have some
292experience with GNU Emacs in order to get the most out of Calc,
293this manual ought to be readable even if you don't know or use Emacs
294regularly.
295
3bf8054f 296This manual is divided into three major parts:@: the ``Getting
4ce54f6b
CY
297Started'' chapter you are reading now, the Calc tutorial, and the Calc
298reference manual.
4009494e
GM
299@c [when-split]
300@c This manual has been printed in two volumes, the @dfn{Tutorial} and the
301@c @dfn{Reference}. Both volumes include a copy of the ``Getting Started''
302@c chapter.
303
304If you are in a hurry to use Calc, there is a brief ``demonstration''
305below which illustrates the major features of Calc in just a couple of
306pages. If you don't have time to go through the full tutorial, this
307will show you everything you need to know to begin.
308@xref{Demonstration of Calc}.
309
310The tutorial chapter walks you through the various parts of Calc
311with lots of hands-on examples and explanations. If you are new
312to Calc and you have some time, try going through at least the
313beginning of the tutorial. The tutorial includes about 70 exercises
314with answers. These exercises give you some guided practice with
315Calc, as well as pointing out some interesting and unusual ways
316to use its features.
317
318The reference section discusses Calc in complete depth. You can read
319the reference from start to finish if you want to learn every aspect
320of Calc. Or, you can look in the table of contents or the Concept
321Index to find the parts of the manual that discuss the things you
322need to know.
323
17587b1b 324@c @cindex Marginal notes
4009494e
GM
325Every Calc keyboard command is listed in the Calc Summary, and also
326in the Key Index. Algebraic functions, @kbd{M-x} commands, and
40ba43b4 327variables also have their own indices.
17587b1b
JB
328@c @texline Each
329@c @infoline In the printed manual, each
330@c paragraph that is referenced in the Key or Function Index is marked
331@c in the margin with its index entry.
4009494e
GM
332
333@c [fix-ref Help Commands]
3bf8054f
JB
334You can access this manual on-line at any time within Calc by pressing
335the @kbd{h i} key sequence. Outside of the Calc window, you can press
336@kbd{C-x * i} to read the manual on-line. From within Calc the command
337@kbd{h t} will jump directly to the Tutorial; from outside of Calc the
338command @kbd{C-x * t} will jump to the Tutorial and start Calc if
339necessary. Pressing @kbd{h s} or @kbd{C-x * s} will take you directly
340to the Calc Summary. Within Calc, you can also go to the part of the
40ba43b4 341manual describing any Calc key, function, or variable using
3bf8054f 342@w{@kbd{h k}}, @kbd{h f}, or @kbd{h v}, respectively. @xref{Help Commands}.
4009494e
GM
343
344@ifnottex
345The Calc manual can be printed, but because the manual is so large, you
346should only make a printed copy if you really need it. To print the
347manual, you will need the @TeX{} typesetting program (this is a free
348program by Donald Knuth at Stanford University) as well as the
349@file{texindex} program and @file{texinfo.tex} file, both of which can
350be obtained from the FSF as part of the @code{texinfo} package.
351To print the Calc manual in one huge tome, you will need the
352source code to this manual, @file{calc.texi}, available as part of the
353Emacs source. Once you have this file, type @kbd{texi2dvi calc.texi}.
354Alternatively, change to the @file{man} subdirectory of the Emacs
355source distribution, and type @kbd{make calc.dvi}. (Don't worry if you
356get some ``overfull box'' warnings while @TeX{} runs.)
357The result will be a device-independent output file called
358@file{calc.dvi}, which you must print in whatever way is right
359for your system. On many systems, the command is
360
361@example
362lpr -d calc.dvi
363@end example
364
365@noindent
366or
367
368@example
369dvips calc.dvi
370@end example
371@end ifnottex
372@c Printed copies of this manual are also available from the Free Software
373@c Foundation.
374
375@node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started
376@section Notations Used in This Manual
377
378@noindent
379This section describes the various notations that are used
380throughout the Calc manual.
381
382In keystroke sequences, uppercase letters mean you must hold down
383the shift key while typing the letter. Keys pressed with Control
384held down are shown as @kbd{C-x}. Keys pressed with Meta held down
385are shown as @kbd{M-x}. Other notations are @key{RET} for the
386Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key,
387@key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key.
388The @key{DEL} key is called Backspace on some keyboards, it is
389whatever key you would use to correct a simple typing error when
390regularly using Emacs.
391
392(If you don't have the @key{LFD} or @key{TAB} keys on your keyboard,
393the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively.
394If you don't have a Meta key, look for Alt or Extend Char. You can
395also press @key{ESC} or @kbd{C-[} first to get the same effect, so
396that @kbd{M-x}, @kbd{@key{ESC} x}, and @kbd{C-[ x} are all equivalent.)
397
398Sometimes the @key{RET} key is not shown when it is ``obvious''
399that you must press @key{RET} to proceed. For example, the @key{RET}
400is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}.
401
402Commands are generally shown like this: @kbd{p} (@code{calc-precision})
403or @kbd{C-x * k} (@code{calc-keypad}). This means that the command is
404normally used by pressing the @kbd{p} key or @kbd{C-x * k} key sequence,
405but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}.
406
407Commands that correspond to functions in algebraic notation
408are written: @kbd{C} (@code{calc-cos}) [@code{cos}]. This means
409the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that
410the corresponding function in an algebraic-style formula would
411be @samp{cos(@var{x})}.
412
413A few commands don't have key equivalents: @code{calc-sincos}
414[@code{sincos}].
415
416@node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started
417@section A Demonstration of Calc
418
419@noindent
420@cindex Demonstration of Calc
421This section will show some typical small problems being solved with
422Calc. The focus is more on demonstration than explanation, but
423everything you see here will be covered more thoroughly in the
424Tutorial.
425
426To begin, start Emacs if necessary (usually the command @code{emacs}
427does this), and type @kbd{C-x * c} to start the
428Calculator. (You can also use @kbd{M-x calc} if this doesn't work.
429@xref{Starting Calc}, for various ways of starting the Calculator.)
430
431Be sure to type all the sample input exactly, especially noting the
432difference between lower-case and upper-case letters. Remember,
433@key{RET}, @key{TAB}, @key{DEL}, and @key{SPC} are the Return, Tab,
434Delete, and Space keys.
435
436@strong{RPN calculation.} In RPN, you type the input number(s) first,
437then the command to operate on the numbers.
438
439@noindent
40ba43b4 440Type @kbd{2 @key{RET} 3 + Q} to compute
4009494e
GM
441@texline @math{\sqrt{2+3} = 2.2360679775}.
442@infoline the square root of 2+3, which is 2.2360679775.
443
444@noindent
40ba43b4 445Type @kbd{P 2 ^} to compute
4009494e
GM
446@texline @math{\pi^2 = 9.86960440109}.
447@infoline the value of `pi' squared, 9.86960440109.
448
449@noindent
450Type @key{TAB} to exchange the order of these two results.
451
452@noindent
453Type @kbd{- I H S} to subtract these results and compute the Inverse
454Hyperbolic sine of the difference, 2.72996136574.
455
456@noindent
457Type @key{DEL} to erase this result.
458
459@strong{Algebraic calculation.} You can also enter calculations using
460conventional ``algebraic'' notation. To enter an algebraic formula,
461use the apostrophe key.
462
463@noindent
40ba43b4 464Type @kbd{' sqrt(2+3) @key{RET}} to compute
4009494e
GM
465@texline @math{\sqrt{2+3}}.
466@infoline the square root of 2+3.
467
468@noindent
40ba43b4 469Type @kbd{' pi^2 @key{RET}} to enter
4009494e 470@texline @math{\pi^2}.
40ba43b4 471@infoline `pi' squared.
4009494e
GM
472To evaluate this symbolic formula as a number, type @kbd{=}.
473
474@noindent
475Type @kbd{' arcsinh($ - $$) @key{RET}} to subtract the second-most-recent
476result from the most-recent and compute the Inverse Hyperbolic sine.
477
478@strong{Keypad mode.} If you are using the X window system, press
479@w{@kbd{C-x * k}} to get Keypad mode. (If you don't use X, skip to
480the next section.)
481
482@noindent
483Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT}
484``buttons'' using your left mouse button.
485
486@noindent
487Click on @key{PI}, @key{2}, and @tfn{y^x}.
488
489@noindent
490Click on @key{INV}, then @key{ENTER} to swap the two results.
491
492@noindent
493Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}.
494
495@noindent
496Click on @key{<-} to erase the result, then click @key{OFF} to turn
497the Keypad Calculator off.
498
499@strong{Grabbing data.} Type @kbd{C-x * x} if necessary to exit Calc.
500Now select the following numbers as an Emacs region: ``Mark'' the
501front of the list by typing @kbd{C-@key{SPC}} or @kbd{C-@@} there,
502then move to the other end of the list. (Either get this list from
503the on-line copy of this manual, accessed by @w{@kbd{C-x * i}}, or just
504type these numbers into a scratch file.) Now type @kbd{C-x * g} to
505``grab'' these numbers into Calc.
506
507@example
508@group
5091.23 1.97
5101.6 2
5111.19 1.08
512@end group
513@end example
514
515@noindent
516The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.''
517Type @w{@kbd{V R +}} to compute the sum of these numbers.
518
519@noindent
520Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute
521the product of the numbers.
522
523@noindent
524You can also grab data as a rectangular matrix. Place the cursor on
525the upper-leftmost @samp{1} and set the mark, then move to just after
526the lower-right @samp{8} and press @kbd{C-x * r}.
527
528@noindent
40ba43b4 529Type @kbd{v t} to transpose this
4009494e 530@texline @math{3\times2}
40ba43b4
PE
531@infoline 3x2
532matrix into a
4009494e
GM
533@texline @math{2\times3}
534@infoline 2x3
535matrix. Type @w{@kbd{v u}} to unpack the rows into two separate
536vectors. Now type @w{@kbd{V R + @key{TAB} V R +}} to compute the sums
537of the two original columns. (There is also a special
538grab-and-sum-columns command, @kbd{C-x * :}.)
539
540@strong{Units conversion.} Units are entered algebraically.
541Type @w{@kbd{' 43 mi/hr @key{RET}}} to enter the quantity 43 miles-per-hour.
542Type @w{@kbd{u c km/hr @key{RET}}}. Type @w{@kbd{u c m/s @key{RET}}}.
543
544@strong{Date arithmetic.} Type @kbd{t N} to get the current date and
545time. Type @kbd{90 +} to find the date 90 days from now. Type
546@kbd{' <25 dec 87> @key{RET}} to enter a date, then @kbd{- 7 /} to see how
547many weeks have passed since then.
548
549@strong{Algebra.} Algebraic entries can also include formulas
550or equations involving variables. Type @kbd{@w{' [x + y} = a, x y = 1] @key{RET}}
551to enter a pair of equations involving three variables.
552(Note the leading apostrophe in this example; also, note that the space
3bf8054f 553in @samp{x y} is required.) Type @w{@kbd{a S x,y @key{RET}}} to solve
4009494e
GM
554these equations for the variables @expr{x} and @expr{y}.
555
556@noindent
557Type @kbd{d B} to view the solutions in more readable notation.
558Type @w{@kbd{d C}} to view them in C language notation, @kbd{d T}
559to view them in the notation for the @TeX{} typesetting system,
c1dabff0 560and @kbd{d L} to view them in the notation for the @LaTeX{} typesetting
4009494e
GM
561system. Type @kbd{d N} to return to normal notation.
562
563@noindent
564Type @kbd{7.5}, then @kbd{s l a @key{RET}} to let @expr{a = 7.5} in these formulas.
3bf8054f 565(That's the letter @kbd{l}, not the numeral @kbd{1}.)
4009494e
GM
566
567@ifnotinfo
568@strong{Help functions.} You can read about any command in the on-line
569manual. Type @kbd{C-x * c} to return to Calc after each of these
570commands: @kbd{h k t N} to read about the @kbd{t N} command,
571@kbd{h f sqrt @key{RET}} to read about the @code{sqrt} function, and
572@kbd{h s} to read the Calc summary.
573@end ifnotinfo
574@ifinfo
575@strong{Help functions.} You can read about any command in the on-line
576manual. Remember to type the letter @kbd{l}, then @kbd{C-x * c}, to
577return here after each of these commands: @w{@kbd{h k t N}} to read
578about the @w{@kbd{t N}} command, @kbd{h f sqrt @key{RET}} to read about the
579@code{sqrt} function, and @kbd{h s} to read the Calc summary.
580@end ifinfo
581
582Press @key{DEL} repeatedly to remove any leftover results from the stack.
583To exit from Calc, press @kbd{q} or @kbd{C-x * c} again.
584
09ae5da1 585@node Using Calc, History and Acknowledgments, Demonstration of Calc, Getting Started
4009494e
GM
586@section Using Calc
587
588@noindent
589Calc has several user interfaces that are specialized for
590different kinds of tasks. As well as Calc's standard interface,
591there are Quick mode, Keypad mode, and Embedded mode.
592
593@menu
594* Starting Calc::
595* The Standard Interface::
596* Quick Mode Overview::
597* Keypad Mode Overview::
598* Standalone Operation::
599* Embedded Mode Overview::
600* Other C-x * Commands::
601@end menu
602
603@node Starting Calc, The Standard Interface, Using Calc, Using Calc
604@subsection Starting Calc
605
606@noindent
607On most systems, you can type @kbd{C-x *} to start the Calculator.
40ba43b4 608The key sequence @kbd{C-x *} is bound to the command @code{calc-dispatch},
4009494e
GM
609which can be rebound if convenient (@pxref{Customizing Calc}).
610
611When you press @kbd{C-x *}, Emacs waits for you to press a second key to
612complete the command. In this case, you will follow @kbd{C-x *} with a
613letter (upper- or lower-case, it doesn't matter for @kbd{C-x *}) that says
614which Calc interface you want to use.
615
616To get Calc's standard interface, type @kbd{C-x * c}. To get
617Keypad mode, type @kbd{C-x * k}. Type @kbd{C-x * ?} to get a brief
618list of the available options, and type a second @kbd{?} to get
619a complete list.
620
621To ease typing, @kbd{C-x * *} also works to start Calc. It starts the
622same interface (either @kbd{C-x * c} or @w{@kbd{C-x * k}}) that you last
623used, selecting the @kbd{C-x * c} interface by default.
624
625If @kbd{C-x *} doesn't work for you, you can always type explicit
626commands like @kbd{M-x calc} (for the standard user interface) or
627@w{@kbd{M-x calc-keypad}} (for Keypad mode). First type @kbd{M-x}
628(that's Meta with the letter @kbd{x}), then, at the prompt,
629type the full command (like @kbd{calc-keypad}) and press Return.
630
631The same commands (like @kbd{C-x * c} or @kbd{C-x * *}) that start
632the Calculator also turn it off if it is already on.
633
634@node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc
635@subsection The Standard Calc Interface
636
637@noindent
638@cindex Standard user interface
639Calc's standard interface acts like a traditional RPN calculator,
640operated by the normal Emacs keyboard. When you type @kbd{C-x * c}
641to start the Calculator, the Emacs screen splits into two windows
642with the file you were editing on top and Calc on the bottom.
643
644@smallexample
645@group
646
647...
648--**-Emacs: myfile (Fundamental)----All----------------------
649--- Emacs Calculator Mode --- |Emacs Calculator Trail
6502: 17.3 | 17.3
6511: -5 | 3
652 . | 2
653 | 4
654 | * 8
655 | ->-5
656 |
92e15881 657--%*-Calc: 12 Deg (Calculator)----All----- --%*- *Calc Trail*
4009494e
GM
658@end group
659@end smallexample
660
661In this figure, the mode-line for @file{myfile} has moved up and the
662``Calculator'' window has appeared below it. As you can see, Calc
663actually makes two windows side-by-side. The lefthand one is
664called the @dfn{stack window} and the righthand one is called the
665@dfn{trail window.} The stack holds the numbers involved in the
666calculation you are currently performing. The trail holds a complete
667record of all calculations you have done. In a desk calculator with
668a printer, the trail corresponds to the paper tape that records what
669you do.
670
671In this case, the trail shows that four numbers (17.3, 3, 2, and 4)
672were first entered into the Calculator, then the 2 and 4 were
673multiplied to get 8, then the 3 and 8 were subtracted to get @mathit{-5}.
674(The @samp{>} symbol shows that this was the most recent calculation.)
675The net result is the two numbers 17.3 and @mathit{-5} sitting on the stack.
676
677Most Calculator commands deal explicitly with the stack only, but
678there is a set of commands that allow you to search back through
679the trail and retrieve any previous result.
680
681Calc commands use the digits, letters, and punctuation keys.
682Shifted (i.e., upper-case) letters are different from lowercase
683letters. Some letters are @dfn{prefix} keys that begin two-letter
684commands. For example, @kbd{e} means ``enter exponent'' and shifted
685@kbd{E} means @expr{e^x}. With the @kbd{d} (``display modes'') prefix
686the letter ``e'' takes on very different meanings: @kbd{d e} means
687``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.''
688
689There is nothing stopping you from switching out of the Calc
690window and back into your editing window, say by using the Emacs
691@w{@kbd{C-x o}} (@code{other-window}) command. When the cursor is
692inside a regular window, Emacs acts just like normal. When the
693cursor is in the Calc stack or trail windows, keys are interpreted
694as Calc commands.
695
696When you quit by pressing @kbd{C-x * c} a second time, the Calculator
697windows go away but the actual Stack and Trail are not gone, just
698hidden. When you press @kbd{C-x * c} once again you will get the
699same stack and trail contents you had when you last used the
700Calculator.
701
702The Calculator does not remember its state between Emacs sessions.
703Thus if you quit Emacs and start it again, @kbd{C-x * c} will give you
704a fresh stack and trail. There is a command (@kbd{m m}) that lets
705you save your favorite mode settings between sessions, though.
706One of the things it saves is which user interface (standard or
707Keypad) you last used; otherwise, a freshly started Emacs will
708always treat @kbd{C-x * *} the same as @kbd{C-x * c}.
709
710The @kbd{q} key is another equivalent way to turn the Calculator off.
711
712If you type @kbd{C-x * b} first and then @kbd{C-x * c}, you get a
713full-screen version of Calc (@code{full-calc}) in which the stack and
714trail windows are still side-by-side but are now as tall as the whole
715Emacs screen. When you press @kbd{q} or @kbd{C-x * c} again to quit,
716the file you were editing before reappears. The @kbd{C-x * b} key
717switches back and forth between ``big'' full-screen mode and the
718normal partial-screen mode.
719
720Finally, @kbd{C-x * o} (@code{calc-other-window}) is like @kbd{C-x * c}
721except that the Calc window is not selected. The buffer you were
3bf8054f
JB
722editing before remains selected instead. If you are in a Calc window,
723then @kbd{C-x * o} will switch you out of it, being careful not to
724switch you to the Calc Trail window. So @kbd{C-x * o} is a handy
725way to switch out of Calc momentarily to edit your file; you can then
726type @kbd{C-x * c} to switch back into Calc when you are done.
4009494e
GM
727
728@node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc
729@subsection Quick Mode (Overview)
730
731@noindent
732@dfn{Quick mode} is a quick way to use Calc when you don't need the
733full complexity of the stack and trail. To use it, type @kbd{C-x * q}
734(@code{quick-calc}) in any regular editing buffer.
735
736Quick mode is very simple: It prompts you to type any formula in
737standard algebraic notation (like @samp{4 - 2/3}) and then displays
738the result at the bottom of the Emacs screen (@mathit{3.33333333333}
739in this case). You are then back in the same editing buffer you
740were in before, ready to continue editing or to type @kbd{C-x * q}
741again to do another quick calculation. The result of the calculation
742will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command
743at this point will yank the result into your editing buffer.
744
745Calc mode settings affect Quick mode, too, though you will have to
746go into regular Calc (with @kbd{C-x * c}) to change the mode settings.
747
748@c [fix-ref Quick Calculator mode]
749@xref{Quick Calculator}, for further information.
750
751@node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc
752@subsection Keypad Mode (Overview)
753
754@noindent
755@dfn{Keypad mode} is a mouse-based interface to the Calculator.
756It is designed for use with terminals that support a mouse. If you
757don't have a mouse, you will have to operate Keypad mode with your
758arrow keys (which is probably more trouble than it's worth).
759
760Type @kbd{C-x * k} to turn Keypad mode on or off. Once again you
761get two new windows, this time on the righthand side of the screen
762instead of at the bottom. The upper window is the familiar Calc
763Stack; the lower window is a picture of a typical calculator keypad.
764
765@tex
766\dimen0=\pagetotal%
767\advance \dimen0 by 24\baselineskip%
768\ifdim \dimen0>\pagegoal \vfill\eject \fi%
769\medskip
770@end tex
771@smallexample
772@group
773|--- Emacs Calculator Mode ---
774|2: 17.3
775|1: -5
776| .
92e15881 777|--%*-Calc: 12 Deg (Calcul
5a83c46e 778|----+----+--Calc---+----+----1
4009494e
GM
779|FLR |CEIL|RND |TRNC|CLN2|FLT |
780|----+----+----+----+----+----|
781| LN |EXP | |ABS |IDIV|MOD |
782|----+----+----+----+----+----|
783|SIN |COS |TAN |SQRT|y^x |1/x |
784|----+----+----+----+----+----|
785| ENTER |+/- |EEX |UNDO| <- |
786|-----+---+-+--+--+-+---++----|
787| INV | 7 | 8 | 9 | / |
788|-----+-----+-----+-----+-----|
789| HYP | 4 | 5 | 6 | * |
790|-----+-----+-----+-----+-----|
791|EXEC | 1 | 2 | 3 | - |
792|-----+-----+-----+-----+-----|
793| OFF | 0 | . | PI | + |
794|-----+-----+-----+-----+-----+
795@end group
796@end smallexample
797
798Keypad mode is much easier for beginners to learn, because there
799is no need to memorize lots of obscure key sequences. But not all
800commands in regular Calc are available on the Keypad. You can
801always switch the cursor into the Calc stack window to use
802standard Calc commands if you need. Serious Calc users, though,
803often find they prefer the standard interface over Keypad mode.
804
805To operate the Calculator, just click on the ``buttons'' of the
806keypad using your left mouse button. To enter the two numbers
807shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to
808add them together you would then click @kbd{+} (to get 12.3 on
809the stack).
810
811If you click the right mouse button, the top three rows of the
812keypad change to show other sets of commands, such as advanced
813math functions, vector operations, and operations on binary
814numbers.
815
816Because Keypad mode doesn't use the regular keyboard, Calc leaves
817the cursor in your original editing buffer. You can type in
818this buffer in the usual way while also clicking on the Calculator
819keypad. One advantage of Keypad mode is that you don't need an
820explicit command to switch between editing and calculating.
821
822If you press @kbd{C-x * b} first, you get a full-screen Keypad mode
823(@code{full-calc-keypad}) with three windows: The keypad in the lower
824left, the stack in the lower right, and the trail on top.
825
826@c [fix-ref Keypad Mode]
827@xref{Keypad Mode}, for further information.
828
829@node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc
830@subsection Standalone Operation
831
832@noindent
833@cindex Standalone Operation
834If you are not in Emacs at the moment but you wish to use Calc,
835you must start Emacs first. If all you want is to run Calc, you
836can give the commands:
837
838@example
839emacs -f full-calc
840@end example
841
842@noindent
843or
844
845@example
846emacs -f full-calc-keypad
847@end example
848
849@noindent
850which run a full-screen Calculator (as if by @kbd{C-x * b C-x * c}) or
851a full-screen X-based Calculator (as if by @kbd{C-x * b C-x * k}).
852In standalone operation, quitting the Calculator (by pressing
853@kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs
854itself.
855
856@node Embedded Mode Overview, Other C-x * Commands, Standalone Operation, Using Calc
857@subsection Embedded Mode (Overview)
858
859@noindent
860@dfn{Embedded mode} is a way to use Calc directly from inside an
861editing buffer. Suppose you have a formula written as part of a
862document like this:
863
864@smallexample
865@group
866The derivative of
867
868 ln(ln(x))
869
870is
871@end group
872@end smallexample
873
874@noindent
875and you wish to have Calc compute and format the derivative for
876you and store this derivative in the buffer automatically. To
877do this with Embedded mode, first copy the formula down to where
3bf8054f
JB
878you want the result to be, leaving a blank line before and after the
879formula:
4009494e
GM
880
881@smallexample
882@group
883The derivative of
884
885 ln(ln(x))
886
887is
888
889 ln(ln(x))
890@end group
891@end smallexample
892
893Now, move the cursor onto this new formula and press @kbd{C-x * e}.
3bf8054f
JB
894Calc will read the formula (using the surrounding blank lines to tell
895how much text to read), then push this formula (invisibly) onto the Calc
896stack. The cursor will stay on the formula in the editing buffer, but
897the line with the formula will now appear as it would on the Calc stack
898(in this case, it will be left-aligned) and the buffer's mode line will
899change to look like the Calc mode line (with mode indicators like
900@samp{12 Deg} and so on). Even though you are still in your editing
901buffer, the keyboard now acts like the Calc keyboard, and any new result
902you get is copied from the stack back into the buffer. To take the
903derivative, you would type @kbd{a d x @key{RET}}.
4009494e
GM
904
905@smallexample
906@group
907The derivative of
908
909 ln(ln(x))
910
911is
912
d2bd74ff 9131 / x ln(x)
4009494e
GM
914@end group
915@end smallexample
916
5fafc247 917(Note that by default, Calc gives division lower precedence than multiplication,
d2bd74ff 918so that @samp{1 / x ln(x)} is equivalent to @samp{1 / (x ln(x))}.)
3bf8054f 919
4009494e
GM
920To make this look nicer, you might want to press @kbd{d =} to center
921the formula, and even @kbd{d B} to use Big display mode.
922
923@smallexample
924@group
925The derivative of
926
927 ln(ln(x))
928
929is
930% [calc-mode: justify: center]
931% [calc-mode: language: big]
932
933 1
934 -------
d2bd74ff 935 x ln(x)
4009494e
GM
936@end group
937@end smallexample
938
939Calc has added annotations to the file to help it remember the modes
940that were used for this formula. They are formatted like comments
941in the @TeX{} typesetting language, just in case you are using @TeX{} or
c1dabff0 942@LaTeX{}. (In this example @TeX{} is not being used, so you might want
4009494e
GM
943to move these comments up to the top of the file or otherwise put them
944out of the way.)
945
946As an extra flourish, we can add an equation number using a
947righthand label: Type @kbd{d @} (1) @key{RET}}.
948
949@smallexample
950@group
951% [calc-mode: justify: center]
952% [calc-mode: language: big]
953% [calc-mode: right-label: " (1)"]
954
955 1
956 ------- (1)
957 ln(x) x
958@end group
959@end smallexample
960
961To leave Embedded mode, type @kbd{C-x * e} again. The mode line
962and keyboard will revert to the way they were before.
963
964The related command @kbd{C-x * w} operates on a single word, which
4a65fb7a
JB
965generally means a single number, inside text. It searches for an
966expression which ``looks'' like a number containing the point.
d2bd74ff
JB
967Here's an example of its use (before you try this, remove the Calc
968annotations or use a new buffer so that the extra settings in the
969annotations don't take effect):
4009494e
GM
970
971@smallexample
972A slope of one-third corresponds to an angle of 1 degrees.
973@end smallexample
974
975Place the cursor on the @samp{1}, then type @kbd{C-x * w} to enable
976Embedded mode on that number. Now type @kbd{3 /} (to get one-third),
977and @kbd{I T} (the Inverse Tangent converts a slope into an angle),
978then @w{@kbd{C-x * w}} again to exit Embedded mode.
979
980@smallexample
981A slope of one-third corresponds to an angle of 18.4349488229 degrees.
982@end smallexample
983
984@c [fix-ref Embedded Mode]
985@xref{Embedded Mode}, for full details.
986
987@node Other C-x * Commands, , Embedded Mode Overview, Using Calc
988@subsection Other @kbd{C-x *} Commands
989
990@noindent
991Two more Calc-related commands are @kbd{C-x * g} and @kbd{C-x * r},
992which ``grab'' data from a selected region of a buffer into the
993Calculator. The region is defined in the usual Emacs way, by
994a ``mark'' placed at one end of the region, and the Emacs
995cursor or ``point'' placed at the other.
996
997The @kbd{C-x * g} command reads the region in the usual left-to-right,
998top-to-bottom order. The result is packaged into a Calc vector
999of numbers and placed on the stack. Calc (in its standard
1000user interface) is then started. Type @kbd{v u} if you want
1001to unpack this vector into separate numbers on the stack. Also,
1002@kbd{C-u C-x * g} interprets the region as a single number or
1003formula.
1004
1005The @kbd{C-x * r} command reads a rectangle, with the point and
1006mark defining opposite corners of the rectangle. The result
1007is a matrix of numbers on the Calculator stack.
1008
1009Complementary to these is @kbd{C-x * y}, which ``yanks'' the
1010value at the top of the Calc stack back into an editing buffer.
1011If you type @w{@kbd{C-x * y}} while in such a buffer, the value is
1012yanked at the current position. If you type @kbd{C-x * y} while
1013in the Calc buffer, Calc makes an educated guess as to which
1014editing buffer you want to use. The Calc window does not have
1015to be visible in order to use this command, as long as there
1016is something on the Calc stack.
1017
1018Here, for reference, is the complete list of @kbd{C-x *} commands.
1019The shift, control, and meta keys are ignored for the keystroke
1020following @kbd{C-x *}.
1021
1022@noindent
1023Commands for turning Calc on and off:
1024
1025@table @kbd
1026@item *
1027Turn Calc on or off, employing the same user interface as last time.
1028
1029@item =, +, -, /, \, &, #
1030Alternatives for @kbd{*}.
1031
1032@item C
1033Turn Calc on or off using its standard bottom-of-the-screen
1034interface. If Calc is already turned on but the cursor is not
1035in the Calc window, move the cursor into the window.
1036
1037@item O
1038Same as @kbd{C}, but don't select the new Calc window. If
1039Calc is already turned on and the cursor is in the Calc window,
1040move it out of that window.
1041
1042@item B
1043Control whether @kbd{C-x * c} and @kbd{C-x * k} use the full screen.
1044
1045@item Q
1046Use Quick mode for a single short calculation.
1047
1048@item K
1049Turn Calc Keypad mode on or off.
1050
1051@item E
1052Turn Calc Embedded mode on or off at the current formula.
1053
1054@item J
1055Turn Calc Embedded mode on or off, select the interesting part.
1056
1057@item W
1058Turn Calc Embedded mode on or off at the current word (number).
1059
1060@item Z
1061Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command.
1062
1063@item X
1064Quit Calc; turn off standard, Keypad, or Embedded mode if on.
1065(This is like @kbd{q} or @key{OFF} inside of Calc.)
1066@end table
1067@iftex
1068@sp 2
1069@end iftex
1070
1071@noindent
1072Commands for moving data into and out of the Calculator:
1073
1074@table @kbd
1075@item G
1076Grab the region into the Calculator as a vector.
1077
1078@item R
1079Grab the rectangular region into the Calculator as a matrix.
1080
1081@item :
1082Grab the rectangular region and compute the sums of its columns.
1083
1084@item _
1085Grab the rectangular region and compute the sums of its rows.
1086
1087@item Y
1088Yank a value from the Calculator into the current editing buffer.
1089@end table
1090@iftex
1091@sp 2
1092@end iftex
1093
1094@noindent
1095Commands for use with Embedded mode:
1096
1097@table @kbd
1098@item A
1099``Activate'' the current buffer. Locate all formulas that
1100contain @samp{:=} or @samp{=>} symbols and record their locations
1101so that they can be updated automatically as variables are changed.
1102
1103@item D
1104Duplicate the current formula immediately below and select
1105the duplicate.
1106
1107@item F
1108Insert a new formula at the current point.
1109
1110@item N
1111Move the cursor to the next active formula in the buffer.
1112
1113@item P
1114Move the cursor to the previous active formula in the buffer.
1115
1116@item U
1117Update (i.e., as if by the @kbd{=} key) the formula at the current point.
1118
1119@item `
1120Edit (as if by @code{calc-edit}) the formula at the current point.
1121@end table
1122@iftex
1123@sp 2
1124@end iftex
1125
1126@noindent
1127Miscellaneous commands:
1128
1129@table @kbd
1130@item I
1131Run the Emacs Info system to read the Calc manual.
1132(This is the same as @kbd{h i} inside of Calc.)
1133
1134@item T
1135Run the Emacs Info system to read the Calc Tutorial.
1136
1137@item S
1138Run the Emacs Info system to read the Calc Summary.
1139
1140@item L
1141Load Calc entirely into memory. (Normally the various parts
1142are loaded only as they are needed.)
1143
1144@item M
1145Read a region of written keystroke names (like @kbd{C-n a b c @key{RET}})
1146and record them as the current keyboard macro.
1147
1148@item 0
1149(This is the ``zero'' digit key.) Reset the Calculator to
1150its initial state: Empty stack, and initial mode settings.
1151@end table
1152
09ae5da1
PE
1153@node History and Acknowledgments, , Using Calc, Getting Started
1154@section History and Acknowledgments
4009494e
GM
1155
1156@noindent
1157Calc was originally started as a two-week project to occupy a lull
1158in the author's schedule. Basically, a friend asked if I remembered
40ba43b4 1159the value of
4009494e 1160@texline @math{2^{32}}.
40ba43b4 1161@infoline @expr{2^32}.
4009494e
GM
1162I didn't offhand, but I said, ``that's easy, just call up an
1163@code{xcalc}.'' @code{Xcalc} duly reported that the answer to our
1164question was @samp{4.294967e+09}---with no way to see the full ten
1165digits even though we knew they were there in the program's memory! I
1166was so annoyed, I vowed to write a calculator of my own, once and for
1167all.
1168
1169I chose Emacs Lisp, a) because I had always been curious about it
1170and b) because, being only a text editor extension language after
1171all, Emacs Lisp would surely reach its limits long before the project
1172got too far out of hand.
1173
1174To make a long story short, Emacs Lisp turned out to be a distressingly
1175solid implementation of Lisp, and the humble task of calculating
1176turned out to be more open-ended than one might have expected.
1177
1178Emacs Lisp didn't have built-in floating point math (now it does), so
4bb49b43 1179this had to be simulated in software. In fact, Emacs integers would
d2bd74ff
JB
1180only comfortably fit six decimal digits or so (at the time)---not
1181enough for a decent calculator. So I had to write my own
1182high-precision integer code as well, and once I had this I figured
1183that arbitrary-size integers were just as easy as large integers.
1184Arbitrary floating-point precision was the logical next step. Also,
1185since the large integer arithmetic was there anyway it seemed only
1186fair to give the user direct access to it, which in turn made it
1187practical to support fractions as well as floats. All these features
1188inspired me to look around for other data types that might be worth
1189having.
4009494e
GM
1190
1191Around this time, my friend Rick Koshi showed me his nifty new HP-28
1192calculator. It allowed the user to manipulate formulas as well as
1193numerical quantities, and it could also operate on matrices. I
1194decided that these would be good for Calc to have, too. And once
1195things had gone this far, I figured I might as well take a look at
1196serious algebra systems for further ideas. Since these systems did
1197far more than I could ever hope to implement, I decided to focus on
1198rewrite rules and other programming features so that users could
1199implement what they needed for themselves.
1200
1201Rick complained that matrices were hard to read, so I put in code to
1202format them in a 2D style. Once these routines were in place, Big mode
1203was obligatory. Gee, what other language modes would be useful?
1204
1205Scott Hemphill and Allen Knutson, two friends with a strong mathematical
1206bent, contributed ideas and algorithms for a number of Calc features
1207including modulo forms, primality testing, and float-to-fraction conversion.
1208
1209Units were added at the eager insistence of Mass Sivilotti. Later,
1210Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable
1211expert assistance with the units table. As far as I can remember, the
1212idea of using algebraic formulas and variables to represent units dates
1213back to an ancient article in Byte magazine about muMath, an early
1214algebra system for microcomputers.
1215
1216Many people have contributed to Calc by reporting bugs and suggesting
1217features, large and small. A few deserve special mention: Tim Peters,
1218who helped develop the ideas that led to the selection commands, rewrite
40ba43b4 1219rules, and many other algebra features;
4009494e
GM
1220@texline Fran\c{c}ois
1221@infoline Francois
1222Pinard, who contributed an early prototype of the Calc Summary appendix
1223as well as providing valuable suggestions in many other areas of Calc;
1224Carl Witty, whose eagle eyes discovered many typographical and factual
1225errors in the Calc manual; Tim Kay, who drove the development of
1226Embedded mode; Ove Ewerlid, who made many suggestions relating to the
1227algebra commands and contributed some code for polynomial operations;
f10d0e80 1228Randal Schwartz, who suggested the @code{calc-eval} function; Juha
4009494e 1229Sarlin, who first worked out how to split Calc into quickly-loading
f10d0e80
JB
1230parts; Bob Weiner, who helped immensely with the Lucid Emacs port; and
1231Robert J. Chassell, who suggested the Calc Tutorial and exercises as
40ba43b4 1232well as many other things.
4009494e
GM
1233
1234@cindex Bibliography
1235@cindex Knuth, Art of Computer Programming
1236@cindex Numerical Recipes
1237@c Should these be expanded into more complete references?
1238Among the books used in the development of Calc were Knuth's @emph{Art
1239of Computer Programming} (especially volume II, @emph{Seminumerical
1240Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky,
1241and Vetterling; Bevington's @emph{Data Reduction and Error Analysis
1242for the Physical Sciences}; @emph{Concrete Mathematics} by Graham,
1243Knuth, and Patashnik; Steele's @emph{Common Lisp, the Language}; the
1244@emph{CRC Standard Math Tables} (William H. Beyer, ed.); and
1245Abramowitz and Stegun's venerable @emph{Handbook of Mathematical
1246Functions}. Also, of course, Calc could not have been written without
1247the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil Lewis and
1248Dan LaLiberte.
1249
1250Final thanks go to Richard Stallman, without whose fine implementations
1251of the Emacs editor, language, and environment, Calc would have been
1252finished in two weeks.
1253
1254@c [tutorial]
1255
1256@ifinfo
1257@c This node is accessed by the `C-x * t' command.
1258@node Interactive Tutorial, Tutorial, Getting Started, Top
1259@chapter Tutorial
1260
1261@noindent
1262Some brief instructions on using the Emacs Info system for this tutorial:
1263
1264Press the space bar and Delete keys to go forward and backward in a
1265section by screenfuls (or use the regular Emacs scrolling commands
1266for this).
1267
1268Press @kbd{n} or @kbd{p} to go to the Next or Previous section.
1269If the section has a @dfn{menu}, press a digit key like @kbd{1}
1270or @kbd{2} to go to a sub-section from the menu. Press @kbd{u} to
1271go back up from a sub-section to the menu it is part of.
1272
1273Exercises in the tutorial all have cross-references to the
1274appropriate page of the ``answers'' section. Press @kbd{f}, then
1275the exercise number, to see the answer to an exercise. After
1276you have followed a cross-reference, you can press the letter
1277@kbd{l} to return to where you were before.
1278
1279You can press @kbd{?} at any time for a brief summary of Info commands.
1280
59ee4113 1281Press the number @kbd{1} now to enter the first section of the Tutorial.
4009494e
GM
1282
1283@menu
1284* Tutorial::
1285@end menu
1286
1287@node Tutorial, Introduction, Interactive Tutorial, Top
1288@end ifinfo
1289@ifnotinfo
1290@node Tutorial, Introduction, Getting Started, Top
1291@end ifnotinfo
1292@chapter Tutorial
1293
1294@noindent
1295This chapter explains how to use Calc and its many features, in
1296a step-by-step, tutorial way. You are encouraged to run Calc and
1297work along with the examples as you read (@pxref{Starting Calc}).
1298If you are already familiar with advanced calculators, you may wish
1299@c [not-split]
1300to skip on to the rest of this manual.
1301@c [when-split]
1302@c to skip on to volume II of this manual, the @dfn{Calc Reference}.
1303
1304@c [fix-ref Embedded Mode]
1305This tutorial describes the standard user interface of Calc only.
1306The Quick mode and Keypad mode interfaces are fairly
1307self-explanatory. @xref{Embedded Mode}, for a description of
1308the Embedded mode interface.
1309
1310The easiest way to read this tutorial on-line is to have two windows on
59ee4113
JB
1311your Emacs screen, one with Calc and one with the Info system. Press
1312@kbd{C-x * t} to set this up; the on-line tutorial will be opened in the
1313current window and Calc will be started in another window. From the
1314Info window, the command @kbd{C-x * c} can be used to switch to the Calc
1315window and @kbd{C-x * o} can be used to switch back to the Info window.
1316(If you have a printed copy of the manual you can use that instead; in
1317that case you only need to press @kbd{C-x * c} to start Calc.)
4009494e
GM
1318
1319This tutorial is designed to be done in sequence. But the rest of this
1320manual does not assume you have gone through the tutorial. The tutorial
1321does not cover everything in the Calculator, but it touches on most
1322general areas.
1323
1324@ifnottex
1325You may wish to print out a copy of the Calc Summary and keep notes on
1326it as you learn Calc. @xref{About This Manual}, to see how to make a
1327printed summary. @xref{Summary}.
1328@end ifnottex
1329@iftex
1330The Calc Summary at the end of the reference manual includes some blank
1331space for your own use. You may wish to keep notes there as you learn
1332Calc.
1333@end iftex
1334
1335@menu
1336* Basic Tutorial::
1337* Arithmetic Tutorial::
1338* Vector/Matrix Tutorial::
1339* Types Tutorial::
1340* Algebra Tutorial::
1341* Programming Tutorial::
1342
1343* Answers to Exercises::
1344@end menu
1345
1346@node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial
1347@section Basic Tutorial
1348
1349@noindent
1350In this section, we learn how RPN and algebraic-style calculations
1351work, how to undo and redo an operation done by mistake, and how
1352to control various modes of the Calculator.
1353
1354@menu
1355* RPN Tutorial:: Basic operations with the stack.
1356* Algebraic Tutorial:: Algebraic entry; variables.
1357* Undo Tutorial:: If you make a mistake: Undo and the trail.
1358* Modes Tutorial:: Common mode-setting commands.
1359@end menu
1360
1361@node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial
1362@subsection RPN Calculations and the Stack
1363
1364@cindex RPN notation
4009494e 1365@noindent
d2bd74ff 1366@ifnottex
4009494e
GM
1367Calc normally uses RPN notation. You may be familiar with the RPN
1368system from Hewlett-Packard calculators, FORTH, or PostScript.
1369(Reverse Polish Notation, RPN, is named after the Polish mathematician
1370Jan Lukasiewicz.)
1371@end ifnottex
1372@tex
4009494e
GM
1373Calc normally uses RPN notation. You may be familiar with the RPN
1374system from Hewlett-Packard calculators, FORTH, or PostScript.
1375(Reverse Polish Notation, RPN, is named after the Polish mathematician
1376Jan \L ukasiewicz.)
1377@end tex
1378
1379The central component of an RPN calculator is the @dfn{stack}. A
1380calculator stack is like a stack of dishes. New dishes (numbers) are
1381added at the top of the stack, and numbers are normally only removed
1382from the top of the stack.
1383
1384@cindex Operators
1385@cindex Operands
1386In an operation like @expr{2+3}, the 2 and 3 are called the @dfn{operands}
1387and the @expr{+} is the @dfn{operator}. In an RPN calculator you always
1388enter the operands first, then the operator. Each time you type a
1389number, Calc adds or @dfn{pushes} it onto the top of the Stack.
1390When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate
1391number of operands from the stack and pushes back the result.
1392
1393Thus we could add the numbers 2 and 3 in an RPN calculator by typing:
1394@kbd{2 @key{RET} 3 @key{RET} +}. (The @key{RET} key, Return, corresponds to
1395the @key{ENTER} key on traditional RPN calculators.) Try this now if
1396you wish; type @kbd{C-x * c} to switch into the Calc window (you can type
1397@kbd{C-x * c} again or @kbd{C-x * o} to switch back to the Tutorial window).
1398The first four keystrokes ``push'' the numbers 2 and 3 onto the stack.
1399The @kbd{+} key ``pops'' the top two numbers from the stack, adds them,
1400and pushes the result (5) back onto the stack. Here's how the stack
1401will look at various points throughout the calculation:
1402
1403@smallexample
1404@group
1405 . 1: 2 2: 2 1: 5 .
1406 . 1: 3 .
1407 .
1408
1409 C-x * c 2 @key{RET} 3 @key{RET} + @key{DEL}
1410@end group
1411@end smallexample
1412
1413The @samp{.} symbol is a marker that represents the top of the stack.
1414Note that the ``top'' of the stack is really shown at the bottom of
1415the Stack window. This may seem backwards, but it turns out to be
1416less distracting in regular use.
1417
1418@cindex Stack levels
1419@cindex Levels of stack
1420The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level
1421numbers}. Old RPN calculators always had four stack levels called
1422@expr{x}, @expr{y}, @expr{z}, and @expr{t}. Calc's stack can grow
1423as large as you like, so it uses numbers instead of letters. Some
1424stack-manipulation commands accept a numeric argument that says
1425which stack level to work on. Normal commands like @kbd{+} always
1426work on the top few levels of the stack.
1427
1428@c [fix-ref Truncating the Stack]
1429The Stack buffer is just an Emacs buffer, and you can move around in
1430it using the regular Emacs motion commands. But no matter where the
1431cursor is, even if you have scrolled the @samp{.} marker out of
1432view, most Calc commands always move the cursor back down to level 1
1433before doing anything. It is possible to move the @samp{.} marker
1434upwards through the stack, temporarily ``hiding'' some numbers from
1435commands like @kbd{+}. This is called @dfn{stack truncation} and
1436we will not cover it in this tutorial; @pxref{Truncating the Stack},
1437if you are interested.
1438
1439You don't really need the second @key{RET} in @kbd{2 @key{RET} 3
1440@key{RET} +}. That's because if you type any operator name or
1441other non-numeric key when you are entering a number, the Calculator
1442automatically enters that number and then does the requested command.
1443Thus @kbd{2 @key{RET} 3 +} will work just as well.
1444
1445Examples in this tutorial will often omit @key{RET} even when the
1446stack displays shown would only happen if you did press @key{RET}:
1447
1448@smallexample
1449@group
14501: 2 2: 2 1: 5
1451 . 1: 3 .
1452 .
1453
1454 2 @key{RET} 3 +
1455@end group
1456@end smallexample
1457
1458@noindent
1459Here, after pressing @kbd{3} the stack would really show @samp{1: 2}
1460with @samp{Calc:@: 3} in the minibuffer. In these situations, you can
1461press the optional @key{RET} to see the stack as the figure shows.
1462
1463(@bullet{}) @strong{Exercise 1.} (This tutorial will include exercises
1464at various points. Try them if you wish. Answers to all the exercises
1465are located at the end of the Tutorial chapter. Each exercise will
1466include a cross-reference to its particular answer. If you are
1467reading with the Emacs Info system, press @kbd{f} and the
1468exercise number to go to the answer, then the letter @kbd{l} to
1469return to where you were.)
1470
1471@noindent
1472Here's the first exercise: What will the keystrokes @kbd{1 @key{RET} 2
1473@key{RET} 3 @key{RET} 4 + * -} compute? (@samp{*} is the symbol for
1474multiplication.) Figure it out by hand, then try it with Calc to see
1475if you're right. @xref{RPN Answer 1, 1}. (@bullet{})
1476
40ba43b4 1477(@bullet{}) @strong{Exercise 2.} Compute
d2bd74ff 1478@texline @math{(2\times4) + (7\times9.5) + {5\over4}}
40ba43b4 1479@infoline @expr{2*4 + 7*9.5 + 5/4}
4009494e
GM
1480using the stack. @xref{RPN Answer 2, 2}. (@bullet{})
1481
1482The @key{DEL} key is called Backspace on some keyboards. It is
1483whatever key you would use to correct a simple typing error when
1484regularly using Emacs. The @key{DEL} key pops and throws away the
1485top value on the stack. (You can still get that value back from
1486the Trail if you should need it later on.) There are many places
1487in this tutorial where we assume you have used @key{DEL} to erase the
1488results of the previous example at the beginning of a new example.
1489In the few places where it is really important to use @key{DEL} to
1490clear away old results, the text will remind you to do so.
1491
1492(It won't hurt to let things accumulate on the stack, except that
1493whenever you give a display-mode-changing command Calc will have to
1494spend a long time reformatting such a large stack.)
1495
1496Since the @kbd{-} key is also an operator (it subtracts the top two
1497stack elements), how does one enter a negative number? Calc uses
1498the @kbd{_} (underscore) key to act like the minus sign in a number.
1499So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key
1500will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine.
1501
1502You can also press @kbd{n}, which means ``change sign.'' It changes
1503the number at the top of the stack (or the number being entered)
1504from positive to negative or vice-versa: @kbd{5 n @key{RET}}.
1505
1506@cindex Duplicating a stack entry
1507If you press @key{RET} when you're not entering a number, the effect
1508is to duplicate the top number on the stack. Consider this calculation:
1509
1510@smallexample
1511@group
15121: 3 2: 3 1: 9 2: 9 1: 81
1513 . 1: 3 . 1: 9 .
1514 . .
1515
1516 3 @key{RET} @key{RET} * @key{RET} *
1517@end group
1518@end smallexample
1519
1520@noindent
1521(Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^},
1522to raise 3 to the fourth power.)
1523
1524The space-bar key (denoted @key{SPC} here) performs the same function
1525as @key{RET}; you could replace all three occurrences of @key{RET} in
1526the above example with @key{SPC} and the effect would be the same.
1527
1528@cindex Exchanging stack entries
1529Another stack manipulation key is @key{TAB}. This exchanges the top
1530two stack entries. Suppose you have computed @kbd{2 @key{RET} 3 +}
1531to get 5, and then you realize what you really wanted to compute
1532was @expr{20 / (2+3)}.
1533
1534@smallexample
1535@group
15361: 5 2: 5 2: 20 1: 4
1537 . 1: 20 1: 5 .
1538 . .
1539
1540 2 @key{RET} 3 + 20 @key{TAB} /
1541@end group
1542@end smallexample
1543
1544@noindent
1545Planning ahead, the calculation would have gone like this:
1546
1547@smallexample
1548@group
15491: 20 2: 20 3: 20 2: 20 1: 4
1550 . 1: 2 2: 2 1: 5 .
1551 . 1: 3 .
1552 .
1553
1554 20 @key{RET} 2 @key{RET} 3 + /
1555@end group
1556@end smallexample
1557
1558A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type
1559@key{TAB}). It rotates the top three elements of the stack upward,
1560bringing the object in level 3 to the top.
1561
1562@smallexample
1563@group
15641: 10 2: 10 3: 10 3: 20 3: 30
1565 . 1: 20 2: 20 2: 30 2: 10
1566 . 1: 30 1: 10 1: 20
1567 . . .
1568
1569 10 @key{RET} 20 @key{RET} 30 @key{RET} M-@key{TAB} M-@key{TAB}
1570@end group
1571@end smallexample
1572
1573(@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are
1574on the stack. Figure out how to add one to the number in level 2
1575without affecting the rest of the stack. Also figure out how to add
1576one to the number in level 3. @xref{RPN Answer 3, 3}. (@bullet{})
1577
1578Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two
1579arguments from the stack and push a result. Operations like @kbd{n} and
1580@kbd{Q} (square root) pop a single number and push the result. You can
1581think of them as simply operating on the top element of the stack.
1582
1583@smallexample
1584@group
15851: 3 1: 9 2: 9 1: 25 1: 5
1586 . . 1: 16 . .
1587 .
1588
1589 3 @key{RET} @key{RET} * 4 @key{RET} @key{RET} * + Q
1590@end group
1591@end smallexample
1592
1593@noindent
1594(Note that capital @kbd{Q} means to hold down the Shift key while
1595typing @kbd{q}. Remember, plain unshifted @kbd{q} is the Quit command.)
1596
1597@cindex Pythagorean Theorem
1598Here we've used the Pythagorean Theorem to determine the hypotenuse of a
1599right triangle. Calc actually has a built-in command for that called
1600@kbd{f h}, but let's suppose we can't remember the necessary keystrokes.
1601We can still enter it by its full name using @kbd{M-x} notation:
1602
1603@smallexample
1604@group
16051: 3 2: 3 1: 5
1606 . 1: 4 .
1607 .
1608
1609 3 @key{RET} 4 @key{RET} M-x calc-hypot
1610@end group
1611@end smallexample
1612
1613All Calculator commands begin with the word @samp{calc-}. Since it
1614gets tiring to type this, Calc provides an @kbd{x} key which is just
1615like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-}
1616prefix for you:
1617
1618@smallexample
1619@group
16201: 3 2: 3 1: 5
1621 . 1: 4 .
1622 .
1623
1624 3 @key{RET} 4 @key{RET} x hypot
1625@end group
1626@end smallexample
1627
1628What happens if you take the square root of a negative number?
1629
1630@smallexample
1631@group
16321: 4 1: -4 1: (0, 2)
1633 . . .
1634
1635 4 @key{RET} n Q
1636@end group
1637@end smallexample
1638
1639@noindent
1640The notation @expr{(a, b)} represents a complex number.
1641Complex numbers are more traditionally written @expr{a + b i};
1642Calc can display in this format, too, but for now we'll stick to the
1643@expr{(a, b)} notation.
1644
1645If you don't know how complex numbers work, you can safely ignore this
1646feature. Complex numbers only arise from operations that would be
1647errors in a calculator that didn't have complex numbers. (For example,
1648taking the square root or logarithm of a negative number produces a
1649complex result.)
1650
1651Complex numbers are entered in the notation shown. The @kbd{(} and
1652@kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.''
1653
1654@smallexample
1655@group
16561: ( ... 2: ( ... 1: (2, ... 1: (2, ... 1: (2, 3)
1657 . 1: 2 . 3 .
1658 . .
1659
1660 ( 2 , 3 )
1661@end group
1662@end smallexample
1663
1664You can perform calculations while entering parts of incomplete objects.
1665However, an incomplete object cannot actually participate in a calculation:
1666
1667@smallexample
1668@group
16691: ( ... 2: ( ... 3: ( ... 1: ( ... 1: ( ...
1670 . 1: 2 2: 2 5 5
1671 . 1: 3 . .
1672 .
1673 (error)
1674 ( 2 @key{RET} 3 + +
1675@end group
1676@end smallexample
1677
1678@noindent
1679Adding 5 to an incomplete object makes no sense, so the last command
1680produces an error message and leaves the stack the same.
1681
1682Incomplete objects can't participate in arithmetic, but they can be
1683moved around by the regular stack commands.
1684
1685@smallexample
1686@group
16872: 2 3: 2 3: 3 1: ( ... 1: (2, 3)
16881: 3 2: 3 2: ( ... 2 .
1689 . 1: ( ... 1: 2 3
1690 . . .
1691
16922 @key{RET} 3 @key{RET} ( M-@key{TAB} M-@key{TAB} )
1693@end group
1694@end smallexample
1695
1696@noindent
1697Note that the @kbd{,} (comma) key did not have to be used here.
1698When you press @kbd{)} all the stack entries between the incomplete
1699entry and the top are collected, so there's never really a reason
1700to use the comma. It's up to you.
1701
1702(@bullet{}) @strong{Exercise 4.} To enter the complex number @expr{(2, 3)},
1703your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}. What happened?
1704(Joe thought of a clever way to correct his mistake in only two
1705keystrokes, but it didn't quite work. Try it to find out why.)
1706@xref{RPN Answer 4, 4}. (@bullet{})
1707
1708Vectors are entered the same way as complex numbers, but with square
1709brackets in place of parentheses. We'll meet vectors again later in
1710the tutorial.
1711
1712Any Emacs command can be given a @dfn{numeric prefix argument} by
1713typing a series of @key{META}-digits beforehand. If @key{META} is
1714awkward for you, you can instead type @kbd{C-u} followed by the
1715necessary digits. Numeric prefix arguments can be negative, as in
1716@kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}. Calc commands use numeric
1717prefix arguments in a variety of ways. For example, a numeric prefix
1718on the @kbd{+} operator adds any number of stack entries at once:
1719
1720@smallexample
1721@group
17221: 10 2: 10 3: 10 3: 10 1: 60
1723 . 1: 20 2: 20 2: 20 .
1724 . 1: 30 1: 30
1725 . .
1726
1727 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u 3 +
1728@end group
1729@end smallexample
1730
1731For stack manipulation commands like @key{RET}, a positive numeric
1732prefix argument operates on the top @var{n} stack entries at once. A
1733negative argument operates on the entry in level @var{n} only. An
1734argument of zero operates on the entire stack. In this example, we copy
1735the second-to-top element of the stack:
1736
1737@smallexample
1738@group
17391: 10 2: 10 3: 10 3: 10 4: 10
1740 . 1: 20 2: 20 2: 20 3: 20
1741 . 1: 30 1: 30 2: 30
1742 . . 1: 20
1743 .
1744
1745 10 @key{RET} 20 @key{RET} 30 @key{RET} C-u -2 @key{RET}
1746@end group
1747@end smallexample
1748
1749@cindex Clearing the stack
1750@cindex Emptying the stack
1751Another common idiom is @kbd{M-0 @key{DEL}}, which clears the stack.
1752(The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the
1753entire stack.)
1754
1755@node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial
1756@subsection Algebraic-Style Calculations
1757
1758@noindent
1759If you are not used to RPN notation, you may prefer to operate the
1760Calculator in Algebraic mode, which is closer to the way
1761non-RPN calculators work. In Algebraic mode, you enter formulas
1762in traditional @expr{2+3} notation.
1763
5fafc247
JB
1764@strong{Notice:} Calc gives @samp{/} lower precedence than @samp{*}, so
1765that @samp{a/b*c} is interpreted as @samp{a/(b*c)}; this is not
1766standard across all computer languages. See below for details.
4009494e
GM
1767
1768You don't really need any special ``mode'' to enter algebraic formulas.
1769You can enter a formula at any time by pressing the apostrophe (@kbd{'})
1770key. Answer the prompt with the desired formula, then press @key{RET}.
1771The formula is evaluated and the result is pushed onto the RPN stack.
1772If you don't want to think in RPN at all, you can enter your whole
1773computation as a formula, read the result from the stack, then press
1774@key{DEL} to delete it from the stack.
1775
1776Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}.
1777The result should be the number 9.
1778
1779Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*},
1780@samp{/}, and @samp{^}. You can use parentheses to make the order
1781of evaluation clear. In the absence of parentheses, @samp{^} is
1782evaluated first, then @samp{*}, then @samp{/}, then finally
1783@samp{+} and @samp{-}. For example, the expression
1784
1785@example
17862 + 3*4*5 / 6*7^8 - 9
1787@end example
1788
1789@noindent
1790is equivalent to
1791
1792@example
17932 + ((3*4*5) / (6*(7^8)) - 9
1794@end example
1795
1796@noindent
1797or, in large mathematical notation,
1798
1799@ifnottex
1800@example
1801@group
1802 3 * 4 * 5
18032 + --------- - 9
1804 8
1805 6 * 7
1806@end group
1807@end example
1808@end ifnottex
1809@tex
4009494e
GM
1810\beforedisplay
1811$$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$
1812\afterdisplay
1813@end tex
1814
1815@noindent
1816The result of this expression will be the number @mathit{-6.99999826533}.
1817
1818Calc's order of evaluation is the same as for most computer languages,
1819except that @samp{*} binds more strongly than @samp{/}, as the above
1820example shows. As in normal mathematical notation, the @samp{*} symbol
1821can often be omitted: @samp{2 a} is the same as @samp{2*a}.
1822
1823Operators at the same level are evaluated from left to right, except
1824that @samp{^} is evaluated from right to left. Thus, @samp{2-3-4} is
1825equivalent to @samp{(2-3)-4} or @mathit{-5}, whereas @samp{2^3^4} is equivalent
1826to @samp{2^(3^4)} (a very large integer; try it!).
1827
1828If you tire of typing the apostrophe all the time, there is
1829Algebraic mode, where Calc automatically senses
1830when you are about to type an algebraic expression. To enter this
1831mode, press the two letters @w{@kbd{m a}}. (An @samp{Alg} indicator
1832should appear in the Calc window's mode line.)
1833
1834Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}.
1835
1836In Algebraic mode, when you press any key that would normally begin
1837entering a number (such as a digit, a decimal point, or the @kbd{_}
1838key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins
1839an algebraic entry.
1840
1841Functions which do not have operator symbols like @samp{+} and @samp{*}
1842must be entered in formulas using function-call notation. For example,
1843the function name corresponding to the square-root key @kbd{Q} is
1844@code{sqrt}. To compute a square root in a formula, you would use
1845the notation @samp{sqrt(@var{x})}.
1846
1847Press the apostrophe, then type @kbd{sqrt(5*2) - 3}. The result should
1848be @expr{0.16227766017}.
1849
1850Note that if the formula begins with a function name, you need to use
1851the apostrophe even if you are in Algebraic mode. If you type @kbd{arcsin}
1852out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite
1853command, and the @kbd{csin} will be taken as the name of the rewrite
1854rule to use!
1855
1856Some people prefer to enter complex numbers and vectors in algebraic
1857form because they find RPN entry with incomplete objects to be too
1858distracting, even though they otherwise use Calc as an RPN calculator.
1859
1860Still in Algebraic mode, type:
1861
1862@smallexample
1863@group
18641: (2, 3) 2: (2, 3) 1: (8, -1) 2: (8, -1) 1: (9, -1)
1865 . 1: (1, -2) . 1: 1 .
1866 . .
1867
1868 (2,3) @key{RET} (1,-2) @key{RET} * 1 @key{RET} +
1869@end group
1870@end smallexample
1871
1872Algebraic mode allows us to enter complex numbers without pressing
1873an apostrophe first, but it also means we need to press @key{RET}
1874after every entry, even for a simple number like @expr{1}.
1875
1876(You can type @kbd{C-u m a} to enable a special Incomplete Algebraic
1877mode in which the @kbd{(} and @kbd{[} keys use algebraic entry even
1878though regular numeric keys still use RPN numeric entry. There is also
1879Total Algebraic mode, started by typing @kbd{m t}, in which all
1880normal keys begin algebraic entry. You must then use the @key{META} key
1881to type Calc commands: @kbd{M-m t} to get back out of Total Algebraic
1882mode, @kbd{M-q} to quit, etc.)
1883
1884If you're still in Algebraic mode, press @kbd{m a} again to turn it off.
1885
1886Actual non-RPN calculators use a mixture of algebraic and RPN styles.
1887In general, operators of two numbers (like @kbd{+} and @kbd{*})
1888use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q})
1889use RPN form. Also, a non-RPN calculator allows you to see the
1890intermediate results of a calculation as you go along. You can
1891accomplish this in Calc by performing your calculation as a series
1892of algebraic entries, using the @kbd{$} sign to tie them together.
1893In an algebraic formula, @kbd{$} represents the number on the top
40ba43b4 1894of the stack. Here, we perform the calculation
4009494e
GM
1895@texline @math{\sqrt{2\times4+1}},
1896@infoline @expr{sqrt(2*4+1)},
1897which on a traditional calculator would be done by pressing
1898@kbd{2 * 4 + 1 =} and then the square-root key.
1899
1900@smallexample
1901@group
19021: 8 1: 9 1: 3
1903 . . .
1904
1905 ' 2*4 @key{RET} $+1 @key{RET} Q
1906@end group
1907@end smallexample
1908
1909@noindent
1910Notice that we didn't need to press an apostrophe for the @kbd{$+1},
1911because the dollar sign always begins an algebraic entry.
1912
1913(@bullet{}) @strong{Exercise 1.} How could you get the same effect as
1914pressing @kbd{Q} but using an algebraic entry instead? How about
1915if the @kbd{Q} key on your keyboard were broken?
1916@xref{Algebraic Answer 1, 1}. (@bullet{})
1917
1918The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack
1919entries. For example, @kbd{' $$+$ @key{RET}} is just like typing @kbd{+}.
1920
1921Algebraic formulas can include @dfn{variables}. To store in a
1922variable, press @kbd{s s}, then type the variable name, then press
1923@key{RET}. (There are actually two flavors of store command:
1924@kbd{s s} stores a number in a variable but also leaves the number
1925on the stack, while @w{@kbd{s t}} removes a number from the stack and
1926stores it in the variable.) A variable name should consist of one
1927or more letters or digits, beginning with a letter.
1928
1929@smallexample
1930@group
19311: 17 . 1: a + a^2 1: 306
1932 . . .
1933
1934 17 s t a @key{RET} ' a+a^2 @key{RET} =
1935@end group
1936@end smallexample
1937
1938@noindent
1939The @kbd{=} key @dfn{evaluates} a formula by replacing all its
1940variables by the values that were stored in them.
1941
1942For RPN calculations, you can recall a variable's value on the
1943stack either by entering its name as a formula and pressing @kbd{=},
1944or by using the @kbd{s r} command.
1945
1946@smallexample
1947@group
19481: 17 2: 17 3: 17 2: 17 1: 306
1949 . 1: 17 2: 17 1: 289 .
1950 . 1: 2 .
1951 .
1952
1953 s r a @key{RET} ' a @key{RET} = 2 ^ +
1954@end group
1955@end smallexample
1956
1957If you press a single digit for a variable name (as in @kbd{s t 3}, you
1958get one of ten @dfn{quick variables} @code{q0} through @code{q9}.
1959They are ``quick'' simply because you don't have to type the letter
1960@code{q} or the @key{RET} after their names. In fact, you can type
1961simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for
1962@kbd{t 3} and @w{@kbd{r 3}}.
1963
1964Any variables in an algebraic formula for which you have not stored
1965values are left alone, even when you evaluate the formula.
1966
1967@smallexample
1968@group
d2bd74ff 19691: 2 a + 2 b 1: 2 b + 34
4009494e
GM
1970 . .
1971
1972 ' 2a+2b @key{RET} =
1973@end group
1974@end smallexample
1975
1976Calls to function names which are undefined in Calc are also left
1977alone, as are calls for which the value is undefined.
1978
1979@smallexample
1980@group
d2bd74ff 19811: log10(0) + log10(x) + log10(5, 6) + foo(3) + 2
4009494e
GM
1982 .
1983
1984 ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) @key{RET}
1985@end group
1986@end smallexample
1987
1988@noindent
1989In this example, the first call to @code{log10} works, but the other
1990calls are not evaluated. In the second call, the logarithm is
1991undefined for that value of the argument; in the third, the argument
1992is symbolic, and in the fourth, there are too many arguments. In the
1993fifth case, there is no function called @code{foo}. You will see a
1994``Wrong number of arguments'' message referring to @samp{log10(5,6)}.
1995Press the @kbd{w} (``why'') key to see any other messages that may
1996have arisen from the last calculation. In this case you will get
1997``logarithm of zero,'' then ``number expected: @code{x}''. Calc
1998automatically displays the first message only if the message is
1999sufficiently important; for example, Calc considers ``wrong number
2000of arguments'' and ``logarithm of zero'' to be important enough to
2001report automatically, while a message like ``number expected: @code{x}''
2002will only show up if you explicitly press the @kbd{w} key.
2003
2004(@bullet{}) @strong{Exercise 2.} Joe entered the formula @samp{2 x y},
2005stored 5 in @code{x}, pressed @kbd{=}, and got the expected result,
2006@samp{10 y}. He then tried the same for the formula @samp{2 x (1+y)},
2007expecting @samp{10 (1+y)}, but it didn't work. Why not?
2008@xref{Algebraic Answer 2, 2}. (@bullet{})
2009
2010(@bullet{}) @strong{Exercise 3.} What result would you expect
2011@kbd{1 @key{RET} 0 /} to give? What if you then type @kbd{0 *}?
2012@xref{Algebraic Answer 3, 3}. (@bullet{})
2013
2014One interesting way to work with variables is to use the
2015@dfn{evaluates-to} (@samp{=>}) operator. It works like this:
2016Enter a formula algebraically in the usual way, but follow
2017the formula with an @samp{=>} symbol. (There is also an @kbd{s =}
2018command which builds an @samp{=>} formula using the stack.) On
2019the stack, you will see two copies of the formula with an @samp{=>}
2020between them. The lefthand formula is exactly like you typed it;
2021the righthand formula has been evaluated as if by typing @kbd{=}.
2022
2023@smallexample
2024@group
20252: 2 + 3 => 5 2: 2 + 3 => 5
20261: 2 a + 2 b => 34 + 2 b 1: 2 a + 2 b => 20 + 2 b
2027 . .
2028
2029' 2+3 => @key{RET} ' 2a+2b @key{RET} s = 10 s t a @key{RET}
2030@end group
2031@end smallexample
2032
2033@noindent
2034Notice that the instant we stored a new value in @code{a}, all
2035@samp{=>} operators already on the stack that referred to @expr{a}
2036were updated to use the new value. With @samp{=>}, you can push a
2037set of formulas on the stack, then change the variables experimentally
2038to see the effects on the formulas' values.
2039
2040You can also ``unstore'' a variable when you are through with it:
2041
2042@smallexample
2043@group
20442: 2 + 5 => 5
20451: 2 a + 2 b => 2 a + 2 b
2046 .
2047
2048 s u a @key{RET}
2049@end group
2050@end smallexample
2051
2052We will encounter formulas involving variables and functions again
2053when we discuss the algebra and calculus features of the Calculator.
2054
2055@node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial
2056@subsection Undo and Redo
2057
2058@noindent
2059If you make a mistake, you can usually correct it by pressing shift-@kbd{U},
2060the ``undo'' command. First, clear the stack (@kbd{M-0 @key{DEL}}) and exit
2061and restart Calc (@kbd{C-x * * C-x * *}) to make sure things start off
2062with a clean slate. Now:
2063
2064@smallexample
2065@group
20661: 2 2: 2 1: 8 2: 2 1: 6
2067 . 1: 3 . 1: 3 .
2068 . .
2069
2070 2 @key{RET} 3 ^ U *
2071@end group
2072@end smallexample
2073
2074You can undo any number of times. Calc keeps a complete record of
2075all you have done since you last opened the Calc window. After the
2076above example, you could type:
2077
2078@smallexample
2079@group
20801: 6 2: 2 1: 2 . .
2081 . 1: 3 .
2082 .
2083 (error)
2084 U U U U
2085@end group
2086@end smallexample
2087
2088You can also type @kbd{D} to ``redo'' a command that you have undone
2089mistakenly.
2090
2091@smallexample
2092@group
2093 . 1: 2 2: 2 1: 6 1: 6
2094 . 1: 3 . .
2095 .
2096 (error)
2097 D D D D
2098@end group
2099@end smallexample
2100
2101@noindent
2102It was not possible to redo past the @expr{6}, since that was placed there
2103by something other than an undo command.
2104
2105@cindex Time travel
2106You can think of undo and redo as a sort of ``time machine.'' Press
2107@kbd{U} to go backward in time, @kbd{D} to go forward. If you go
2108backward and do something (like @kbd{*}) then, as any science fiction
2109reader knows, you have changed your future and you cannot go forward
2110again. Thus, the inability to redo past the @expr{6} even though there
2111was an earlier undo command.
2112
2113You can always recall an earlier result using the Trail. We've ignored
2114the trail so far, but it has been faithfully recording everything we
2115did since we loaded the Calculator. If the Trail is not displayed,
2116press @kbd{t d} now to turn it on.
2117
2118Let's try grabbing an earlier result. The @expr{8} we computed was
2119undone by a @kbd{U} command, and was lost even to Redo when we pressed
2120@kbd{*}, but it's still there in the trail. There should be a little
2121@samp{>} arrow (the @dfn{trail pointer}) resting on the last trail
2122entry. If there isn't, press @kbd{t ]} to reset the trail pointer.
2123Now, press @w{@kbd{t p}} to move the arrow onto the line containing
2124@expr{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the
2125stack.
2126
2127If you press @kbd{t ]} again, you will see that even our Yank command
2128went into the trail.
2129
2130Let's go further back in time. Earlier in the tutorial we computed
2131a huge integer using the formula @samp{2^3^4}. We don't remember
2132what it was, but the first digits were ``241''. Press @kbd{t r}
2133(which stands for trail-search-reverse), then type @kbd{241}.
2134The trail cursor will jump back to the next previous occurrence of
2135the string ``241'' in the trail. This is just a regular Emacs
2136incremental search; you can now press @kbd{C-s} or @kbd{C-r} to
2137continue the search forwards or backwards as you like.
2138
2139To finish the search, press @key{RET}. This halts the incremental
2140search and leaves the trail pointer at the thing we found. Now we
2141can type @kbd{t y} to yank that number onto the stack. If we hadn't
2142remembered the ``241'', we could simply have searched for @kbd{2^3^4},
2143then pressed @kbd{@key{RET} t n} to halt and then move to the next item.
2144
2145You may have noticed that all the trail-related commands begin with
2146the letter @kbd{t}. (The store-and-recall commands, on the other hand,
2147all began with @kbd{s}.) Calc has so many commands that there aren't
2148enough keys for all of them, so various commands are grouped into
2149two-letter sequences where the first letter is called the @dfn{prefix}
2150key. If you type a prefix key by accident, you can press @kbd{C-g}
2151to cancel it. (In fact, you can press @kbd{C-g} to cancel almost
2152anything in Emacs.) To get help on a prefix key, press that key
2153followed by @kbd{?}. Some prefixes have several lines of help,
40ba43b4 2154so you need to press @kbd{?} repeatedly to see them all.
4009494e
GM
2155You can also type @kbd{h h} to see all the help at once.
2156
2157Try pressing @kbd{t ?} now. You will see a line of the form,
2158
2159@smallexample
2160trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank: [MORE] t-
2161@end smallexample
2162
2163@noindent
2164The word ``trail'' indicates that the @kbd{t} prefix key contains
2165trail-related commands. Each entry on the line shows one command,
2166with a single capital letter showing which letter you press to get
2167that command. We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and
2168@kbd{t y} so far. The @samp{[MORE]} means you can press @kbd{?}
2169again to see more @kbd{t}-prefix commands. Notice that the commands
2170are roughly divided (by semicolons) into related groups.
2171
2172When you are in the help display for a prefix key, the prefix is
2173still active. If you press another key, like @kbd{y} for example,
2174it will be interpreted as a @kbd{t y} command. If all you wanted
2175was to look at the help messages, press @kbd{C-g} afterwards to cancel
2176the prefix.
2177
2178One more way to correct an error is by editing the stack entries.
2179The actual Stack buffer is marked read-only and must not be edited
2180directly, but you can press @kbd{`} (the backquote or accent grave)
2181to edit a stack entry.
2182
2183Try entering @samp{3.141439} now. If this is supposed to represent
2184@cpi{}, it's got several errors. Press @kbd{`} to edit this number.
2185Now use the normal Emacs cursor motion and editing keys to change
2186the second 4 to a 5, and to transpose the 3 and the 9. When you
2187press @key{RET}, the number on the stack will be replaced by your
2188new number. This works for formulas, vectors, and all other types
2189of values you can put on the stack. The @kbd{`} key also works
2190during entry of a number or algebraic formula.
2191
2192@node Modes Tutorial, , Undo Tutorial, Basic Tutorial
2193@subsection Mode-Setting Commands
2194
2195@noindent
2196Calc has many types of @dfn{modes} that affect the way it interprets
2197your commands or the way it displays data. We have already seen one
2198mode, namely Algebraic mode. There are many others, too; we'll
2199try some of the most common ones here.
2200
2201Perhaps the most fundamental mode in Calc is the current @dfn{precision}.
2202Notice the @samp{12} on the Calc window's mode line:
2203
2204@smallexample
92e15881 2205--%*-Calc: 12 Deg (Calculator)----All------
4009494e
GM
2206@end smallexample
2207
2208@noindent
2209Most of the symbols there are Emacs things you don't need to worry
2210about, but the @samp{12} and the @samp{Deg} are mode indicators.
2211The @samp{12} means that calculations should always be carried to
221212 significant figures. That is why, when we type @kbd{1 @key{RET} 7 /},
2213we get @expr{0.142857142857} with exactly 12 digits, not counting
2214leading and trailing zeros.
2215
2216You can set the precision to anything you like by pressing @kbd{p},
2217then entering a suitable number. Try pressing @kbd{p 30 @key{RET}},
2218then doing @kbd{1 @key{RET} 7 /} again:
2219
2220@smallexample
2221@group
22221: 0.142857142857
22232: 0.142857142857142857142857142857
2224 .
2225@end group
2226@end smallexample
2227
2228Although the precision can be set arbitrarily high, Calc always
2229has to have @emph{some} value for the current precision. After
2230all, the true value @expr{1/7} is an infinitely repeating decimal;
2231Calc has to stop somewhere.
2232
2233Of course, calculations are slower the more digits you request.
2234Press @w{@kbd{p 12}} now to set the precision back down to the default.
2235
2236Calculations always use the current precision. For example, even
2237though we have a 30-digit value for @expr{1/7} on the stack, if
2238we use it in a calculation in 12-digit mode it will be rounded
2239down to 12 digits before it is used. Try it; press @key{RET} to
2240duplicate the number, then @w{@kbd{1 +}}. Notice that the @key{RET}
2241key didn't round the number, because it doesn't do any calculation.
2242But the instant we pressed @kbd{+}, the number was rounded down.
2243
2244@smallexample
2245@group
22461: 0.142857142857
22472: 0.142857142857142857142857142857
22483: 1.14285714286
2249 .
2250@end group
2251@end smallexample
2252
2253@noindent
2254In fact, since we added a digit on the left, we had to lose one
2255digit on the right from even the 12-digit value of @expr{1/7}.
2256
2257How did we get more than 12 digits when we computed @samp{2^3^4}? The
2258answer is that Calc makes a distinction between @dfn{integers} and
2259@dfn{floating-point} numbers, or @dfn{floats}. An integer is a number
2260that does not contain a decimal point. There is no such thing as an
2261``infinitely repeating fraction integer,'' so Calc doesn't have to limit
2262itself. If you asked for @samp{2^10000} (don't try this!), you would
2263have to wait a long time but you would eventually get an exact answer.
2264If you ask for @samp{2.^10000}, you will quickly get an answer which is
2265correct only to 12 places. The decimal point tells Calc that it should
2266use floating-point arithmetic to get the answer, not exact integer
2267arithmetic.
2268
2269You can use the @kbd{F} (@code{calc-floor}) command to convert a
2270floating-point value to an integer, and @kbd{c f} (@code{calc-float})
2271to convert an integer to floating-point form.
2272
2273Let's try entering that last calculation:
2274
2275@smallexample
2276@group
22771: 2. 2: 2. 1: 1.99506311689e3010
2278 . 1: 10000 .
2279 .
2280
2281 2.0 @key{RET} 10000 @key{RET} ^
2282@end group
2283@end smallexample
2284
2285@noindent
2286@cindex Scientific notation, entry of
2287Notice the letter @samp{e} in there. It represents ``times ten to the
2288power of,'' and is used by Calc automatically whenever writing the
2289number out fully would introduce more extra zeros than you probably
2290want to see. You can enter numbers in this notation, too.
2291
2292@smallexample
2293@group
22941: 2. 2: 2. 1: 1.99506311678e3010
2295 . 1: 10000. .
2296 .
2297
2298 2.0 @key{RET} 1e4 @key{RET} ^
2299@end group
2300@end smallexample
2301
2302@cindex Round-off errors
2303@noindent
2304Hey, the answer is different! Look closely at the middle columns
2305of the two examples. In the first, the stack contained the
2306exact integer @expr{10000}, but in the second it contained
2307a floating-point value with a decimal point. When you raise a
2308number to an integer power, Calc uses repeated squaring and
2309multiplication to get the answer. When you use a floating-point
2310power, Calc uses logarithms and exponentials. As you can see,
2311a slight error crept in during one of these methods. Which
2312one should we trust? Let's raise the precision a bit and find
2313out:
2314
2315@smallexample
2316@group
2317 . 1: 2. 2: 2. 1: 1.995063116880828e3010
2318 . 1: 10000. .
2319 .
2320
2321 p 16 @key{RET} 2. @key{RET} 1e4 ^ p 12 @key{RET}
2322@end group
2323@end smallexample
2324
2325@noindent
2326@cindex Guard digits
2327Presumably, it doesn't matter whether we do this higher-precision
2328calculation using an integer or floating-point power, since we
2329have added enough ``guard digits'' to trust the first 12 digits
2330no matter what. And the verdict is@dots{} Integer powers were more
2331accurate; in fact, the result was only off by one unit in the
2332last place.
2333
2334@cindex Guard digits
2335Calc does many of its internal calculations to a slightly higher
2336precision, but it doesn't always bump the precision up enough.
2337In each case, Calc added about two digits of precision during
2338its calculation and then rounded back down to 12 digits
2339afterward. In one case, it was enough; in the other, it
2340wasn't. If you really need @var{x} digits of precision, it
2341never hurts to do the calculation with a few extra guard digits.
2342
2343What if we want guard digits but don't want to look at them?
2344We can set the @dfn{float format}. Calc supports four major
2345formats for floating-point numbers, called @dfn{normal},
2346@dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering
2347notation}. You get them by pressing @w{@kbd{d n}}, @kbd{d f},
2348@kbd{d s}, and @kbd{d e}, respectively. In each case, you can
2349supply a numeric prefix argument which says how many digits
2350should be displayed. As an example, let's put a few numbers
2351onto the stack and try some different display modes. First,
2352use @kbd{M-0 @key{DEL}} to clear the stack, then enter the four
2353numbers shown here:
2354
2355@smallexample
2356@group
23574: 12345 4: 12345 4: 12345 4: 12345 4: 12345
23583: 12345. 3: 12300. 3: 1.2345e4 3: 1.23e4 3: 12345.000
23592: 123.45 2: 123. 2: 1.2345e2 2: 1.23e2 2: 123.450
23601: 12.345 1: 12.3 1: 1.2345e1 1: 1.23e1 1: 12.345
2361 . . . . .
2362
2363 d n M-3 d n d s M-3 d s M-3 d f
2364@end group
2365@end smallexample
2366
2367@noindent
2368Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down
2369to three significant digits, but then when we typed @kbd{d s} all
2370five significant figures reappeared. The float format does not
2371affect how numbers are stored, it only affects how they are
2372displayed. Only the current precision governs the actual rounding
2373of numbers in the Calculator's memory.
2374
2375Engineering notation, not shown here, is like scientific notation
2376except the exponent (the power-of-ten part) is always adjusted to be
2377a multiple of three (as in ``kilo,'' ``micro,'' etc.). As a result
2378there will be one, two, or three digits before the decimal point.
2379
2380Whenever you change a display-related mode, Calc redraws everything
2381in the stack. This may be slow if there are many things on the stack,
2382so Calc allows you to type shift-@kbd{H} before any mode command to
2383prevent it from updating the stack. Anything Calc displays after the
2384mode-changing command will appear in the new format.
2385
2386@smallexample
2387@group
23884: 12345 4: 12345 4: 12345 4: 12345 4: 12345
23893: 12345.000 3: 12345.000 3: 12345.000 3: 1.2345e4 3: 12345.
23902: 123.450 2: 123.450 2: 1.2345e1 2: 1.2345e1 2: 123.45
23911: 12.345 1: 1.2345e1 1: 1.2345e2 1: 1.2345e2 1: 12.345
2392 . . . . .
2393
2394 H d s @key{DEL} U @key{TAB} d @key{SPC} d n
2395@end group
2396@end smallexample
2397
2398@noindent
2399Here the @kbd{H d s} command changes to scientific notation but without
2400updating the screen. Deleting the top stack entry and undoing it back
2401causes it to show up in the new format; swapping the top two stack
2402entries reformats both entries. The @kbd{d @key{SPC}} command refreshes the
2403whole stack. The @kbd{d n} command changes back to the normal float
2404format; since it doesn't have an @kbd{H} prefix, it also updates all
2405the stack entries to be in @kbd{d n} format.
2406
2407Notice that the integer @expr{12345} was not affected by any
2408of the float formats. Integers are integers, and are always
2409displayed exactly.
2410
2411@cindex Large numbers, readability
2412Large integers have their own problems. Let's look back at
2413the result of @kbd{2^3^4}.
2414
2415@example
24162417851639229258349412352
2417@end example
2418
2419@noindent
2420Quick---how many digits does this have? Try typing @kbd{d g}:
2421
2422@example
24232,417,851,639,229,258,349,412,352
2424@end example
2425
2426@noindent
2427Now how many digits does this have? It's much easier to tell!
2428We can actually group digits into clumps of any size. Some
2429people prefer @kbd{M-5 d g}:
2430
2431@example
243224178,51639,22925,83494,12352
2433@end example
2434
2435Let's see what happens to floating-point numbers when they are grouped.
2436First, type @kbd{p 25 @key{RET}} to make sure we have enough precision
2437to get ourselves into trouble. Now, type @kbd{1e13 /}:
2438
2439@example
244024,17851,63922.9258349412352
2441@end example
2442
2443@noindent
2444The integer part is grouped but the fractional part isn't. Now try
2445@kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five):
2446
2447@example
244824,17851,63922.92583,49412,352
2449@end example
2450
2451If you find it hard to tell the decimal point from the commas, try
2452changing the grouping character to a space with @kbd{d , @key{SPC}}:
2453
2454@example
245524 17851 63922.92583 49412 352
2456@end example
2457
2458Type @kbd{d , ,} to restore the normal grouping character, then
2459@kbd{d g} again to turn grouping off. Also, press @kbd{p 12} to
2460restore the default precision.
2461
2462Press @kbd{U} enough times to get the original big integer back.
2463(Notice that @kbd{U} does not undo each mode-setting command; if
2464you want to undo a mode-setting command, you have to do it yourself.)
2465Now, type @kbd{d r 16 @key{RET}}:
2466
2467@example
246816#200000000000000000000
2469@end example
2470
2471@noindent
2472The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form.
2473Suddenly it looks pretty simple; this should be no surprise, since we
2474got this number by computing a power of two, and 16 is a power of 2.
2475In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary
2476form:
2477
2478@example
24792#1000000000000000000000000000000000000000000000000000000 @dots{}
2480@end example
2481
2482@noindent
2483We don't have enough space here to show all the zeros! They won't
2484fit on a typical screen, either, so you will have to use horizontal
2485scrolling to see them all. Press @kbd{<} and @kbd{>} to scroll the
2486stack window left and right by half its width. Another way to view
2487something large is to press @kbd{`} (back-quote) to edit the top of
2488stack in a separate window. (Press @kbd{C-c C-c} when you are done.)
2489
2490You can enter non-decimal numbers using the @kbd{#} symbol, too.
2491Let's see what the hexadecimal number @samp{5FE} looks like in
2492binary. Type @kbd{16#5FE} (the letters can be typed in upper or
2493lower case; they will always appear in upper case). It will also
2494help to turn grouping on with @kbd{d g}:
2495
2496@example
24972#101,1111,1110
2498@end example
2499
2500Notice that @kbd{d g} groups by fours by default if the display radix
2501is binary or hexadecimal, but by threes if it is decimal, octal, or any
2502other radix.
2503
2504Now let's see that number in decimal; type @kbd{d r 10}:
2505
2506@example
25071,534
2508@end example
2509
2510Numbers are not @emph{stored} with any particular radix attached. They're
2511just numbers; they can be entered in any radix, and are always displayed
2512in whatever radix you've chosen with @kbd{d r}. The current radix applies
2513to integers, fractions, and floats.
2514
2515@cindex Roundoff errors, in non-decimal numbers
2516(@bullet{}) @strong{Exercise 1.} Your friend Joe tried to enter one-third
2517as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12. He got
2518@samp{3#0.0222222...} (with 25 2's) in the display. When he multiplied
2519that by three, he got @samp{3#0.222222...} instead of the expected
2520@samp{3#1}. Next, Joe entered @samp{3#0.2} and, to his great relief,
2521saw @samp{3#0.2} on the screen. But when he typed @kbd{2 /}, he got
2522@samp{3#0.10000001} (some zeros omitted). What's going on here?
2523@xref{Modes Answer 1, 1}. (@bullet{})
2524
2525@cindex Scientific notation, in non-decimal numbers
2526(@bullet{}) @strong{Exercise 2.} Scientific notation works in non-decimal
2527modes in the natural way (the exponent is a power of the radix instead of
2528a power of ten, although the exponent itself is always written in decimal).
2529Thus @samp{8#1.23e3 = 8#1230.0}. Suppose we have the hexadecimal number
2530@samp{f.e8f} times 16 to the 15th power: We write @samp{16#f.e8fe15}.
2531What is wrong with this picture? What could we write instead that would
2532work better? @xref{Modes Answer 2, 2}. (@bullet{})
2533
2534The @kbd{m} prefix key has another set of modes, relating to the way
2535Calc interprets your inputs and does computations. Whereas @kbd{d}-prefix
2536modes generally affect the way things look, @kbd{m}-prefix modes affect
2537the way they are actually computed.
2538
2539The most popular @kbd{m}-prefix mode is the @dfn{angular mode}. Notice
2540the @samp{Deg} indicator in the mode line. This means that if you use
2541a command that interprets a number as an angle, it will assume the
2542angle is measured in degrees. For example,
2543
2544@smallexample
2545@group
25461: 45 1: 0.707106781187 1: 0.500000000001 1: 0.5
2547 . . . .
2548
2549 45 S 2 ^ c 1
2550@end group
2551@end smallexample
2552
2553@noindent
2554The shift-@kbd{S} command computes the sine of an angle. The sine
40ba43b4 2555of 45 degrees is
4009494e 2556@texline @math{\sqrt{2}/2};
40ba43b4 2557@infoline @expr{sqrt(2)/2};
4009494e 2558squaring this yields @expr{2/4 = 0.5}. However, there has been a slight
40ba43b4 2559roundoff error because the representation of
4009494e 2560@texline @math{\sqrt{2}/2}
40ba43b4 2561@infoline @expr{sqrt(2)/2}
4009494e
GM
2562wasn't exact. The @kbd{c 1} command is a handy way to clean up numbers
2563in this case; it temporarily reduces the precision by one digit while it
2564re-rounds the number on the top of the stack.
2565
2566@cindex Roundoff errors, examples
2567(@bullet{}) @strong{Exercise 3.} Your friend Joe computed the sine
2568of 45 degrees as shown above, then, hoping to avoid an inexact
2569result, he increased the precision to 16 digits before squaring.
2570What happened? @xref{Modes Answer 3, 3}. (@bullet{})
2571
2572To do this calculation in radians, we would type @kbd{m r} first.
2573(The indicator changes to @samp{Rad}.) 45 degrees corresponds to
2574@cpiover{4} radians. To get @cpi{}, press the @kbd{P} key. (Once
2575again, this is a shifted capital @kbd{P}. Remember, unshifted
2576@kbd{p} sets the precision.)
2577
2578@smallexample
2579@group
25801: 3.14159265359 1: 0.785398163398 1: 0.707106781187
2581 . . .
2582
2583 P 4 / m r S
2584@end group
2585@end smallexample
2586
2587Likewise, inverse trigonometric functions generate results in
2588either radians or degrees, depending on the current angular mode.
2589
2590@smallexample
2591@group
25921: 0.707106781187 1: 0.785398163398 1: 45.
2593 . . .
2594
2595 .5 Q m r I S m d U I S
2596@end group
2597@end smallexample
2598
2599@noindent
40ba43b4 2600Here we compute the Inverse Sine of
4009494e 2601@texline @math{\sqrt{0.5}},
40ba43b4 2602@infoline @expr{sqrt(0.5)},
4009494e
GM
2603first in radians, then in degrees.
2604
2605Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees
2606and vice-versa.
2607
2608@smallexample
2609@group
26101: 45 1: 0.785398163397 1: 45.
2611 . . .
2612
2613 45 c r c d
2614@end group
2615@end smallexample
2616
2617Another interesting mode is @dfn{Fraction mode}. Normally,
2618dividing two integers produces a floating-point result if the
2619quotient can't be expressed as an exact integer. Fraction mode
2620causes integer division to produce a fraction, i.e., a rational
2621number, instead.
2622
2623@smallexample
2624@group
26252: 12 1: 1.33333333333 1: 4:3
26261: 9 . .
2627 .
2628
2629 12 @key{RET} 9 / m f U / m f
2630@end group
2631@end smallexample
2632
2633@noindent
2634In the first case, we get an approximate floating-point result.
2635In the second case, we get an exact fractional result (four-thirds).
2636
2637You can enter a fraction at any time using @kbd{:} notation.
2638(Calc uses @kbd{:} instead of @kbd{/} as the fraction separator
2639because @kbd{/} is already used to divide the top two stack
2640elements.) Calculations involving fractions will always
2641produce exact fractional results; Fraction mode only says
2642what to do when dividing two integers.
2643
2644@cindex Fractions vs. floats
2645@cindex Floats vs. fractions
2646(@bullet{}) @strong{Exercise 4.} If fractional arithmetic is exact,
2647why would you ever use floating-point numbers instead?
2648@xref{Modes Answer 4, 4}. (@bullet{})
2649
2650Typing @kbd{m f} doesn't change any existing values in the stack.
2651In the above example, we had to Undo the division and do it over
2652again when we changed to Fraction mode. But if you use the
2653evaluates-to operator you can get commands like @kbd{m f} to
2654recompute for you.
2655
2656@smallexample
2657@group
26581: 12 / 9 => 1.33333333333 1: 12 / 9 => 1.333 1: 12 / 9 => 4:3
2659 . . .
2660
2661 ' 12/9 => @key{RET} p 4 @key{RET} m f
2662@end group
2663@end smallexample
2664
2665@noindent
2666In this example, the righthand side of the @samp{=>} operator
2667on the stack is recomputed when we change the precision, then
2668again when we change to Fraction mode. All @samp{=>} expressions
2669on the stack are recomputed every time you change any mode that
2670might affect their values.
2671
2672@node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial
2673@section Arithmetic Tutorial
2674
2675@noindent
2676In this section, we explore the arithmetic and scientific functions
2677available in the Calculator.
2678
2679The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/},
2680and @kbd{^}. Each normally takes two numbers from the top of the stack
2681and pushes back a result. The @kbd{n} and @kbd{&} keys perform
2682change-sign and reciprocal operations, respectively.
2683
2684@smallexample
2685@group
26861: 5 1: 0.2 1: 5. 1: -5. 1: 5.
2687 . . . . .
2688
2689 5 & & n n
2690@end group
2691@end smallexample
2692
2693@cindex Binary operators
2694You can apply a ``binary operator'' like @kbd{+} across any number of
2695stack entries by giving it a numeric prefix. You can also apply it
2696pairwise to several stack elements along with the top one if you use
2697a negative prefix.
2698
2699@smallexample
2700@group
27013: 2 1: 9 3: 2 4: 2 3: 12
27022: 3 . 2: 3 3: 3 2: 13
27031: 4 1: 4 2: 4 1: 14
2704 . . 1: 10 .
2705 .
2706
27072 @key{RET} 3 @key{RET} 4 M-3 + U 10 M-- M-3 +
2708@end group
2709@end smallexample
2710
2711@cindex Unary operators
2712You can apply a ``unary operator'' like @kbd{&} to the top @var{n}
2713stack entries with a numeric prefix, too.
2714
2715@smallexample
2716@group
27173: 2 3: 0.5 3: 0.5
27182: 3 2: 0.333333333333 2: 3.
27191: 4 1: 0.25 1: 4.
2720 . . .
2721
27222 @key{RET} 3 @key{RET} 4 M-3 & M-2 &
2723@end group
2724@end smallexample
2725
2726Notice that the results here are left in floating-point form.
2727We can convert them back to integers by pressing @kbd{F}, the
2728``floor'' function. This function rounds down to the next lower
2729integer. There is also @kbd{R}, which rounds to the nearest
2730integer.
2731
2732@smallexample
2733@group
27347: 2. 7: 2 7: 2
27356: 2.4 6: 2 6: 2
27365: 2.5 5: 2 5: 3
27374: 2.6 4: 2 4: 3
27383: -2. 3: -2 3: -2
27392: -2.4 2: -3 2: -2
27401: -2.6 1: -3 1: -3
2741 . . .
2742
2743 M-7 F U M-7 R
2744@end group
2745@end smallexample
2746
2747Since dividing-and-flooring (i.e., ``integer quotient'') is such a
2748common operation, Calc provides a special command for that purpose, the
2749backslash @kbd{\}. Another common arithmetic operator is @kbd{%}, which
2750computes the remainder that would arise from a @kbd{\} operation, i.e.,
2751the ``modulo'' of two numbers. For example,
2752
2753@smallexample
2754@group
27552: 1234 1: 12 2: 1234 1: 34
27561: 100 . 1: 100 .
2757 . .
2758
27591234 @key{RET} 100 \ U %
2760@end group
2761@end smallexample
2762
2763These commands actually work for any real numbers, not just integers.
2764
2765@smallexample
2766@group
27672: 3.1415 1: 3 2: 3.1415 1: 0.1415
27681: 1 . 1: 1 .
2769 . .
2770
27713.1415 @key{RET} 1 \ U %
2772@end group
2773@end smallexample
2774
2775(@bullet{}) @strong{Exercise 1.} The @kbd{\} command would appear to be a
2776frill, since you could always do the same thing with @kbd{/ F}. Think
2777of a situation where this is not true---@kbd{/ F} would be inadequate.
2778Now think of a way you could get around the problem if Calc didn't
2779provide a @kbd{\} command. @xref{Arithmetic Answer 1, 1}. (@bullet{})
2780
2781We've already seen the @kbd{Q} (square root) and @kbd{S} (sine)
2782commands. Other commands along those lines are @kbd{C} (cosine),
2783@kbd{T} (tangent), @kbd{E} (@expr{e^x}) and @kbd{L} (natural
2784logarithm). These can be modified by the @kbd{I} (inverse) and
2785@kbd{H} (hyperbolic) prefix keys.
2786
2787Let's compute the sine and cosine of an angle, and verify the
40ba43b4 2788identity
4009494e 2789@texline @math{\sin^2x + \cos^2x = 1}.
40ba43b4 2790@infoline @expr{sin(x)^2 + cos(x)^2 = 1}.
4009494e
GM
2791We'll arbitrarily pick @mathit{-64} degrees as a good value for @expr{x}.
2792With the angular mode set to degrees (type @w{@kbd{m d}}), do:
2793
2794@smallexample
2795@group
27962: -64 2: -64 2: -0.89879 2: -0.89879 1: 1.
27971: -64 1: -0.89879 1: -64 1: 0.43837 .
2798 . . . .
2799
2800 64 n @key{RET} @key{RET} S @key{TAB} C f h
2801@end group
2802@end smallexample
2803
2804@noindent
2805(For brevity, we're showing only five digits of the results here.
2806You can of course do these calculations to any precision you like.)
2807
2808Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum
2809of squares, command.
2810
40ba43b4 2811Another identity is
4009494e
GM
2812@texline @math{\displaystyle\tan x = {\sin x \over \cos x}}.
2813@infoline @expr{tan(x) = sin(x) / cos(x)}.
2814@smallexample
2815@group
2816
28172: -0.89879 1: -2.0503 1: -64.
28181: 0.43837 . .
2819 .
2820
2821 U / I T
2822@end group
2823@end smallexample
2824
2825A physical interpretation of this calculation is that if you move
2826@expr{0.89879} units downward and @expr{0.43837} units to the right,
2827your direction of motion is @mathit{-64} degrees from horizontal. Suppose
2828we move in the opposite direction, up and to the left:
2829
2830@smallexample
2831@group
28322: -0.89879 2: 0.89879 1: -2.0503 1: -64.
28331: 0.43837 1: -0.43837 . .
2834 . .
2835
2836 U U M-2 n / I T
2837@end group
2838@end smallexample
2839
2840@noindent
2841How can the angle be the same? The answer is that the @kbd{/} operation
2842loses information about the signs of its inputs. Because the quotient
2843is negative, we know exactly one of the inputs was negative, but we
2844can't tell which one. There is an @kbd{f T} [@code{arctan2}] function which
2845computes the inverse tangent of the quotient of a pair of numbers.
2846Since you feed it the two original numbers, it has enough information
2847to give you a full 360-degree answer.
2848
2849@smallexample
2850@group
28512: 0.89879 1: 116. 3: 116. 2: 116. 1: 180.
28521: -0.43837 . 2: -0.89879 1: -64. .
2853 . 1: 0.43837 .
2854 .
2855
2856 U U f T M-@key{RET} M-2 n f T -
2857@end group
2858@end smallexample
2859
2860@noindent
2861The resulting angles differ by 180 degrees; in other words, they
2862point in opposite directions, just as we would expect.
2863
2864The @key{META}-@key{RET} we used in the third step is the
2865``last-arguments'' command. It is sort of like Undo, except that it
2866restores the arguments of the last command to the stack without removing
2867the command's result. It is useful in situations like this one,
2868where we need to do several operations on the same inputs. We could
2869have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate
2870the top two stack elements right after the @kbd{U U}, then a pair of
2871@kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates.
2872
2873A similar identity is supposed to hold for hyperbolic sines and cosines,
2874except that it is the @emph{difference}
2875@texline @math{\cosh^2x - \sinh^2x}
40ba43b4 2876@infoline @expr{cosh(x)^2 - sinh(x)^2}
4009494e
GM
2877that always equals one. Let's try to verify this identity.
2878
2879@smallexample
2880@group
28812: -64 2: -64 2: -64 2: 9.7192e54 2: 9.7192e54
28821: -64 1: -3.1175e27 1: 9.7192e54 1: -64 1: 9.7192e54
2883 . . . . .
2884
2885 64 n @key{RET} @key{RET} H C 2 ^ @key{TAB} H S 2 ^
2886@end group
2887@end smallexample
2888
2889@noindent
2890@cindex Roundoff errors, examples
2891Something's obviously wrong, because when we subtract these numbers
2892the answer will clearly be zero! But if you think about it, if these
2893numbers @emph{did} differ by one, it would be in the 55th decimal
2894place. The difference we seek has been lost entirely to roundoff
2895error.
2896
2897We could verify this hypothesis by doing the actual calculation with,
2898say, 60 decimal places of precision. This will be slow, but not
2899enormously so. Try it if you wish; sure enough, the answer is
29000.99999, reasonably close to 1.
2901
2902Of course, a more reasonable way to verify the identity is to use
2903a more reasonable value for @expr{x}!
2904
2905@cindex Common logarithm
2906Some Calculator commands use the Hyperbolic prefix for other purposes.
2907The logarithm and exponential functions, for example, work to the base
2908@expr{e} normally but use base-10 instead if you use the Hyperbolic
2909prefix.
2910
2911@smallexample
2912@group
29131: 1000 1: 6.9077 1: 1000 1: 3
2914 . . . .
2915
2916 1000 L U H L
2917@end group
2918@end smallexample
2919
2920@noindent
2921First, we mistakenly compute a natural logarithm. Then we undo
2922and compute a common logarithm instead.
2923
2924The @kbd{B} key computes a general base-@var{b} logarithm for any
2925value of @var{b}.
2926
2927@smallexample
2928@group
29292: 1000 1: 3 1: 1000. 2: 1000. 1: 6.9077
29301: 10 . . 1: 2.71828 .
2931 . .
2932
2933 1000 @key{RET} 10 B H E H P B
2934@end group
2935@end smallexample
2936
2937@noindent
2938Here we first use @kbd{B} to compute the base-10 logarithm, then use
2939the ``hyperbolic'' exponential as a cheap hack to recover the number
29401000, then use @kbd{B} again to compute the natural logarithm. Note
2941that @kbd{P} with the hyperbolic prefix pushes the constant @expr{e}
2942onto the stack.
2943
2944You may have noticed that both times we took the base-10 logarithm
2945of 1000, we got an exact integer result. Calc always tries to give
2946an exact rational result for calculations involving rational numbers
2947where possible. But when we used @kbd{H E}, the result was a
2948floating-point number for no apparent reason. In fact, if we had
2949computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an
2950exact integer 1000. But the @kbd{H E} command is rigged to generate
2951a floating-point result all of the time so that @kbd{1000 H E} will
2952not waste time computing a thousand-digit integer when all you
2953probably wanted was @samp{1e1000}.
2954
2955(@bullet{}) @strong{Exercise 2.} Find a pair of integer inputs to
2956the @kbd{B} command for which Calc could find an exact rational
2957result but doesn't. @xref{Arithmetic Answer 2, 2}. (@bullet{})
2958
2959The Calculator also has a set of functions relating to combinatorics
2960and statistics. You may be familiar with the @dfn{factorial} function,
2961which computes the product of all the integers up to a given number.
2962
2963@smallexample
2964@group
29651: 100 1: 93326215443... 1: 100. 1: 9.3326e157
2966 . . . .
2967
2968 100 ! U c f !
2969@end group
2970@end smallexample
2971
2972@noindent
2973Recall, the @kbd{c f} command converts the integer or fraction at the
2974top of the stack to floating-point format. If you take the factorial
2975of a floating-point number, you get a floating-point result
2976accurate to the current precision. But if you give @kbd{!} an
2977exact integer, you get an exact integer result (158 digits long
2978in this case).
2979
2980If you take the factorial of a non-integer, Calc uses a generalized
2981factorial function defined in terms of Euler's Gamma function
2982@texline @math{\Gamma(n)}
2983@infoline @expr{gamma(n)}
2984(which is itself available as the @kbd{f g} command).
2985
2986@smallexample
2987@group
29883: 4. 3: 24. 1: 5.5 1: 52.342777847
29892: 4.5 2: 52.3427777847 . .
29901: 5. 1: 120.
2991 . .
2992
2993 M-3 ! M-0 @key{DEL} 5.5 f g
2994@end group
2995@end smallexample
2996
2997@noindent
40ba43b4 2998Here we verify the identity
4009494e
GM
2999@texline @math{n! = \Gamma(n+1)}.
3000@infoline @expr{@var{n}!@: = gamma(@var{n}+1)}.
3001
3002The binomial coefficient @var{n}-choose-@var{m}
3003@texline or @math{\displaystyle {n \choose m}}
3004is defined by
3005@texline @math{\displaystyle {n! \over m! \, (n-m)!}}
3006@infoline @expr{n!@: / m!@: (n-m)!}
3007for all reals @expr{n} and @expr{m}. The intermediate results in this
3008formula can become quite large even if the final result is small; the
3009@kbd{k c} command computes a binomial coefficient in a way that avoids
3010large intermediate values.
3011
3012The @kbd{k} prefix key defines several common functions out of
3013combinatorics and number theory. Here we compute the binomial
3014coefficient 30-choose-20, then determine its prime factorization.
3015
3016@smallexample
3017@group
30182: 30 1: 30045015 1: [3, 3, 5, 7, 11, 13, 23, 29]
30191: 20 . .
3020 .
3021
3022 30 @key{RET} 20 k c k f
3023@end group
3024@end smallexample
3025
3026@noindent
a8b14149
JB
3027You can verify these prime factors by using @kbd{V R *} to multiply
3028together the elements of this vector. The result is the original
3029number, 30045015.
4009494e
GM
3030
3031@cindex Hash tables
3032Suppose a program you are writing needs a hash table with at least
303310000 entries. It's best to use a prime number as the actual size
3034of a hash table. Calc can compute the next prime number after 10000:
3035
3036@smallexample
3037@group
30381: 10000 1: 10007 1: 9973
3039 . . .
3040
3041 10000 k n I k n
3042@end group
3043@end smallexample
3044
3045@noindent
3046Just for kicks we've also computed the next prime @emph{less} than
304710000.
3048
3049@c [fix-ref Financial Functions]
3050@xref{Financial Functions}, for a description of the Calculator
3051commands that deal with business and financial calculations (functions
3052like @code{pv}, @code{rate}, and @code{sln}).
3053
3054@c [fix-ref Binary Number Functions]
3055@xref{Binary Functions}, to read about the commands for operating
3056on binary numbers (like @code{and}, @code{xor}, and @code{lsh}).
3057
3058@node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
3059@section Vector/Matrix Tutorial
3060
3061@noindent
3062A @dfn{vector} is a list of numbers or other Calc data objects.
3063Calc provides a large set of commands that operate on vectors. Some
3064are familiar operations from vector analysis. Others simply treat
3065a vector as a list of objects.
3066
3067@menu
3068* Vector Analysis Tutorial::
3069* Matrix Tutorial::
3070* List Tutorial::
3071@end menu
3072
3073@node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
3074@subsection Vector Analysis
3075
3076@noindent
3077If you add two vectors, the result is a vector of the sums of the
3078elements, taken pairwise.
3079
3080@smallexample
3081@group
30821: [1, 2, 3] 2: [1, 2, 3] 1: [8, 8, 3]
3083 . 1: [7, 6, 0] .
3084 .
3085
3086 [1,2,3] s 1 [7 6 0] s 2 +
3087@end group
3088@end smallexample
3089
3090@noindent
3091Note that we can separate the vector elements with either commas or
3092spaces. This is true whether we are using incomplete vectors or
3093algebraic entry. The @kbd{s 1} and @kbd{s 2} commands save these
3094vectors so we can easily reuse them later.
3095
3096If you multiply two vectors, the result is the sum of the products
3097of the elements taken pairwise. This is called the @dfn{dot product}
3098of the vectors.
3099
3100@smallexample
3101@group
31022: [1, 2, 3] 1: 19
31031: [7, 6, 0] .
3104 .
3105
3106 r 1 r 2 *
3107@end group
3108@end smallexample
3109
3110@cindex Dot product
3111The dot product of two vectors is equal to the product of their
3112lengths times the cosine of the angle between them. (Here the vector
3113is interpreted as a line from the origin @expr{(0,0,0)} to the
3114specified point in three-dimensional space.) The @kbd{A}
3115(absolute value) command can be used to compute the length of a
3116vector.
3117
3118@smallexample
3119@group
31203: 19 3: 19 1: 0.550782 1: 56.579
31212: [1, 2, 3] 2: 3.741657 . .
31221: [7, 6, 0] 1: 9.219544
3123 . .
3124
3125 M-@key{RET} M-2 A * / I C
3126@end group
3127@end smallexample
3128
3129@noindent
3130First we recall the arguments to the dot product command, then
3131we compute the absolute values of the top two stack entries to
3132obtain the lengths of the vectors, then we divide the dot product
3133by the product of the lengths to get the cosine of the angle.
3134The inverse cosine finds that the angle between the vectors
3135is about 56 degrees.
3136
3137@cindex Cross product
3138@cindex Perpendicular vectors
3139The @dfn{cross product} of two vectors is a vector whose length
3140is the product of the lengths of the inputs times the sine of the
3141angle between them, and whose direction is perpendicular to both
3142input vectors. Unlike the dot product, the cross product is
3143defined only for three-dimensional vectors. Let's double-check
3144our computation of the angle using the cross product.
3145
3146@smallexample
3147@group
31482: [1, 2, 3] 3: [-18, 21, -8] 1: [-0.52, 0.61, -0.23] 1: 56.579
31491: [7, 6, 0] 2: [1, 2, 3] . .
3150 . 1: [7, 6, 0]
3151 .
3152
3153 r 1 r 2 V C s 3 M-@key{RET} M-2 A * / A I S
3154@end group
3155@end smallexample
3156
3157@noindent
3158First we recall the original vectors and compute their cross product,
3159which we also store for later reference. Now we divide the vector
3160by the product of the lengths of the original vectors. The length of
3161this vector should be the sine of the angle; sure enough, it is!
3162
3163@c [fix-ref General Mode Commands]
3164Vector-related commands generally begin with the @kbd{v} prefix key.
3165Some are uppercase letters and some are lowercase. To make it easier
3166to type these commands, the shift-@kbd{V} prefix key acts the same as
3167the @kbd{v} key. (@xref{General Mode Commands}, for a way to make all
3168prefix keys have this property.)
3169
3170If we take the dot product of two perpendicular vectors we expect
3171to get zero, since the cosine of 90 degrees is zero. Let's check
3172that the cross product is indeed perpendicular to both inputs:
3173
3174@smallexample
3175@group
31762: [1, 2, 3] 1: 0 2: [7, 6, 0] 1: 0
31771: [-18, 21, -8] . 1: [-18, 21, -8] .
3178 . .
3179
3180 r 1 r 3 * @key{DEL} r 2 r 3 *
3181@end group
3182@end smallexample
3183
3184@cindex Normalizing a vector
3185@cindex Unit vectors
3186(@bullet{}) @strong{Exercise 1.} Given a vector on the top of the
3187stack, what keystrokes would you use to @dfn{normalize} the
3188vector, i.e., to reduce its length to one without changing its
3189direction? @xref{Vector Answer 1, 1}. (@bullet{})
3190
3191(@bullet{}) @strong{Exercise 2.} Suppose a certain particle can be
3192at any of several positions along a ruler. You have a list of
3193those positions in the form of a vector, and another list of the
3194probabilities for the particle to be at the corresponding positions.
3195Find the average position of the particle.
3196@xref{Vector Answer 2, 2}. (@bullet{})
3197
3198@node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
3199@subsection Matrices
3200
3201@noindent
3202A @dfn{matrix} is just a vector of vectors, all the same length.
3203This means you can enter a matrix using nested brackets. You can
3204also use the semicolon character to enter a matrix. We'll show
3205both methods here:
3206
3207@smallexample
3208@group
32091: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3210 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3211 . .
3212
3213 [[1 2 3] [4 5 6]] ' [1 2 3; 4 5 6] @key{RET}
3214@end group
3215@end smallexample
3216
3217@noindent
3218We'll be using this matrix again, so type @kbd{s 4} to save it now.
3219
3220Note that semicolons work with incomplete vectors, but they work
3221better in algebraic entry. That's why we use the apostrophe in
3222the second example.
3223
3224When two matrices are multiplied, the lefthand matrix must have
3225the same number of columns as the righthand matrix has rows.
3226Row @expr{i}, column @expr{j} of the result is effectively the
3227dot product of row @expr{i} of the left matrix by column @expr{j}
3228of the right matrix.
3229
3230If we try to duplicate this matrix and multiply it by itself,
3231the dimensions are wrong and the multiplication cannot take place:
3232
3233@smallexample
3234@group
32351: [ [ 1, 2, 3 ] * [ [ 1, 2, 3 ]
3236 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3237 .
3238
3239 @key{RET} *
3240@end group
3241@end smallexample
3242
3243@noindent
3244Though rather hard to read, this is a formula which shows the product
3245of two matrices. The @samp{*} function, having invalid arguments, has
3246been left in symbolic form.
3247
3248We can multiply the matrices if we @dfn{transpose} one of them first.
3249
3250@smallexample
3251@group
32522: [ [ 1, 2, 3 ] 1: [ [ 14, 32 ] 1: [ [ 17, 22, 27 ]
3253 [ 4, 5, 6 ] ] [ 32, 77 ] ] [ 22, 29, 36 ]
32541: [ [ 1, 4 ] . [ 27, 36, 45 ] ]
3255 [ 2, 5 ] .
3256 [ 3, 6 ] ]
3257 .
3258
3259 U v t * U @key{TAB} *
3260@end group
3261@end smallexample
3262
3263Matrix multiplication is not commutative; indeed, switching the
3264order of the operands can even change the dimensions of the result
3265matrix, as happened here!
3266
3267If you multiply a plain vector by a matrix, it is treated as a
3268single row or column depending on which side of the matrix it is
3269on. The result is a plain vector which should also be interpreted
3270as a row or column as appropriate.
3271
3272@smallexample
3273@group
32742: [ [ 1, 2, 3 ] 1: [14, 32]
3275 [ 4, 5, 6 ] ] .
32761: [1, 2, 3]
3277 .
3278
3279 r 4 r 1 *
3280@end group
3281@end smallexample
3282
3283Multiplying in the other order wouldn't work because the number of
3284rows in the matrix is different from the number of elements in the
3285vector.
3286
3287(@bullet{}) @strong{Exercise 1.} Use @samp{*} to sum along the rows
40ba43b4 3288of the above
4009494e 3289@texline @math{2\times3}
40ba43b4 3290@infoline 2x3
4009494e 3291matrix to get @expr{[6, 15]}. Now use @samp{*} to sum along the columns
40ba43b4 3292to get @expr{[5, 7, 9]}.
4009494e
GM
3293@xref{Matrix Answer 1, 1}. (@bullet{})
3294
3295@cindex Identity matrix
3296An @dfn{identity matrix} is a square matrix with ones along the
3297diagonal and zeros elsewhere. It has the property that multiplication
3298by an identity matrix, on the left or on the right, always produces
3299the original matrix.
3300
3301@smallexample
3302@group
33031: [ [ 1, 2, 3 ] 2: [ [ 1, 2, 3 ] 1: [ [ 1, 2, 3 ]
3304 [ 4, 5, 6 ] ] [ 4, 5, 6 ] ] [ 4, 5, 6 ] ]
3305 . 1: [ [ 1, 0, 0 ] .
3306 [ 0, 1, 0 ]
3307 [ 0, 0, 1 ] ]
3308 .
3309
3310 r 4 v i 3 @key{RET} *
3311@end group
3312@end smallexample
3313
3314If a matrix is square, it is often possible to find its @dfn{inverse},
3315that is, a matrix which, when multiplied by the original matrix, yields
3316an identity matrix. The @kbd{&} (reciprocal) key also computes the
3317inverse of a matrix.
3318
3319@smallexample
3320@group
33211: [ [ 1, 2, 3 ] 1: [ [ -2.4, 1.2, -0.2 ]
3322 [ 4, 5, 6 ] [ 2.8, -1.4, 0.4 ]
3323 [ 7, 6, 0 ] ] [ -0.73333, 0.53333, -0.2 ] ]
3324 . .
3325
3326 r 4 r 2 | s 5 &
3327@end group
3328@end smallexample
3329
3330@noindent
3331The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
3332matrices together. Here we have used it to add a new row onto
3333our matrix to make it square.
3334
3335We can multiply these two matrices in either order to get an identity.
3336
3337@smallexample
3338@group
33391: [ [ 1., 0., 0. ] 1: [ [ 1., 0., 0. ]
3340 [ 0., 1., 0. ] [ 0., 1., 0. ]
3341 [ 0., 0., 1. ] ] [ 0., 0., 1. ] ]
3342 . .
3343
3344 M-@key{RET} * U @key{TAB} *
3345@end group
3346@end smallexample
3347
3348@cindex Systems of linear equations
3349@cindex Linear equations, systems of
3350Matrix inverses are related to systems of linear equations in algebra.
3351Suppose we had the following set of equations:
3352
3353@ifnottex
3354@group
3355@example
3356 a + 2b + 3c = 6
3357 4a + 5b + 6c = 2
3358 7a + 6b = 3
3359@end example
3360@end group
3361@end ifnottex
3362@tex
4009494e
GM
3363\beforedisplayh
3364$$ \openup1\jot \tabskip=0pt plus1fil
3365\halign to\displaywidth{\tabskip=0pt
3366 $\hfil#$&$\hfil{}#{}$&
3367 $\hfil#$&$\hfil{}#{}$&
3368 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3369 a&+&2b&+&3c&=6 \cr
3370 4a&+&5b&+&6c&=2 \cr
3371 7a&+&6b& & &=3 \cr}
3372$$
3373\afterdisplayh
3374@end tex
3375
3376@noindent
3377This can be cast into the matrix equation,
3378
3379@ifnottex
3380@group
3381@example
3382 [ [ 1, 2, 3 ] [ [ a ] [ [ 6 ]
3383 [ 4, 5, 6 ] * [ b ] = [ 2 ]
3384 [ 7, 6, 0 ] ] [ c ] ] [ 3 ] ]
3385@end example
3386@end group
3387@end ifnottex
3388@tex
4009494e
GM
3389\beforedisplay
3390$$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 }
3391 \times
3392 \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 }
3393$$
3394\afterdisplay
3395@end tex
3396
3397We can solve this system of equations by multiplying both sides by the
3398inverse of the matrix. Calc can do this all in one step:
3399
3400@smallexample
3401@group
34022: [6, 2, 3] 1: [-12.6, 15.2, -3.93333]
34031: [ [ 1, 2, 3 ] .
3404 [ 4, 5, 6 ]
3405 [ 7, 6, 0 ] ]
3406 .
3407
3408 [6,2,3] r 5 /
3409@end group
3410@end smallexample
3411
3412@noindent
3413The result is the @expr{[a, b, c]} vector that solves the equations.
3414(Dividing by a square matrix is equivalent to multiplying by its
3415inverse.)
3416
3417Let's verify this solution:
3418
3419@smallexample
3420@group
34212: [ [ 1, 2, 3 ] 1: [6., 2., 3.]
3422 [ 4, 5, 6 ] .
3423 [ 7, 6, 0 ] ]
34241: [-12.6, 15.2, -3.93333]
3425 .
3426
3427 r 5 @key{TAB} *
3428@end group
3429@end smallexample
3430
3431@noindent
3432Note that we had to be careful about the order in which we multiplied
3433the matrix and vector. If we multiplied in the other order, Calc would
3434assume the vector was a row vector in order to make the dimensions
3435come out right, and the answer would be incorrect. If you
3436don't feel safe letting Calc take either interpretation of your
40ba43b4 3437vectors, use explicit
4009494e
GM
3438@texline @math{N\times1}
3439@infoline Nx1
3440or
3441@texline @math{1\times N}
3442@infoline 1xN
3443matrices instead. In this case, you would enter the original column
3444vector as @samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}.
3445
3446(@bullet{}) @strong{Exercise 2.} Algebraic entry allows you to make
3447vectors and matrices that include variables. Solve the following
3448system of equations to get expressions for @expr{x} and @expr{y}
3449in terms of @expr{a} and @expr{b}.
3450
3451@ifnottex
3452@group
3453@example
3454 x + a y = 6
3455 x + b y = 10
3456@end example
3457@end group
3458@end ifnottex
3459@tex
4009494e
GM
3460\beforedisplay
3461$$ \eqalign{ x &+ a y = 6 \cr
3462 x &+ b y = 10}
3463$$
3464\afterdisplay
3465@end tex
3466
3467@noindent
3468@xref{Matrix Answer 2, 2}. (@bullet{})
3469
3470@cindex Least-squares for over-determined systems
3471@cindex Over-determined systems of equations
3472(@bullet{}) @strong{Exercise 3.} A system of equations is ``over-determined''
3473if it has more equations than variables. It is often the case that
3474there are no values for the variables that will satisfy all the
3475equations at once, but it is still useful to find a set of values
3476which ``nearly'' satisfy all the equations. In terms of matrix equations,
3477you can't solve @expr{A X = B} directly because the matrix @expr{A}
3478is not square for an over-determined system. Matrix inversion works
3479only for square matrices. One common trick is to multiply both sides
3480on the left by the transpose of @expr{A}:
3481@ifnottex
3482@samp{trn(A)*A*X = trn(A)*B}.
3483@end ifnottex
3484@tex
4009494e
GM
3485$A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}.
3486@end tex
40ba43b4 3487Now
4009494e 3488@texline @math{A^T A}
40ba43b4 3489@infoline @expr{trn(A)*A}
4009494e
GM
3490is a square matrix so a solution is possible. It turns out that the
3491@expr{X} vector you compute in this way will be a ``least-squares''
3492solution, which can be regarded as the ``closest'' solution to the set
3493of equations. Use Calc to solve the following over-determined
3494system:
3495
3496@ifnottex
3497@group
3498@example
3499 a + 2b + 3c = 6
3500 4a + 5b + 6c = 2
3501 7a + 6b = 3
3502 2a + 4b + 6c = 11
3503@end example
3504@end group
3505@end ifnottex
3506@tex
4009494e
GM
3507\beforedisplayh
3508$$ \openup1\jot \tabskip=0pt plus1fil
3509\halign to\displaywidth{\tabskip=0pt
3510 $\hfil#$&$\hfil{}#{}$&
3511 $\hfil#$&$\hfil{}#{}$&
3512 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3513 a&+&2b&+&3c&=6 \cr
3514 4a&+&5b&+&6c&=2 \cr
3515 7a&+&6b& & &=3 \cr
3516 2a&+&4b&+&6c&=11 \cr}
3517$$
3518\afterdisplayh
3519@end tex
3520
3521@noindent
3522@xref{Matrix Answer 3, 3}. (@bullet{})
3523
3524@node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
3525@subsection Vectors as Lists
3526
3527@noindent
3528@cindex Lists
3529Although Calc has a number of features for manipulating vectors and
3530matrices as mathematical objects, you can also treat vectors as
3531simple lists of values. For example, we saw that the @kbd{k f}
3532command returns a vector which is a list of the prime factors of a
3533number.
3534
3535You can pack and unpack stack entries into vectors:
3536
3537@smallexample
3538@group
35393: 10 1: [10, 20, 30] 3: 10
35402: 20 . 2: 20
35411: 30 1: 30
3542 . .
3543
3544 M-3 v p v u
3545@end group
3546@end smallexample
3547
3548You can also build vectors out of consecutive integers, or out
3549of many copies of a given value:
3550
3551@smallexample
3552@group
35531: [1, 2, 3, 4] 2: [1, 2, 3, 4] 2: [1, 2, 3, 4]
3554 . 1: 17 1: [17, 17, 17, 17]
3555 . .
3556
3557 v x 4 @key{RET} 17 v b 4 @key{RET}
3558@end group
3559@end smallexample
3560
3561You can apply an operator to every element of a vector using the
3562@dfn{map} command.
3563
3564@smallexample
3565@group
35661: [17, 34, 51, 68] 1: [289, 1156, 2601, 4624] 1: [17, 34, 51, 68]
3567 . . .
3568
3569 V M * 2 V M ^ V M Q
3570@end group
3571@end smallexample
3572
3573@noindent
3574In the first step, we multiply the vector of integers by the vector
3575of 17's elementwise. In the second step, we raise each element to
3576the power two. (The general rule is that both operands must be
3577vectors of the same length, or else one must be a vector and the
3578other a plain number.) In the final step, we take the square root
3579of each element.
3580
3581(@bullet{}) @strong{Exercise 1.} Compute a vector of powers of two
40ba43b4 3582from
4009494e 3583@texline @math{2^{-4}}
40ba43b4 3584@infoline @expr{2^-4}
4009494e
GM
3585to @expr{2^4}. @xref{List Answer 1, 1}. (@bullet{})
3586
3587You can also @dfn{reduce} a binary operator across a vector.
3588For example, reducing @samp{*} computes the product of all the
3589elements in the vector:
3590
3591@smallexample
3592@group
35931: 123123 1: [3, 7, 11, 13, 41] 1: 123123
3594 . . .
3595
3596 123123 k f V R *
3597@end group
3598@end smallexample
3599
3600@noindent
3601In this example, we decompose 123123 into its prime factors, then
3602multiply those factors together again to yield the original number.
3603
3604We could compute a dot product ``by hand'' using mapping and
3605reduction:
3606
3607@smallexample
3608@group
36092: [1, 2, 3] 1: [7, 12, 0] 1: 19
36101: [7, 6, 0] . .
3611 .
3612
3613 r 1 r 2 V M * V R +
3614@end group
3615@end smallexample
3616
3617@noindent
3618Recalling two vectors from the previous section, we compute the
3619sum of pairwise products of the elements to get the same answer
3620for the dot product as before.
3621
3622A slight variant of vector reduction is the @dfn{accumulate} operation,
3623@kbd{V U}. This produces a vector of the intermediate results from
3624a corresponding reduction. Here we compute a table of factorials:
3625
3626@smallexample
3627@group
36281: [1, 2, 3, 4, 5, 6] 1: [1, 2, 6, 24, 120, 720]
3629 . .
3630
3631 v x 6 @key{RET} V U *
3632@end group
3633@end smallexample
3634
3635Calc allows vectors to grow as large as you like, although it gets
3636rather slow if vectors have more than about a hundred elements.
3637Actually, most of the time is spent formatting these large vectors
3638for display, not calculating on them. Try the following experiment
3639(if your computer is very fast you may need to substitute a larger
3640vector size).
3641
3642@smallexample
3643@group
36441: [1, 2, 3, 4, ... 1: [2, 3, 4, 5, ...
3645 . .
3646
3647 v x 500 @key{RET} 1 V M +
3648@end group
3649@end smallexample
3650
3651Now press @kbd{v .} (the letter @kbd{v}, then a period) and try the
3652experiment again. In @kbd{v .} mode, long vectors are displayed
3653``abbreviated'' like this:
3654
3655@smallexample
3656@group
36571: [1, 2, 3, ..., 500] 1: [2, 3, 4, ..., 501]
3658 . .
3659
3660 v x 500 @key{RET} 1 V M +
3661@end group
3662@end smallexample
3663
3664@noindent
3665(where now the @samp{...} is actually part of the Calc display).
3666You will find both operations are now much faster. But notice that
3667even in @w{@kbd{v .}} mode, the full vectors are still shown in the Trail.
3668Type @w{@kbd{t .}} to cause the trail to abbreviate as well, and try the
3669experiment one more time. Operations on long vectors are now quite
3670fast! (But of course if you use @kbd{t .} you will lose the ability
3671to get old vectors back using the @kbd{t y} command.)
3672
3673An easy way to view a full vector when @kbd{v .} mode is active is
3674to press @kbd{`} (back-quote) to edit the vector; editing always works
3675with the full, unabbreviated value.
3676
3677@cindex Least-squares for fitting a straight line
3678@cindex Fitting data to a line
3679@cindex Line, fitting data to
3680@cindex Data, extracting from buffers
3681@cindex Columns of data, extracting
3682As a larger example, let's try to fit a straight line to some data,
3683using the method of least squares. (Calc has a built-in command for
3684least-squares curve fitting, but we'll do it by hand here just to
3685practice working with vectors.) Suppose we have the following list
3686of values in a file we have loaded into Emacs:
3687
3688@smallexample
3689 x y
3690 --- ---
3691 1.34 0.234
3692 1.41 0.298
3693 1.49 0.402
3694 1.56 0.412
3695 1.64 0.466
3696 1.73 0.473
3697 1.82 0.601
3698 1.91 0.519
3699 2.01 0.603
3700 2.11 0.637
3701 2.22 0.645
3702 2.33 0.705
3703 2.45 0.917
3704 2.58 1.009
3705 2.71 0.971
3706 2.85 1.062
3707 3.00 1.148
3708 3.15 1.157
3709 3.32 1.354
3710@end smallexample
3711
3712@noindent
3713If you are reading this tutorial in printed form, you will find it
3714easiest to press @kbd{C-x * i} to enter the on-line Info version of
3715the manual and find this table there. (Press @kbd{g}, then type
3716@kbd{List Tutorial}, to jump straight to this section.)
3717
3718Position the cursor at the upper-left corner of this table, just
3719to the left of the @expr{1.34}. Press @kbd{C-@@} to set the mark.
3720(On your system this may be @kbd{C-2}, @kbd{C-@key{SPC}}, or @kbd{NUL}.)
3721Now position the cursor to the lower-right, just after the @expr{1.354}.
3722You have now defined this region as an Emacs ``rectangle.'' Still
3723in the Info buffer, type @kbd{C-x * r}. This command
3724(@code{calc-grab-rectangle}) will pop you back into the Calculator, with
3725the contents of the rectangle you specified in the form of a matrix.
3726
3727@smallexample
3728@group
37291: [ [ 1.34, 0.234 ]
3730 [ 1.41, 0.298 ]
3731 @dots{}
3732@end group
3733@end smallexample
3734
3735@noindent
3736(You may wish to use @kbd{v .} mode to abbreviate the display of this
3737large matrix.)
3738
3739We want to treat this as a pair of lists. The first step is to
3740transpose this matrix into a pair of rows. Remember, a matrix is
3741just a vector of vectors. So we can unpack the matrix into a pair
3742of row vectors on the stack.
3743
3744@smallexample
3745@group
37461: [ [ 1.34, 1.41, 1.49, ... ] 2: [1.34, 1.41, 1.49, ... ]
3747 [ 0.234, 0.298, 0.402, ... ] ] 1: [0.234, 0.298, 0.402, ... ]
3748 . .
3749
3750 v t v u
3751@end group
3752@end smallexample
3753
3754@noindent
3755Let's store these in quick variables 1 and 2, respectively.
3756
3757@smallexample
3758@group
37591: [1.34, 1.41, 1.49, ... ] .
3760 .
3761
3762 t 2 t 1
3763@end group
3764@end smallexample
3765
3766@noindent
3767(Recall that @kbd{t 2} is a variant of @kbd{s 2} that removes the
3768stored value from the stack.)
3769
3770In a least squares fit, the slope @expr{m} is given by the formula
3771
3772@ifnottex
3773@example
3774m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
3775@end example
3776@end ifnottex
3777@tex
4009494e
GM
3778\beforedisplay
3779$$ m = {N \sum x y - \sum x \sum y \over
3780 N \sum x^2 - \left( \sum x \right)^2} $$
3781\afterdisplay
3782@end tex
3783
3784@noindent
40ba43b4 3785where
4009494e 3786@texline @math{\sum x}
40ba43b4 3787@infoline @expr{sum(x)}
4009494e
GM
3788represents the sum of all the values of @expr{x}. While there is an
3789actual @code{sum} function in Calc, it's easier to sum a vector using a
3790simple reduction. First, let's compute the four different sums that
3791this formula uses.
3792
3793@smallexample
3794@group
37951: 41.63 1: 98.0003
3796 . .
3797
3798 r 1 V R + t 3 r 1 2 V M ^ V R + t 4
3799
3800@end group
3801@end smallexample
3802@noindent
3803@smallexample
3804@group
38051: 13.613 1: 33.36554
3806 . .
3807
3808 r 2 V R + t 5 r 1 r 2 V M * V R + t 6
3809@end group
3810@end smallexample
3811
3812@ifnottex
3813@noindent
3814These are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
3815respectively. (We could have used @kbd{*} to compute @samp{sum(x^2)} and
3816@samp{sum(x y)}.)
3817@end ifnottex
3818@tex
4009494e
GM
3819These are $\sum x$, $\sum x^2$, $\sum y$, and $\sum x y$,
3820respectively. (We could have used \kbd{*} to compute $\sum x^2$ and
3821$\sum x y$.)
3822@end tex
3823
3824Finally, we also need @expr{N}, the number of data points. This is just
3825the length of either of our lists.
3826
3827@smallexample
3828@group
38291: 19
3830 .
3831
3832 r 1 v l t 7
3833@end group
3834@end smallexample
3835
3836@noindent
3837(That's @kbd{v} followed by a lower-case @kbd{l}.)
3838
3839Now we grind through the formula:
3840
3841@smallexample
3842@group
38431: 633.94526 2: 633.94526 1: 67.23607
3844 . 1: 566.70919 .
3845 .
3846
3847 r 7 r 6 * r 3 r 5 * -
3848
3849@end group
3850@end smallexample
3851@noindent
3852@smallexample
3853@group
38542: 67.23607 3: 67.23607 2: 67.23607 1: 0.52141679
38551: 1862.0057 2: 1862.0057 1: 128.9488 .
3856 . 1: 1733.0569 .
3857 .
3858
3859 r 7 r 4 * r 3 2 ^ - / t 8
3860@end group
3861@end smallexample
3862
3863That gives us the slope @expr{m}. The y-intercept @expr{b} can now
3864be found with the simple formula,
3865
3866@ifnottex
3867@example
3868b = (sum(y) - m sum(x)) / N
3869@end example
3870@end ifnottex
3871@tex
4009494e
GM
3872\beforedisplay
3873$$ b = {\sum y - m \sum x \over N} $$
3874\afterdisplay
3875\vskip10pt
3876@end tex
3877
3878@smallexample
3879@group
38801: 13.613 2: 13.613 1: -8.09358 1: -0.425978
3881 . 1: 21.70658 . .
3882 .
3883
3884 r 5 r 8 r 3 * - r 7 / t 9
3885@end group
3886@end smallexample
3887
40ba43b4 3888Let's ``plot'' this straight line approximation,
4009494e 3889@texline @math{y \approx m x + b},
40ba43b4 3890@infoline @expr{m x + b},
4009494e
GM
3891and compare it with the original data.
3892
3893@smallexample
3894@group
38951: [0.699, 0.735, ... ] 1: [0.273, 0.309, ... ]
3896 . .
3897
3898 r 1 r 8 * r 9 + s 0
3899@end group
3900@end smallexample
3901
3902@noindent
3903Notice that multiplying a vector by a constant, and adding a constant
3904to a vector, can be done without mapping commands since these are
3905common operations from vector algebra. As far as Calc is concerned,
3906we've just been doing geometry in 19-dimensional space!
3907
3908We can subtract this vector from our original @expr{y} vector to get
3909a feel for the error of our fit. Let's find the maximum error:
3910
3911@smallexample
3912@group
39131: [0.0387, 0.0112, ... ] 1: [0.0387, 0.0112, ... ] 1: 0.0897
3914 . . .
3915
3916 r 2 - V M A V R X
3917@end group
3918@end smallexample
3919
3920@noindent
3921First we compute a vector of differences, then we take the absolute
3922values of these differences, then we reduce the @code{max} function
3923across the vector. (The @code{max} function is on the two-key sequence
3924@kbd{f x}; because it is so common to use @code{max} in a vector
3925operation, the letters @kbd{X} and @kbd{N} are also accepted for
3926@code{max} and @code{min} in this context. In general, you answer
3927the @kbd{V M} or @kbd{V R} prompt with the actual key sequence that
3928invokes the function you want. You could have typed @kbd{V R f x} or
3929even @kbd{V R x max @key{RET}} if you had preferred.)
3930
3931If your system has the GNUPLOT program, you can see graphs of your
3932data and your straight line to see how well they match. (If you have
3933GNUPLOT 3.0 or higher, the following instructions will work regardless
3934of the kind of display you have. Some GNUPLOT 2.0, non-X-windows systems
3935may require additional steps to view the graphs.)
3936
3937Let's start by plotting the original data. Recall the ``@var{x}'' and ``@var{y}''
3938vectors onto the stack and press @kbd{g f}. This ``fast'' graphing
3939command does everything you need to do for simple, straightforward
3940plotting of data.
3941
3942@smallexample
3943@group
39442: [1.34, 1.41, 1.49, ... ]
39451: [0.234, 0.298, 0.402, ... ]
3946 .
3947
3948 r 1 r 2 g f
3949@end group
3950@end smallexample
3951
3952If all goes well, you will shortly get a new window containing a graph
3953of the data. (If not, contact your GNUPLOT or Calc installer to find
3954out what went wrong.) In the X window system, this will be a separate
3955graphics window. For other kinds of displays, the default is to
3956display the graph in Emacs itself using rough character graphics.
3957Press @kbd{q} when you are done viewing the character graphics.
3958
3959Next, let's add the line we got from our least-squares fit.
3960@ifinfo
3961(If you are reading this tutorial on-line while running Calc, typing
3962@kbd{g a} may cause the tutorial to disappear from its window and be
3963replaced by a buffer named @samp{*Gnuplot Commands*}. The tutorial
40ba43b4 3964will reappear when you terminate GNUPLOT by typing @kbd{g q}.)
4009494e
GM
3965@end ifinfo
3966
3967@smallexample
3968@group
39692: [1.34, 1.41, 1.49, ... ]
39701: [0.273, 0.309, 0.351, ... ]
3971 .
3972
3973 @key{DEL} r 0 g a g p
3974@end group
3975@end smallexample
3976
3977It's not very useful to get symbols to mark the data points on this
3978second curve; you can type @kbd{g S g p} to remove them. Type @kbd{g q}
3979when you are done to remove the X graphics window and terminate GNUPLOT.
3980
3981(@bullet{}) @strong{Exercise 2.} An earlier exercise showed how to do
3982least squares fitting to a general system of equations. Our 19 data
3983points are really 19 equations of the form @expr{y_i = m x_i + b} for
3984different pairs of @expr{(x_i,y_i)}. Use the matrix-transpose method
3985to solve for @expr{m} and @expr{b}, duplicating the above result.
3986@xref{List Answer 2, 2}. (@bullet{})
3987
3988@cindex Geometric mean
3989(@bullet{}) @strong{Exercise 3.} If the input data do not form a
3990rectangle, you can use @w{@kbd{C-x * g}} (@code{calc-grab-region})
3991to grab the data the way Emacs normally works with regions---it reads
3992left-to-right, top-to-bottom, treating line breaks the same as spaces.
3993Use this command to find the geometric mean of the following numbers.
3994(The geometric mean is the @var{n}th root of the product of @var{n} numbers.)
3995
3996@example
39972.3 6 22 15.1 7
3998 15 14 7.5
3999 2.5
4000@end example
4001
4002@noindent
4003The @kbd{C-x * g} command accepts numbers separated by spaces or commas,
4004with or without surrounding vector brackets.
4005@xref{List Answer 3, 3}. (@bullet{})
4006
4007@ifnottex
4008As another example, a theorem about binomial coefficients tells
4009us that the alternating sum of binomial coefficients
4010@var{n}-choose-0 minus @var{n}-choose-1 plus @var{n}-choose-2, and so
4011on up to @var{n}-choose-@var{n},
4012always comes out to zero. Let's verify this
4013for @expr{n=6}.
4014@end ifnottex
4015@tex
4016As another example, a theorem about binomial coefficients tells
4017us that the alternating sum of binomial coefficients
4018${n \choose 0} - {n \choose 1} + {n \choose 2} - \cdots \pm {n \choose n}$
4019always comes out to zero. Let's verify this
4020for \cite{n=6}.
4021@end tex
4022
4023@smallexample
4024@group
40251: [1, 2, 3, 4, 5, 6, 7] 1: [0, 1, 2, 3, 4, 5, 6]
4026 . .
4027
4028 v x 7 @key{RET} 1 -
4029
4030@end group
4031@end smallexample
4032@noindent
4033@smallexample
4034@group
40351: [1, -6, 15, -20, 15, -6, 1] 1: 0
4036 . .
4037
4038 V M ' (-1)^$ choose(6,$) @key{RET} V R +
4039@end group
4040@end smallexample
4041
4042The @kbd{V M '} command prompts you to enter any algebraic expression
4043to define the function to map over the vector. The symbol @samp{$}
4044inside this expression represents the argument to the function.
4045The Calculator applies this formula to each element of the vector,
4046substituting each element's value for the @samp{$} sign(s) in turn.
4047
4048To define a two-argument function, use @samp{$$} for the first
4049argument and @samp{$} for the second: @kbd{V M ' $$-$ @key{RET}} is
4050equivalent to @kbd{V M -}. This is analogous to regular algebraic
4051entry, where @samp{$$} would refer to the next-to-top stack entry
4052and @samp{$} would refer to the top stack entry, and @kbd{' $$-$ @key{RET}}
4053would act exactly like @kbd{-}.
4054
4055Notice that the @kbd{V M '} command has recorded two things in the
4056trail: The result, as usual, and also a funny-looking thing marked
4057@samp{oper} that represents the operator function you typed in.
4058The function is enclosed in @samp{< >} brackets, and the argument is
4059denoted by a @samp{#} sign. If there were several arguments, they
4060would be shown as @samp{#1}, @samp{#2}, and so on. (For example,
4061@kbd{V M ' $$-$} will put the function @samp{<#1 - #2>} on the
4062trail.) This object is a ``nameless function''; you can use nameless
4063@w{@samp{< >}} notation to answer the @kbd{V M '} prompt if you like.
4064Nameless function notation has the interesting, occasionally useful
4065property that a nameless function is not actually evaluated until
4066it is used. For example, @kbd{V M ' $+random(2.0)} evaluates
4067@samp{random(2.0)} once and adds that random number to all elements
4068of the vector, but @kbd{V M ' <#+random(2.0)>} evaluates the
4069@samp{random(2.0)} separately for each vector element.
4070
4071Another group of operators that are often useful with @kbd{V M} are
4072the relational operators: @kbd{a =}, for example, compares two numbers
4073and gives the result 1 if they are equal, or 0 if not. Similarly,
4074@w{@kbd{a <}} checks for one number being less than another.
4075
4076Other useful vector operations include @kbd{v v}, to reverse a
4077vector end-for-end; @kbd{V S}, to sort the elements of a vector
4078into increasing order; and @kbd{v r} and @w{@kbd{v c}}, to extract
4079one row or column of a matrix, or (in both cases) to extract one
4080element of a plain vector. With a negative argument, @kbd{v r}
4081and @kbd{v c} instead delete one row, column, or vector element.
4082
4083@cindex Divisor functions
4084(@bullet{}) @strong{Exercise 4.} The @expr{k}th @dfn{divisor function}
4085@tex
4086$\sigma_k(n)$
4087@end tex
4088is the sum of the @expr{k}th powers of all the divisors of an
4089integer @expr{n}. Figure out a method for computing the divisor
4090function for reasonably small values of @expr{n}. As a test,
4091the 0th and 1st divisor functions of 30 are 8 and 72, respectively.
4092@xref{List Answer 4, 4}. (@bullet{})
4093
4094@cindex Square-free numbers
4095@cindex Duplicate values in a list
4096(@bullet{}) @strong{Exercise 5.} The @kbd{k f} command produces a
4097list of prime factors for a number. Sometimes it is important to
4098know that a number is @dfn{square-free}, i.e., that no prime occurs
4099more than once in its list of prime factors. Find a sequence of
4100keystrokes to tell if a number is square-free; your method should
4101leave 1 on the stack if it is, or 0 if it isn't.
4102@xref{List Answer 5, 5}. (@bullet{})
4103
4104@cindex Triangular lists
4105(@bullet{}) @strong{Exercise 6.} Build a list of lists that looks
4106like the following diagram. (You may wish to use the @kbd{v /}
4107command to enable multi-line display of vectors.)
4108
4109@smallexample
4110@group
41111: [ [1],
4112 [1, 2],
4113 [1, 2, 3],
4114 [1, 2, 3, 4],
4115 [1, 2, 3, 4, 5],
4116 [1, 2, 3, 4, 5, 6] ]
4117@end group
4118@end smallexample
4119
4120@noindent
4121@xref{List Answer 6, 6}. (@bullet{})
4122
4123(@bullet{}) @strong{Exercise 7.} Build the following list of lists.
4124
4125@smallexample
4126@group
41271: [ [0],
4128 [1, 2],
4129 [3, 4, 5],
4130 [6, 7, 8, 9],
4131 [10, 11, 12, 13, 14],
4132 [15, 16, 17, 18, 19, 20] ]
4133@end group
4134@end smallexample
4135
4136@noindent
4137@xref{List Answer 7, 7}. (@bullet{})
4138
4139@cindex Maximizing a function over a list of values
4140@c [fix-ref Numerical Solutions]
4141(@bullet{}) @strong{Exercise 8.} Compute a list of values of Bessel's
4142@texline @math{J_1(x)}
40ba43b4 4143@infoline @expr{J1}
4009494e
GM
4144function @samp{besJ(1,x)} for @expr{x} from 0 to 5 in steps of 0.25.
4145Find the value of @expr{x} (from among the above set of values) for
4146which @samp{besJ(1,x)} is a maximum. Use an ``automatic'' method,
4147i.e., just reading along the list by hand to find the largest value
4148is not allowed! (There is an @kbd{a X} command which does this kind
4149of thing automatically; @pxref{Numerical Solutions}.)
4150@xref{List Answer 8, 8}. (@bullet{})
4151
4152@cindex Digits, vectors of
4153(@bullet{}) @strong{Exercise 9.} You are given an integer in the range
4154@texline @math{0 \le N < 10^m}
40ba43b4 4155@infoline @expr{0 <= N < 10^m}
4009494e
GM
4156for @expr{m=12} (i.e., an integer of less than
4157twelve digits). Convert this integer into a vector of @expr{m}
4158digits, each in the range from 0 to 9. In vector-of-digits notation,
4159add one to this integer to produce a vector of @expr{m+1} digits
4160(since there could be a carry out of the most significant digit).
4161Convert this vector back into a regular integer. A good integer
4162to try is 25129925999. @xref{List Answer 9, 9}. (@bullet{})
4163
4164(@bullet{}) @strong{Exercise 10.} Your friend Joe tried to use
4165@kbd{V R a =} to test if all numbers in a list were equal. What
4166happened? How would you do this test? @xref{List Answer 10, 10}. (@bullet{})
4167
4168(@bullet{}) @strong{Exercise 11.} The area of a circle of radius one
40ba43b4 4169is @cpi{}. The area of the
4009494e
GM
4170@texline @math{2\times2}
4171@infoline 2x2
4172square that encloses that circle is 4. So if we throw @var{n} darts at
4173random points in the square, about @cpiover{4} of them will land inside
40ba43b4 4174the circle. This gives us an entertaining way to estimate the value of
4009494e
GM
4175@cpi{}. The @w{@kbd{k r}}
4176command picks a random number between zero and the value on the stack.
4177We could get a random floating-point number between @mathit{-1} and 1 by typing
4178@w{@kbd{2.0 k r 1 -}}. Build a vector of 100 random @expr{(x,y)} points in
4179this square, then use vector mapping and reduction to count how many
4180points lie inside the unit circle. Hint: Use the @kbd{v b} command.
4181@xref{List Answer 11, 11}. (@bullet{})
4182
4183@cindex Matchstick problem
4184(@bullet{}) @strong{Exercise 12.} The @dfn{matchstick problem} provides
4185another way to calculate @cpi{}. Say you have an infinite field
4186of vertical lines with a spacing of one inch. Toss a one-inch matchstick
4187onto the field. The probability that the matchstick will land crossing
40ba43b4 4188a line turns out to be
4009494e 4189@texline @math{2/\pi}.
40ba43b4 4190@infoline @expr{2/pi}.
4009494e
GM
4191Toss 100 matchsticks to estimate @cpi{}. (If you want still more fun,
4192the probability that the GCD (@w{@kbd{k g}}) of two large integers is
40ba43b4 4193one turns out to be
4009494e
GM
4194@texline @math{6/\pi^2}.
4195@infoline @expr{6/pi^2}.
4196That provides yet another way to estimate @cpi{}.)
4197@xref{List Answer 12, 12}. (@bullet{})
4198
4199(@bullet{}) @strong{Exercise 13.} An algebraic entry of a string in
4200double-quote marks, @samp{"hello"}, creates a vector of the numerical
4201(ASCII) codes of the characters (here, @expr{[104, 101, 108, 108, 111]}).
4202Sometimes it is convenient to compute a @dfn{hash code} of a string,
4203which is just an integer that represents the value of that string.
4204Two equal strings have the same hash code; two different strings
4205@dfn{probably} have different hash codes. (For example, Calc has
4206over 400 function names, but Emacs can quickly find the definition for
4207any given name because it has sorted the functions into ``buckets'' by
4208their hash codes. Sometimes a few names will hash into the same bucket,
4209but it is easier to search among a few names than among all the names.)
4210One popular hash function is computed as follows: First set @expr{h = 0}.
4211Then, for each character from the string in turn, set @expr{h = 3h + c_i}
4212where @expr{c_i} is the character's ASCII code. If we have 511 buckets,
4213we then take the hash code modulo 511 to get the bucket number. Develop a
4214simple command or commands for converting string vectors into hash codes.
4215The hash code for @samp{"Testing, 1, 2, 3"} is 1960915098, which modulo
4216511 is 121. @xref{List Answer 13, 13}. (@bullet{})
4217
4218(@bullet{}) @strong{Exercise 14.} The @kbd{H V R} and @kbd{H V U}
4219commands do nested function evaluations. @kbd{H V U} takes a starting
4220value and a number of steps @var{n} from the stack; it then applies the
4221function you give to the starting value 0, 1, 2, up to @var{n} times
4222and returns a vector of the results. Use this command to create a
4223``random walk'' of 50 steps. Start with the two-dimensional point
4224@expr{(0,0)}; then take one step a random distance between @mathit{-1} and 1
4225in both @expr{x} and @expr{y}; then take another step, and so on. Use the
4226@kbd{g f} command to display this random walk. Now modify your random
4227walk to walk a unit distance, but in a random direction, at each step.
4228(Hint: The @code{sincos} function returns a vector of the cosine and
4229sine of an angle.) @xref{List Answer 14, 14}. (@bullet{})
4230
4231@node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
4232@section Types Tutorial
4233
4234@noindent
4235Calc understands a variety of data types as well as simple numbers.
4236In this section, we'll experiment with each of these types in turn.
4237
4238The numbers we've been using so far have mainly been either @dfn{integers}
4239or @dfn{floats}. We saw that floats are usually a good approximation to
4240the mathematical concept of real numbers, but they are only approximations
4241and are susceptible to roundoff error. Calc also supports @dfn{fractions},
4242which can exactly represent any rational number.
4243
4244@smallexample
4245@group
42461: 3628800 2: 3628800 1: 518400:7 1: 518414:7 1: 7:518414
4247 . 1: 49 . . .
4248 .
4249
4250 10 ! 49 @key{RET} : 2 + &
4251@end group
4252@end smallexample
4253
4254@noindent
4255The @kbd{:} command divides two integers to get a fraction; @kbd{/}
4256would normally divide integers to get a floating-point result.
4257Notice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
4258since the @kbd{:} would otherwise be interpreted as part of a
4259fraction beginning with 49.
4260
4261You can convert between floating-point and fractional format using
4262@kbd{c f} and @kbd{c F}:
4263
4264@smallexample
4265@group
42661: 1.35027217629e-5 1: 7:518414
4267 . .
4268
4269 c f c F
4270@end group
4271@end smallexample
4272
4273The @kbd{c F} command replaces a floating-point number with the
4274``simplest'' fraction whose floating-point representation is the
4275same, to within the current precision.
4276
4277@smallexample
4278@group
42791: 3.14159265359 1: 1146408:364913 1: 3.1416 1: 355:113
4280 . . . .
4281
4282 P c F @key{DEL} p 5 @key{RET} P c F
4283@end group
4284@end smallexample
4285
4286(@bullet{}) @strong{Exercise 1.} A calculation has produced the
4287result 1.26508260337. You suspect it is the square root of the
4288product of @cpi{} and some rational number. Is it? (Be sure
4289to allow for roundoff error!) @xref{Types Answer 1, 1}. (@bullet{})
4290
4291@dfn{Complex numbers} can be stored in both rectangular and polar form.
4292
4293@smallexample
4294@group
42951: -9 1: (0, 3) 1: (3; 90.) 1: (6; 90.) 1: (2.4495; 45.)
4296 . . . . .
4297
4298 9 n Q c p 2 * Q
4299@end group
4300@end smallexample
4301
4302@noindent
4303The square root of @mathit{-9} is by default rendered in rectangular form
4304(@w{@expr{0 + 3i}}), but we can convert it to polar form (3 with a
4305phase angle of 90 degrees). All the usual arithmetic and scientific
4306operations are defined on both types of complex numbers.
4307
4308Another generalized kind of number is @dfn{infinity}. Infinity
4309isn't really a number, but it can sometimes be treated like one.
4310Calc uses the symbol @code{inf} to represent positive infinity,
4311i.e., a value greater than any real number. Naturally, you can
4312also write @samp{-inf} for minus infinity, a value less than any
4313real number. The word @code{inf} can only be input using
4314algebraic entry.
4315
4316@smallexample
4317@group
43182: inf 2: -inf 2: -inf 2: -inf 1: nan
43191: -17 1: -inf 1: -inf 1: inf .
4320 . . . .
4321
4322' inf @key{RET} 17 n * @key{RET} 72 + A +
4323@end group
4324@end smallexample
4325
4326@noindent
4327Since infinity is infinitely large, multiplying it by any finite
4328number (like @mathit{-17}) has no effect, except that since @mathit{-17}
4329is negative, it changes a plus infinity to a minus infinity.
4330(``A huge positive number, multiplied by @mathit{-17}, yields a huge
4331negative number.'') Adding any finite number to infinity also
4332leaves it unchanged. Taking an absolute value gives us plus
4333infinity again. Finally, we add this plus infinity to the minus
4334infinity we had earlier. If you work it out, you might expect
4335the answer to be @mathit{-72} for this. But the 72 has been completely
4336lost next to the infinities; by the time we compute @w{@samp{inf - inf}}
4337the finite difference between them, if any, is undetectable.
4338So we say the result is @dfn{indeterminate}, which Calc writes
4339with the symbol @code{nan} (for Not A Number).
4340
4341Dividing by zero is normally treated as an error, but you can get
4342Calc to write an answer in terms of infinity by pressing @kbd{m i}
4343to turn on Infinite mode.
4344
4345@smallexample
4346@group
43473: nan 2: nan 2: nan 2: nan 1: nan
43482: 1 1: 1 / 0 1: uinf 1: uinf .
43491: 0 . . .
4350 .
4351
4352 1 @key{RET} 0 / m i U / 17 n * +
4353@end group
4354@end smallexample
4355
4356@noindent
4357Dividing by zero normally is left unevaluated, but after @kbd{m i}
4358it instead gives an infinite result. The answer is actually
4359@code{uinf}, ``undirected infinity.'' If you look at a graph of
4360@expr{1 / x} around @w{@expr{x = 0}}, you'll see that it goes toward
4361plus infinity as you approach zero from above, but toward minus
4362infinity as you approach from below. Since we said only @expr{1 / 0},
4363Calc knows that the answer is infinite but not in which direction.
4364That's what @code{uinf} means. Notice that multiplying @code{uinf}
4365by a negative number still leaves plain @code{uinf}; there's no
4366point in saying @samp{-uinf} because the sign of @code{uinf} is
4367unknown anyway. Finally, we add @code{uinf} to our @code{nan},
4368yielding @code{nan} again. It's easy to see that, because
4369@code{nan} means ``totally unknown'' while @code{uinf} means
4370``unknown sign but known to be infinite,'' the more mysterious
4371@code{nan} wins out when it is combined with @code{uinf}, or, for
4372that matter, with anything else.
4373
4374(@bullet{}) @strong{Exercise 2.} Predict what Calc will answer
4375for each of these formulas: @samp{inf / inf}, @samp{exp(inf)},
4376@samp{exp(-inf)}, @samp{sqrt(-inf)}, @samp{sqrt(uinf)},
4377@samp{abs(uinf)}, @samp{ln(0)}.
4378@xref{Types Answer 2, 2}. (@bullet{})
4379
4380(@bullet{}) @strong{Exercise 3.} We saw that @samp{inf - inf = nan},
4381which stands for an unknown value. Can @code{nan} stand for
4382a complex number? Can it stand for infinity?
4383@xref{Types Answer 3, 3}. (@bullet{})
4384
4385@dfn{HMS forms} represent a value in terms of hours, minutes, and
4386seconds.
4387
4388@smallexample
4389@group
43901: 2@@ 30' 0" 1: 3@@ 30' 0" 2: 3@@ 30' 0" 1: 2.
4391 . . 1: 1@@ 45' 0." .
4392 .
4393
4394 2@@ 30' @key{RET} 1 + @key{RET} 2 / /
4395@end group
4396@end smallexample
4397
4398HMS forms can also be used to hold angles in degrees, minutes, and
4399seconds.
4400
4401@smallexample
4402@group
44031: 0.5 1: 26.56505 1: 26@@ 33' 54.18" 1: 0.44721
4404 . . . .
4405
4406 0.5 I T c h S
4407@end group
4408@end smallexample
4409
4410@noindent
4411First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
4412form, then we take the sine of that angle. Note that the trigonometric
4413functions will accept HMS forms directly as input.
4414
4415@cindex Beatles
4416(@bullet{}) @strong{Exercise 4.} The Beatles' @emph{Abbey Road} is
441747 minutes and 26 seconds long, and contains 17 songs. What is the
4418average length of a song on @emph{Abbey Road}? If the Extended Disco
4419Version of @emph{Abbey Road} added 20 seconds to the length of each
4420song, how long would the album be? @xref{Types Answer 4, 4}. (@bullet{})
4421
4422A @dfn{date form} represents a date, or a date and time. Dates must
4423be entered using algebraic entry. Date forms are surrounded by
4424@samp{< >} symbols; most standard formats for dates are recognized.
4425
4426@smallexample
4427@group
44282: <Sun Jan 13, 1991> 1: 2.25
44291: <6:00pm Thu Jan 10, 1991> .
4430 .
4431
4432' <13 Jan 1991>, <1/10/91, 6pm> @key{RET} -
4433@end group
4434@end smallexample
4435
4436@noindent
4437In this example, we enter two dates, then subtract to find the
4438number of days between them. It is also possible to add an
4439HMS form or a number (of days) to a date form to get another
4440date form.
4441
4442@smallexample
4443@group
44441: <4:45:59pm Mon Jan 14, 1991> 1: <2:50:59am Thu Jan 17, 1991>
4445 . .
4446
4447 t N 2 + 10@@ 5' +
4448@end group
4449@end smallexample
4450
4451@c [fix-ref Date Arithmetic]
4452@noindent
4453The @kbd{t N} (``now'') command pushes the current date and time on the
4454stack; then we add two days, ten hours and five minutes to the date and
4455time. Other date-and-time related commands include @kbd{t J}, which
4456does Julian day conversions, @kbd{t W}, which finds the beginning of
4457the week in which a date form lies, and @kbd{t I}, which increments a
4458date by one or several months. @xref{Date Arithmetic}, for more.
4459
4460(@bullet{}) @strong{Exercise 5.} How many days until the next
4461Friday the 13th? @xref{Types Answer 5, 5}. (@bullet{})
4462
4463(@bullet{}) @strong{Exercise 6.} How many leap years will there be
4464between now and the year 10001 A.D.? @xref{Types Answer 6, 6}. (@bullet{})
4465
4466@cindex Slope and angle of a line
4467@cindex Angle and slope of a line
4468An @dfn{error form} represents a mean value with an attached standard
4469deviation, or error estimate. Suppose our measurements indicate that
4470a certain telephone pole is about 30 meters away, with an estimated
4471error of 1 meter, and 8 meters tall, with an estimated error of 0.2
4472meters. What is the slope of a line from here to the top of the
4473pole, and what is the equivalent angle in degrees?
4474
4475@smallexample
4476@group
44771: 8 +/- 0.2 2: 8 +/- 0.2 1: 0.266 +/- 0.011 1: 14.93 +/- 0.594
4478 . 1: 30 +/- 1 . .
4479 .
4480
4481 8 p .2 @key{RET} 30 p 1 / I T
4482@end group
4483@end smallexample
4484
4485@noindent
4486This means that the angle is about 15 degrees, and, assuming our
4487original error estimates were valid standard deviations, there is about
4488a 60% chance that the result is correct within 0.59 degrees.
4489
4490@cindex Torus, volume of
4491(@bullet{}) @strong{Exercise 7.} The volume of a torus (a donut shape) is
4492@texline @math{2 \pi^2 R r^2}
40ba43b4 4493@infoline @w{@expr{2 pi^2 R r^2}}
4009494e
GM
4494where @expr{R} is the radius of the circle that
4495defines the center of the tube and @expr{r} is the radius of the tube
4496itself. Suppose @expr{R} is 20 cm and @expr{r} is 4 cm, each known to
4497within 5 percent. What is the volume and the relative uncertainty of
4498the volume? @xref{Types Answer 7, 7}. (@bullet{})
4499
4500An @dfn{interval form} represents a range of values. While an
4501error form is best for making statistical estimates, intervals give
4502you exact bounds on an answer. Suppose we additionally know that
4503our telephone pole is definitely between 28 and 31 meters away,
4504and that it is between 7.7 and 8.1 meters tall.
4505
4506@smallexample
4507@group
45081: [7.7 .. 8.1] 2: [7.7 .. 8.1] 1: [0.24 .. 0.28] 1: [13.9 .. 16.1]
4509 . 1: [28 .. 31] . .
4510 .
4511
4512 [ 7.7 .. 8.1 ] [ 28 .. 31 ] / I T
4513@end group
4514@end smallexample
4515
4516@noindent
4517If our bounds were correct, then the angle to the top of the pole
4518is sure to lie in the range shown.
4519
4520The square brackets around these intervals indicate that the endpoints
4521themselves are allowable values. In other words, the distance to the
4522telephone pole is between 28 and 31, @emph{inclusive}. You can also
4523make an interval that is exclusive of its endpoints by writing
4524parentheses instead of square brackets. You can even make an interval
4525which is inclusive (``closed'') on one end and exclusive (``open'') on
4526the other.
4527
4528@smallexample
4529@group
45301: [1 .. 10) 1: (0.1 .. 1] 2: (0.1 .. 1] 1: (0.2 .. 3)
4531 . . 1: [2 .. 3) .
4532 .
4533
4534 [ 1 .. 10 ) & [ 2 .. 3 ) *
4535@end group
4536@end smallexample
4537
4538@noindent
4539The Calculator automatically keeps track of which end values should
4540be open and which should be closed. You can also make infinite or
4541semi-infinite intervals by using @samp{-inf} or @samp{inf} for one
4542or both endpoints.
4543
4544(@bullet{}) @strong{Exercise 8.} What answer would you expect from
4545@samp{@w{1 /} @w{(0 .. 10)}}? What about @samp{@w{1 /} @w{(-10 .. 0)}}? What
4546about @samp{@w{1 /} @w{[0 .. 10]}} (where the interval actually includes
4547zero)? What about @samp{@w{1 /} @w{(-10 .. 10)}}?
4548@xref{Types Answer 8, 8}. (@bullet{})
4549
4550(@bullet{}) @strong{Exercise 9.} Two easy ways of squaring a number
4551are @kbd{@key{RET} *} and @w{@kbd{2 ^}}. Normally these produce the same
4552answer. Would you expect this still to hold true for interval forms?
4553If not, which of these will result in a larger interval?
4554@xref{Types Answer 9, 9}. (@bullet{})
4555
4556A @dfn{modulo form} is used for performing arithmetic modulo @var{m}.
4557For example, arithmetic involving time is generally done modulo 12
4558or 24 hours.
4559
4560@smallexample
4561@group
45621: 17 mod 24 1: 3 mod 24 1: 21 mod 24 1: 9 mod 24
4563 . . . .
4564
4565 17 M 24 @key{RET} 10 + n 5 /
4566@end group
4567@end smallexample
4568
4569@noindent
4570In this last step, Calc has divided by 5 modulo 24; i.e., it has found a
4571new number which, when multiplied by 5 modulo 24, produces the original
4572number, 21. If @var{m} is prime and the divisor is not a multiple of
4573@var{m}, it is always possible to find such a number. For non-prime
40ba43b4 4574@var{m} like 24, it is only sometimes possible.
4009494e
GM
4575
4576@smallexample
4577@group
45781: 10 mod 24 1: 16 mod 24 1: 1000000... 1: 16
4579 . . . .
4580
4581 10 M 24 @key{RET} 100 ^ 10 @key{RET} 100 ^ 24 %
4582@end group
4583@end smallexample
4584
4585@noindent
4586These two calculations get the same answer, but the first one is
4587much more efficient because it avoids the huge intermediate value
4588that arises in the second one.
4589
4590@cindex Fermat, primality test of
4591(@bullet{}) @strong{Exercise 10.} A theorem of Pierre de Fermat
40ba43b4 4592says that
d2bd74ff 4593@texline @math{x^{n-1} \bmod n = 1}
4009494e
GM
4594@infoline @expr{x^(n-1) mod n = 1}
4595if @expr{n} is a prime number and @expr{x} is an integer less than
4596@expr{n}. If @expr{n} is @emph{not} a prime number, this will
4597@emph{not} be true for most values of @expr{x}. Thus we can test
4598informally if a number is prime by trying this formula for several
4599values of @expr{x}. Use this test to tell whether the following numbers
4600are prime: 811749613, 15485863. @xref{Types Answer 10, 10}. (@bullet{})
4601
4602It is possible to use HMS forms as parts of error forms, intervals,
4603modulo forms, or as the phase part of a polar complex number.
4604For example, the @code{calc-time} command pushes the current time
4605of day on the stack as an HMS/modulo form.
4606
4607@smallexample
4608@group
46091: 17@@ 34' 45" mod 24@@ 0' 0" 1: 6@@ 22' 15" mod 24@@ 0' 0"
4610 . .
4611
4612 x time @key{RET} n
4613@end group
4614@end smallexample
4615
4616@noindent
4617This calculation tells me it is six hours and 22 minutes until midnight.
4618
4619(@bullet{}) @strong{Exercise 11.} A rule of thumb is that one year
40ba43b4 4620is about
4009494e 4621@texline @math{\pi \times 10^7}
40ba43b4 4622@infoline @w{@expr{pi * 10^7}}
4009494e
GM
4623seconds. What time will it be that many seconds from right now?
4624@xref{Types Answer 11, 11}. (@bullet{})
4625
4626(@bullet{}) @strong{Exercise 12.} You are preparing to order packaging
4627for the CD release of the Extended Disco Version of @emph{Abbey Road}.
4628You are told that the songs will actually be anywhere from 20 to 60
4629seconds longer than the originals. One CD can hold about 75 minutes
4630of music. Should you order single or double packages?
4631@xref{Types Answer 12, 12}. (@bullet{})
4632
4633Another kind of data the Calculator can manipulate is numbers with
4634@dfn{units}. This isn't strictly a new data type; it's simply an
4635application of algebraic expressions, where we use variables with
4636suggestive names like @samp{cm} and @samp{in} to represent units
4637like centimeters and inches.
4638
4639@smallexample
4640@group
46411: 2 in 1: 5.08 cm 1: 0.027778 fath 1: 0.0508 m
4642 . . . .
4643
4644 ' 2in @key{RET} u c cm @key{RET} u c fath @key{RET} u b
4645@end group
4646@end smallexample
4647
4648@noindent
4649We enter the quantity ``2 inches'' (actually an algebraic expression
4650which means two times the variable @samp{in}), then we convert it
4651first to centimeters, then to fathoms, then finally to ``base'' units,
4652which in this case means meters.
4653
4654@smallexample
4655@group
46561: 9 acre 1: 3 sqrt(acre) 1: 190.84 m 1: 190.84 m + 30 cm
4657 . . . .
4658
4659 ' 9 acre @key{RET} Q u s ' $+30 cm @key{RET}
4660
4661@end group
4662@end smallexample
4663@noindent
4664@smallexample
4665@group
46661: 191.14 m 1: 36536.3046 m^2 1: 365363046 cm^2
4667 . . .
4668
4669 u s 2 ^ u c cgs
4670@end group
4671@end smallexample
4672
4673@noindent
4674Since units expressions are really just formulas, taking the square
4675root of @samp{acre} is undefined. After all, @code{acre} might be an
4676algebraic variable that you will someday assign a value. We use the
4677``units-simplify'' command to simplify the expression with variables
4678being interpreted as unit names.
4679
4680In the final step, we have converted not to a particular unit, but to a
4681units system. The ``cgs'' system uses centimeters instead of meters
4682as its standard unit of length.
4683
4684There is a wide variety of units defined in the Calculator.
4685
4686@smallexample
4687@group
46881: 55 mph 1: 88.5139 kph 1: 88.5139 km / hr 1: 8.201407e-8 c
4689 . . . .
4690
4691 ' 55 mph @key{RET} u c kph @key{RET} u c km/hr @key{RET} u c c @key{RET}
4692@end group
4693@end smallexample
4694
4695@noindent
4696We express a speed first in miles per hour, then in kilometers per
4697hour, then again using a slightly more explicit notation, then
4698finally in terms of fractions of the speed of light.
4699
4700Temperature conversions are a bit more tricky. There are two ways to
4701interpret ``20 degrees Fahrenheit''---it could mean an actual
4702temperature, or it could mean a change in temperature. For normal
4703units there is no difference, but temperature units have an offset
4704as well as a scale factor and so there must be two explicit commands
4705for them.
4706
4707@smallexample
4708@group
d2bd74ff 47091: 20 degF 1: 11.1111 degC 1: -6.666 degC
4009494e
GM
4710 . . . .
4711
d2bd74ff 4712 ' 20 degF @key{RET} u c degC @key{RET} U u t degC @key{RET}
4009494e
GM
4713@end group
4714@end smallexample
4715
4716@noindent
4717First we convert a change of 20 degrees Fahrenheit into an equivalent
4718change in degrees Celsius (or Centigrade). Then, we convert the
d2bd74ff 4719absolute temperature 20 degrees Fahrenheit into Celsius.
4009494e
GM
4720
4721For simple unit conversions, you can put a plain number on the stack.
4722Then @kbd{u c} and @kbd{u t} will prompt for both old and new units.
4723When you use this method, you're responsible for remembering which
4724numbers are in which units:
4725
4726@smallexample
4727@group
47281: 55 1: 88.5139 1: 8.201407e-8
4729 . . .
4730
4731 55 u c mph @key{RET} kph @key{RET} u c km/hr @key{RET} c @key{RET}
4732@end group
4733@end smallexample
4734
4735To see a complete list of built-in units, type @kbd{u v}. Press
4736@w{@kbd{C-x * c}} again to re-enter the Calculator when you're done looking
4737at the units table.
4738
4739(@bullet{}) @strong{Exercise 13.} How many seconds are there really
4740in a year? @xref{Types Answer 13, 13}. (@bullet{})
4741
4742@cindex Speed of light
4743(@bullet{}) @strong{Exercise 14.} Supercomputer designs are limited by
4744the speed of light (and of electricity, which is nearly as fast).
4745Suppose a computer has a 4.1 ns (nanosecond) clock cycle, and its
4746cabinet is one meter across. Is speed of light going to be a
4747significant factor in its design? @xref{Types Answer 14, 14}. (@bullet{})
4748
4749(@bullet{}) @strong{Exercise 15.} Sam the Slug normally travels about
4750five yards in an hour. He has obtained a supply of Power Pills; each
4751Power Pill he eats doubles his speed. How many Power Pills can he
4752swallow and still travel legally on most US highways?
4753@xref{Types Answer 15, 15}. (@bullet{})
4754
4755@node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
4756@section Algebra and Calculus Tutorial
4757
4758@noindent
4759This section shows how to use Calc's algebra facilities to solve
4760equations, do simple calculus problems, and manipulate algebraic
4761formulas.
4762
4763@menu
4764* Basic Algebra Tutorial::
4765* Rewrites Tutorial::
4766@end menu
4767
4768@node Basic Algebra Tutorial, Rewrites Tutorial, Algebra Tutorial, Algebra Tutorial
4769@subsection Basic Algebra
4770
4771@noindent
4772If you enter a formula in Algebraic mode that refers to variables,
4773the formula itself is pushed onto the stack. You can manipulate
4774formulas as regular data objects.
4775
4776@smallexample
4777@group
d2bd74ff 47781: 2 x^2 - 6 1: 6 - 2 x^2 1: (3 x^2 + y) (6 - 2 x^2)
4009494e
GM
4779 . . .
4780
4781 ' 2x^2-6 @key{RET} n ' 3x^2+y @key{RET} *
4782@end group
4783@end smallexample
4784
4785(@bullet{}) @strong{Exercise 1.} Do @kbd{' x @key{RET} Q 2 ^} and
4786@kbd{' x @key{RET} 2 ^ Q} both wind up with the same result (@samp{x})?
4787Why or why not? @xref{Algebra Answer 1, 1}. (@bullet{})
4788
4789There are also commands for doing common algebraic operations on
4790formulas. Continuing with the formula from the last example,
4791
4792@smallexample
4793@group
d2bd74ff 47941: 18 x^2 - 6 x^4 + 6 y - 2 y x^2 1: (18 - 2 y) x^2 - 6 x^4 + 6 y
4009494e
GM
4795 . .
4796
4797 a x a c x @key{RET}
4798@end group
4799@end smallexample
4800
4801@noindent
4802First we ``expand'' using the distributive law, then we ``collect''
4803terms involving like powers of @expr{x}.
4804
4805Let's find the value of this expression when @expr{x} is 2 and @expr{y}
4806is one-half.
4807
4808@smallexample
4809@group
48101: 17 x^2 - 6 x^4 + 3 1: -25
4811 . .
4812
4813 1:2 s l y @key{RET} 2 s l x @key{RET}
4814@end group
4815@end smallexample
4816
4817@noindent
4818The @kbd{s l} command means ``let''; it takes a number from the top of
4819the stack and temporarily assigns it as the value of the variable
4820you specify. It then evaluates (as if by the @kbd{=} key) the
4821next expression on the stack. After this command, the variable goes
4822back to its original value, if any.
4823
4824(An earlier exercise in this tutorial involved storing a value in the
4825variable @code{x}; if this value is still there, you will have to
4826unstore it with @kbd{s u x @key{RET}} before the above example will work
4827properly.)
4828
4829@cindex Maximum of a function using Calculus
4830Let's find the maximum value of our original expression when @expr{y}
4831is one-half and @expr{x} ranges over all possible values. We can
4832do this by taking the derivative with respect to @expr{x} and examining
4833values of @expr{x} for which the derivative is zero. If the second
4834derivative of the function at that value of @expr{x} is negative,
4835the function has a local maximum there.
4836
4837@smallexample
4838@group
48391: 17 x^2 - 6 x^4 + 3 1: 34 x - 24 x^3
4840 . .
4841
4842 U @key{DEL} s 1 a d x @key{RET} s 2
4843@end group
4844@end smallexample
4845
4846@noindent
4847Well, the derivative is clearly zero when @expr{x} is zero. To find
4848the other root(s), let's divide through by @expr{x} and then solve:
4849
4850@smallexample
4851@group
d2bd74ff
JB
48521: (34 x - 24 x^3) / x 1: 34 - 24 x^2
4853 . .
4009494e 4854
d2bd74ff 4855 ' x @key{RET} / a x
4009494e
GM
4856
4857@end group
4858@end smallexample
4859@noindent
4860@smallexample
4861@group
d2bd74ff 48621: 0.70588 x^2 = 1 1: x = 1.19023
4009494e
GM
4863 . .
4864
4865 0 a = s 3 a S x @key{RET}
4866@end group
4867@end smallexample
4868
4869@noindent
4009494e
GM
4870Now we compute the second derivative and plug in our values of @expr{x}:
4871
4872@smallexample
4873@group
48741: 1.19023 2: 1.19023 2: 1.19023
4875 . 1: 34 x - 24 x^3 1: 34 - 72 x^2
4876 . .
4877
4878 a . r 2 a d x @key{RET} s 4
4879@end group
4880@end smallexample
4881
4882@noindent
4883(The @kbd{a .} command extracts just the righthand side of an equation.
4884Another method would have been to use @kbd{v u} to unpack the equation
4885@w{@samp{x = 1.19}} to @samp{x} and @samp{1.19}, then use @kbd{M-- M-2 @key{DEL}}
4886to delete the @samp{x}.)
4887
4888@smallexample
4889@group
48902: 34 - 72 x^2 1: -68. 2: 34 - 72 x^2 1: 34
48911: 1.19023 . 1: 0 .
4892 . .
4893
4894 @key{TAB} s l x @key{RET} U @key{DEL} 0 s l x @key{RET}
4895@end group
4896@end smallexample
4897
4898@noindent
4899The first of these second derivatives is negative, so we know the function
4900has a maximum value at @expr{x = 1.19023}. (The function also has a
4901local @emph{minimum} at @expr{x = 0}.)
4902
4903When we solved for @expr{x}, we got only one value even though
d2bd74ff 4904@expr{0.70588 x^2 = 1} is a quadratic equation that ought to have
4009494e
GM
4905two solutions. The reason is that @w{@kbd{a S}} normally returns a
4906single ``principal'' solution. If it needs to come up with an
4907arbitrary sign (as occurs in the quadratic formula) it picks @expr{+}.
4908If it needs an arbitrary integer, it picks zero. We can get a full
4909solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
4910
4911@smallexample
4912@group
d2bd74ff 49131: 0.70588 x^2 = 1 1: x = 1.19023 s1 1: x = -1.19023
4009494e
GM
4914 . . .
4915
4916 r 3 H a S x @key{RET} s 5 1 n s l s1 @key{RET}
4917@end group
4918@end smallexample
4919
4920@noindent
4921Calc has invented the variable @samp{s1} to represent an unknown sign;
4922it is supposed to be either @mathit{+1} or @mathit{-1}. Here we have used
4923the ``let'' command to evaluate the expression when the sign is negative.
4924If we plugged this into our second derivative we would get the same,
4925negative, answer, so @expr{x = -1.19023} is also a maximum.
4926
4927To find the actual maximum value, we must plug our two values of @expr{x}
4928into the original formula.
4929
4930@smallexample
4931@group
49322: 17 x^2 - 6 x^4 + 3 1: 24.08333 s1^2 - 12.04166 s1^4 + 3
49331: x = 1.19023 s1 .
4934 .
4935
4936 r 1 r 5 s l @key{RET}
4937@end group
4938@end smallexample
4939
4940@noindent
4941(Here we see another way to use @kbd{s l}; if its input is an equation
4942with a variable on the lefthand side, then @kbd{s l} treats the equation
4943like an assignment to that variable if you don't give a variable name.)
4944
4945It's clear that this will have the same value for either sign of
4946@code{s1}, but let's work it out anyway, just for the exercise:
4947
4948@smallexample
4949@group
49502: [-1, 1] 1: [15.04166, 15.04166]
49511: 24.08333 s1^2 ... .
4952 .
4953
4954 [ 1 n , 1 ] @key{TAB} V M $ @key{RET}
4955@end group
4956@end smallexample
4957
4958@noindent
4959Here we have used a vector mapping operation to evaluate the function
4960at several values of @samp{s1} at once. @kbd{V M $} is like @kbd{V M '}
4961except that it takes the formula from the top of the stack. The
4962formula is interpreted as a function to apply across the vector at the
4963next-to-top stack level. Since a formula on the stack can't contain
4964@samp{$} signs, Calc assumes the variables in the formula stand for
4965different arguments. It prompts you for an @dfn{argument list}, giving
4966the list of all variables in the formula in alphabetical order as the
4967default list. In this case the default is @samp{(s1)}, which is just
4968what we want so we simply press @key{RET} at the prompt.
4969
4970If there had been several different values, we could have used
4971@w{@kbd{V R X}} to find the global maximum.
4972
4973Calc has a built-in @kbd{a P} command that solves an equation using
4974@w{@kbd{H a S}} and returns a vector of all the solutions. It simply
4975automates the job we just did by hand. Applied to our original
4976cubic polynomial, it would produce the vector of solutions
4977@expr{[1.19023, -1.19023, 0]}. (There is also an @kbd{a X} command
4978which finds a local maximum of a function. It uses a numerical search
4979method rather than examining the derivatives, and thus requires you
4980to provide some kind of initial guess to show it where to look.)
4981
4982(@bullet{}) @strong{Exercise 2.} Given a vector of the roots of a
4983polynomial (such as the output of an @kbd{a P} command), what
4984sequence of commands would you use to reconstruct the original
4985polynomial? (The answer will be unique to within a constant
4986multiple; choose the solution where the leading coefficient is one.)
4987@xref{Algebra Answer 2, 2}. (@bullet{})
4988
4989The @kbd{m s} command enables Symbolic mode, in which formulas
4990like @samp{sqrt(5)} that can't be evaluated exactly are left in
4991symbolic form rather than giving a floating-point approximate answer.
4992Fraction mode (@kbd{m f}) is also useful when doing algebra.
4993
4994@smallexample
4995@group
49962: 34 x - 24 x^3 2: 34 x - 24 x^3
49971: 34 x - 24 x^3 1: [sqrt(51) / 6, sqrt(51) / -6, 0]
4998 . .
4999
5000 r 2 @key{RET} m s m f a P x @key{RET}
5001@end group
5002@end smallexample
5003
5004One more mode that makes reading formulas easier is Big mode.
5005
5006@smallexample
5007@group
5008 3
50092: 34 x - 24 x
5010
5011 ____ ____
5012 V 51 V 51
50131: [-----, -----, 0]
5014 6 -6
5015
5016 .
5017
5018 d B
5019@end group
5020@end smallexample
5021
5022Here things like powers, square roots, and quotients and fractions
5023are displayed in a two-dimensional pictorial form. Calc has other
5024language modes as well, such as C mode, FORTRAN mode, @TeX{} mode
c1dabff0 5025and @LaTeX{} mode.
4009494e
GM
5026
5027@smallexample
5028@group
50292: 34*x - 24*pow(x, 3) 2: 34*x - 24*x**3
50301: @{sqrt(51) / 6, sqrt(51) / -6, 0@} 1: /sqrt(51) / 6, sqrt(51) / -6, 0/
5031 . .
5032
5033 d C d F
5034
5035@end group
5036@end smallexample
5037@noindent
5038@smallexample
5039@group
50403: 34 x - 24 x^3
50412: [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
50421: @{2 \over 3@} \sqrt@{5@}
5043 .
5044
5045 d T ' 2 \sqrt@{5@} \over 3 @key{RET}
5046@end group
5047@end smallexample
5048
5049@noindent
5050As you can see, language modes affect both entry and display of
5051formulas. They affect such things as the names used for built-in
5052functions, the set of arithmetic operators and their precedences,
5053and notations for vectors and matrices.
5054
5055Notice that @samp{sqrt(51)} may cause problems with older
5056implementations of C and FORTRAN, which would require something more
5057like @samp{sqrt(51.0)}. It is always wise to check over the formulas
5058produced by the various language modes to make sure they are fully
5059correct.
5060
5061Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes. (You
5062may prefer to remain in Big mode, but all the examples in the tutorial
5063are shown in normal mode.)
5064
5065@cindex Area under a curve
5066What is the area under the portion of this curve from @expr{x = 1} to @expr{2}?
5067This is simply the integral of the function:
5068
5069@smallexample
5070@group
50711: 17 x^2 - 6 x^4 + 3 1: 5.6666 x^3 - 1.2 x^5 + 3 x
5072 . .
5073
5074 r 1 a i x
5075@end group
5076@end smallexample
5077
5078@noindent
5079We want to evaluate this at our two values for @expr{x} and subtract.
5080One way to do it is again with vector mapping and reduction:
5081
5082@smallexample
5083@group
50842: [2, 1] 1: [12.93333, 7.46666] 1: 5.46666
50851: 5.6666 x^3 ... . .
5086
5087 [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
5088@end group
5089@end smallexample
5090
5091(@bullet{}) @strong{Exercise 3.} Find the integral from 1 to @expr{y}
40ba43b4 5092of
4009494e 5093@texline @math{x \sin \pi x}
40ba43b4 5094@infoline @w{@expr{x sin(pi x)}}
4009494e
GM
5095(where the sine is calculated in radians). Find the values of the
5096integral for integers @expr{y} from 1 to 5. @xref{Algebra Answer 3,
50973}. (@bullet{})
5098
5099Calc's integrator can do many simple integrals symbolically, but many
5100others are beyond its capabilities. Suppose we wish to find the area
40ba43b4 5101under the curve
4009494e 5102@texline @math{\sin x \ln x}
40ba43b4 5103@infoline @expr{sin(x) ln(x)}
4009494e
GM
5104over the same range of @expr{x}. If you entered this formula and typed
5105@kbd{a i x @key{RET}} (don't bother to try this), Calc would work for a
5106long time but would be unable to find a solution. In fact, there is no
5107closed-form solution to this integral. Now what do we do?
5108
5109@cindex Integration, numerical
5110@cindex Numerical integration
5111One approach would be to do the integral numerically. It is not hard
5112to do this by hand using vector mapping and reduction. It is rather
5113slow, though, since the sine and logarithm functions take a long time.
5114We can save some time by reducing the working precision.
5115
5116@smallexample
5117@group
51183: 10 1: [1, 1.1, 1.2, ... , 1.8, 1.9]
51192: 1 .
51201: 0.1
5121 .
5122
5123 10 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
5124@end group
5125@end smallexample
5126
5127@noindent
5128(Note that we have used the extended version of @kbd{v x}; we could
5129also have used plain @kbd{v x} as follows: @kbd{v x 10 @key{RET} 9 + .1 *}.)
5130
5131@smallexample
5132@group
51332: [1, 1.1, ... ] 1: [0., 0.084941, 0.16993, ... ]
d2bd74ff 51341: ln(x) sin(x) .
4009494e
GM
5135 .
5136
5137 ' sin(x) ln(x) @key{RET} s 1 m r p 5 @key{RET} V M $ @key{RET}
5138
5139@end group
5140@end smallexample
5141@noindent
5142@smallexample
5143@group
51441: 3.4195 0.34195
5145 . .
5146
5147 V R + 0.1 *
5148@end group
5149@end smallexample
5150
5151@noindent
5152(If you got wildly different results, did you remember to switch
5153to Radians mode?)
5154
5155Here we have divided the curve into ten segments of equal width;
5156approximating these segments as rectangular boxes (i.e., assuming
5157the curve is nearly flat at that resolution), we compute the areas
5158of the boxes (height times width), then sum the areas. (It is
5159faster to sum first, then multiply by the width, since the width
5160is the same for every box.)
5161
5162The true value of this integral turns out to be about 0.374, so
5163we're not doing too well. Let's try another approach.
5164
5165@smallexample
5166@group
d2bd74ff 51671: ln(x) sin(x) 1: 0.84147 x + 0.11957 (x - 1)^2 - ...
4009494e
GM
5168 . .
5169
5170 r 1 a t x=1 @key{RET} 4 @key{RET}
5171@end group
5172@end smallexample
5173
5174@noindent
5175Here we have computed the Taylor series expansion of the function
5176about the point @expr{x=1}. We can now integrate this polynomial
5177approximation, since polynomials are easy to integrate.
5178
5179@smallexample
5180@group
51811: 0.42074 x^2 + ... 1: [-0.0446, -0.42073] 1: 0.3761
5182 . . .
5183
5184 a i x @key{RET} [ 2 , 1 ] @key{TAB} V M $ @key{RET} V R -
5185@end group
5186@end smallexample
5187
5188@noindent
5189Better! By increasing the precision and/or asking for more terms
5190in the Taylor series, we can get a result as accurate as we like.
5191(Taylor series converge better away from singularities in the
5192function such as the one at @code{ln(0)}, so it would also help to
5193expand the series about the points @expr{x=2} or @expr{x=1.5} instead
5194of @expr{x=1}.)
5195
5196@cindex Simpson's rule
5197@cindex Integration by Simpson's rule
5198(@bullet{}) @strong{Exercise 4.} Our first method approximated the
5199curve by stairsteps of width 0.1; the total area was then the sum
5200of the areas of the rectangles under these stairsteps. Our second
5201method approximated the function by a polynomial, which turned out
5202to be a better approximation than stairsteps. A third method is
5203@dfn{Simpson's rule}, which is like the stairstep method except
5204that the steps are not required to be flat. Simpson's rule boils
5205down to the formula,
5206
5207@ifnottex
5208@example
5209(h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
5210 + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
5211@end example
5212@end ifnottex
5213@tex
4009494e
GM
5214\beforedisplay
5215$$ \displaylines{
5216 \qquad {h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
5217 \hfill \cr \hfill {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h)) \qquad
5218} $$
5219\afterdisplay
5220@end tex
5221
5222@noindent
5223where @expr{n} (which must be even) is the number of slices and @expr{h}
5224is the width of each slice. These are 10 and 0.1 in our example.
5225For reference, here is the corresponding formula for the stairstep
5226method:
5227
5228@ifnottex
5229@example
5230h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
5231 + f(a+(n-2)*h) + f(a+(n-1)*h))
5232@end example
5233@end ifnottex
5234@tex
4009494e
GM
5235\beforedisplay
5236$$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
5237 + f(a+(n-2)h) + f(a+(n-1)h)) $$
5238\afterdisplay
5239@end tex
5240
40ba43b4 5241Compute the integral from 1 to 2 of
4009494e 5242@texline @math{\sin x \ln x}
40ba43b4
PE
5243@infoline @expr{sin(x) ln(x)}
5244using Simpson's rule with 10 slices.
4009494e
GM
5245@xref{Algebra Answer 4, 4}. (@bullet{})
5246
5247Calc has a built-in @kbd{a I} command for doing numerical integration.
5248It uses @dfn{Romberg's method}, which is a more sophisticated cousin
5249of Simpson's rule. In particular, it knows how to keep refining the
5250result until the current precision is satisfied.
5251
5252@c [fix-ref Selecting Sub-Formulas]
5253Aside from the commands we've seen so far, Calc also provides a
5254large set of commands for operating on parts of formulas. You
5255indicate the desired sub-formula by placing the cursor on any part
5256of the formula before giving a @dfn{selection} command. Selections won't
5257be covered in the tutorial; @pxref{Selecting Subformulas}, for
5258details and examples.
5259
5260@c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
5261@c to 2^((n-1)*(r-1)).
5262
5263@node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
5264@subsection Rewrite Rules
5265
5266@noindent
5267No matter how many built-in commands Calc provided for doing algebra,
5268there would always be something you wanted to do that Calc didn't have
5269in its repertoire. So Calc also provides a @dfn{rewrite rule} system
5270that you can use to define your own algebraic manipulations.
5271
5272Suppose we want to simplify this trigonometric formula:
5273
5274@smallexample
5275@group
d2bd74ff 52761: 2 sec(x)^2 / tan(x)^2 - 2 / tan(x)^2
4009494e
GM
5277 .
5278
d2bd74ff 5279 ' 2sec(x)^2/tan(x)^2 - 2/tan(x)^2 @key{RET} s 1
4009494e
GM
5280@end group
5281@end smallexample
5282
5283@noindent
d2bd74ff
JB
5284If we were simplifying this by hand, we'd probably combine over the common
5285denominator. The @kbd{a n} algebra command will do this, but we'll do
5286it with a rewrite rule just for practice.
4009494e
GM
5287
5288Rewrite rules are written with the @samp{:=} symbol.
5289
5290@smallexample
5291@group
d2bd74ff 52921: (2 sec(x)^2 - 2) / tan(x)^2
4009494e
GM
5293 .
5294
d2bd74ff 5295 a r a/x + b/x := (a+b)/x @key{RET}
4009494e
GM
5296@end group
5297@end smallexample
5298
5299@noindent
5300(The ``assignment operator'' @samp{:=} has several uses in Calc. All
d2bd74ff 5301by itself the formula @samp{a/x + b/x := (a+b)/x} doesn't do anything,
4009494e
GM
5302but when it is given to the @kbd{a r} command, that command interprets
5303it as a rewrite rule.)
5304
d2bd74ff 5305The lefthand side, @samp{a/x + b/x}, is called the @dfn{pattern} of the
4009494e
GM
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
d2bd74ff
JB
5310the expression @samp{2 sec(x)^2}, the meta-variable @samp{b} matched
5311the constant @samp{-2} and the meta-variable @samp{x} matched
5312the expression @samp{tan(x)^2}.
4009494e
GM
5313
5314This rule points out several interesting features of rewrite patterns.
5315First, if a meta-variable appears several times in a pattern, it must
5316match the same thing everywhere. This rule detects common denominators
5317because the same meta-variable @samp{x} is used in both of the
5318denominators.
5319
5320Second, meta-variable names are independent from variables in the
5321target formula. Notice that the meta-variable @samp{x} here matches
d2bd74ff 5322the subformula @samp{tan(x)^2}; Calc never confuses the two meanings of
4009494e
GM
5323@samp{x}.
5324
5325And third, rewrite patterns know a little bit about the algebraic
5326properties of formulas. The pattern called for a sum of two quotients;
5327Calc was able to match a difference of two quotients by matching
d2bd74ff
JB
5328@samp{a = 2 sec(x)^2}, @samp{b = -2}, and @samp{x = tan(x)^2}.
5329
5330When the pattern part of a rewrite rule matches a part of the formula,
5331that part is replaced by the righthand side with all the meta-variables
5332substituted with the things they matched. So the result is
5333@samp{(2 sec(x)^2 - 2) / tan(x)^2}.
4009494e
GM
5334
5335@c [fix-ref Algebraic Properties of Rewrite Rules]
5336We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
5337the rule. It would have worked just the same in all cases. (If we
5338really wanted the rule to apply only to @samp{+} or only to @samp{-},
5339we could have used the @code{plain} symbol. @xref{Algebraic Properties
5340of Rewrite Rules}, for some examples of this.)
5341
5342One more rewrite will complete the job. We want to use the identity
d2bd74ff 5343@samp{tan(x)^2 + 1 = sec(x)^2}, but of course we must first rearrange
4009494e 5344the identity in a way that matches our formula. The obvious rule
d2bd74ff
JB
5345would be @samp{@w{2 sec(x)^2 - 2} := 2 tan(x)^2}, but a little thought shows
5346that the rule @samp{sec(x)^2 := 1 + tan(x)^2} will also work. The
4009494e
GM
5347latter rule has a more general pattern so it will work in many other
5348situations, too.
5349
5350@smallexample
5351@group
d2bd74ff
JB
53521: 2
5353 .
4009494e 5354
d2bd74ff 5355 a r sec(x)^2 := 1 + tan(x)^2 @key{RET}
4009494e
GM
5356@end group
5357@end smallexample
5358
5359You may ask, what's the point of using the most general rule if you
5360have to type it in every time anyway? The answer is that Calc allows
5361you to store a rewrite rule in a variable, then give the variable
5362name in the @kbd{a r} command. In fact, this is the preferred way to
5363use rewrites. For one, if you need a rule once you'll most likely
5364need it again later. Also, if the rule doesn't work quite right you
5365can simply Undo, edit the variable, and run the rule again without
5366having to retype it.
5367
5368@smallexample
5369@group
d2bd74ff
JB
5370' a/x + b/x := (a+b)/x @key{RET} s t merge @key{RET}
5371' sec(x)^2 := 1 + tan(x)^2 @key{RET} s t secsqr @key{RET}
4009494e 5372
d2bd74ff 53731: 2 sec(x)^2 / tan(x)^2 - 2 / tan(x)^2 1: 2
4009494e
GM
5374 . .
5375
d2bd74ff 5376 r 1 a r merge @key{RET} a r secsqr @key{RET}
4009494e
GM
5377@end group
5378@end smallexample
5379
5380To edit a variable, type @kbd{s e} and the variable name, use regular
5381Emacs editing commands as necessary, then type @kbd{C-c C-c} to store
40ba43b4 5382the edited value back into the variable.
4009494e
GM
5383You can also use @w{@kbd{s e}} to create a new variable if you wish.
5384
5385Notice that the first time you use each rule, Calc puts up a ``compiling''
5386message briefly. The pattern matcher converts rules into a special
5387optimized pattern-matching language rather than using them directly.
5388This allows @kbd{a r} to apply even rather complicated rules very
5389efficiently. If the rule is stored in a variable, Calc compiles it
5390only once and stores the compiled form along with the variable. That's
5391another good reason to store your rules in variables rather than
5392entering them on the fly.
5393
5394(@bullet{}) @strong{Exercise 1.} Type @kbd{m s} to get Symbolic
5395mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
5396Using a rewrite rule, simplify this formula by multiplying the top and
5397bottom by the conjugate @w{@samp{1 - sqrt(2)}}. The result will have
5398to be expanded by the distributive law; do this with another
5399rewrite. @xref{Rewrites Answer 1, 1}. (@bullet{})
5400
5401The @kbd{a r} command can also accept a vector of rewrite rules, or
5402a variable containing a vector of rules.
5403
5404@smallexample
5405@group
d2bd74ff 54061: [merge, secsqr] 1: [a/x + b/x := (a + b)/x, ... ]
4009494e
GM
5407 . .
5408
d2bd74ff 5409 ' [merge,sinsqr] @key{RET} =
4009494e
GM
5410
5411@end group
5412@end smallexample
5413@noindent
5414@smallexample
5415@group
d2bd74ff 54161: 2 sec(x)^2 / tan(x)^2 - 2 / tan(x)^2 1: 2
4009494e
GM
5417 . .
5418
d2bd74ff 5419 s t trig @key{RET} r 1 a r trig @key{RET}
4009494e
GM
5420@end group
5421@end smallexample
5422
5423@c [fix-ref Nested Formulas with Rewrite Rules]
5424Calc tries all the rules you give against all parts of the formula,
5425repeating until no further change is possible. (The exact order in
5426which things are tried is rather complex, but for simple rules like
5427the ones we've used here the order doesn't really matter.
5428@xref{Nested Formulas with Rewrite Rules}.)
5429
5430Calc actually repeats only up to 100 times, just in case your rule set
5431has gotten into an infinite loop. You can give a numeric prefix argument
5432to @kbd{a r} to specify any limit. In particular, @kbd{M-1 a r} does
5433only one rewrite at a time.
5434
5435@smallexample
5436@group
d2bd74ff
JB
54371: (2 sec(x)^2 - 2) / tan(x)^2 1: 2
5438 . .
4009494e 5439
d2bd74ff 5440 r 1 M-1 a r trig @key{RET} M-1 a r trig @key{RET}
4009494e
GM
5441@end group
5442@end smallexample
5443
5444You can type @kbd{M-0 a r} if you want no limit at all on the number
5445of rewrites that occur.
5446
5447Rewrite rules can also be @dfn{conditional}. Simply follow the rule
5448with a @samp{::} symbol and the desired condition. For example,
5449
5450@smallexample
5451@group
d2bd74ff 54521: sin(x + 2 pi) + sin(x + 3 pi) + sin(x + 4 pi)
4009494e
GM
5453 .
5454
d2bd74ff 5455 ' sin(x+2pi) + sin(x+3pi) + sin(x+4pi) @key{RET}
4009494e
GM
5456
5457@end group
5458@end smallexample
5459@noindent
5460@smallexample
5461@group
d2bd74ff 54621: sin(x + 3 pi) + 2 sin(x)
4009494e
GM
5463 .
5464
d2bd74ff 5465 a r sin(a + k pi) := sin(a) :: k % 2 = 0 @key{RET}
4009494e
GM
5466@end group
5467@end smallexample
5468
5469@noindent
5470(Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
5471which will be zero only when @samp{k} is an even integer.)
5472
d2bd74ff
JB
5473An interesting point is that the variable @samp{pi} was matched
5474literally rather than acting as a meta-variable.
5475This is because it is a special-constant variable. The special
5476constants @samp{e}, @samp{i}, @samp{phi}, and so on also match literally.
4009494e
GM
5477A common error with rewrite
5478rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
5479to match any @samp{f} with five arguments but in fact matching
5480only when the fifth argument is literally @samp{e}!
5481
5482@cindex Fibonacci numbers
5483@ignore
5484@starindex
5485@end ignore
5486@tindex fib
5487Rewrite rules provide an interesting way to define your own functions.
5488Suppose we want to define @samp{fib(n)} to produce the @var{n}th
5489Fibonacci number. The first two Fibonacci numbers are each 1;
5490later numbers are formed by summing the two preceding numbers in
5491the sequence. This is easy to express in a set of three rules:
5492
5493@smallexample
5494@group
5495' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] @key{RET} s t fib
5496
54971: fib(7) 1: 13
5498 . .
5499
5500 ' fib(7) @key{RET} a r fib @key{RET}
5501@end group
5502@end smallexample
5503
5504One thing that is guaranteed about the order that rewrites are tried
5505is that, for any given subformula, earlier rules in the rule set will
5506be tried for that subformula before later ones. So even though the
5507first and third rules both match @samp{fib(1)}, we know the first will
5508be used preferentially.
5509
5510This rule set has one dangerous bug: Suppose we apply it to the
5511formula @samp{fib(x)}? (Don't actually try this.) The third rule
5512will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
5513Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
5514fib(x-4)}, and so on, expanding forever. What we really want is to apply
5515the third rule only when @samp{n} is an integer greater than two. Type
5516@w{@kbd{s e fib @key{RET}}}, then edit the third rule to:
5517
5518@smallexample
5519fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
5520@end smallexample
5521
5522@noindent
5523Now:
5524
5525@smallexample
5526@group
d2bd74ff 55271: fib(6) + fib(x) + fib(0) 1: fib(x) + fib(0) + 8
4009494e
GM
5528 . .
5529
5530 ' fib(6)+fib(x)+fib(0) @key{RET} a r fib @key{RET}
5531@end group
5532@end smallexample
5533
5534@noindent
5535We've created a new function, @code{fib}, and a new command,
5536@w{@kbd{a r fib @key{RET}}}, which means ``evaluate all @code{fib} calls in
5537this formula.'' To make things easier still, we can tell Calc to
5538apply these rules automatically by storing them in the special
5539variable @code{EvalRules}.
5540
5541@smallexample
5542@group
55431: [fib(1) := ...] . 1: [8, 13]
5544 . .
5545
5546 s r fib @key{RET} s t EvalRules @key{RET} ' [fib(6), fib(7)] @key{RET}
5547@end group
5548@end smallexample
5549
5550It turns out that this rule set has the problem that it does far
5551more work than it needs to when @samp{n} is large. Consider the
5552first few steps of the computation of @samp{fib(6)}:
5553
5554@smallexample
5555@group
5556fib(6) =
5557fib(5) + fib(4) =
5558fib(4) + fib(3) + fib(3) + fib(2) =
5559fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
5560@end group
5561@end smallexample
5562
5563@noindent
5564Note that @samp{fib(3)} appears three times here. Unless Calc's
5565algebraic simplifier notices the multiple @samp{fib(3)}s and combines
5566them (and, as it happens, it doesn't), this rule set does lots of
5567needless recomputation. To cure the problem, type @code{s e EvalRules}
5568to edit the rules (or just @kbd{s E}, a shorthand command for editing
5569@code{EvalRules}) and add another condition:
5570
5571@smallexample
5572fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
5573@end smallexample
5574
5575@noindent
5576If a @samp{:: remember} condition appears anywhere in a rule, then if
5577that rule succeeds Calc will add another rule that describes that match
5578to the front of the rule set. (Remembering works in any rule set, but
5579for technical reasons it is most effective in @code{EvalRules}.) For
5580example, if the rule rewrites @samp{fib(7)} to something that evaluates
5581to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
5582
5583Type @kbd{' fib(8) @key{RET}} to compute the eighth Fibonacci number, then
5584type @kbd{s E} again to see what has happened to the rule set.
5585
5586With the @code{remember} feature, our rule set can now compute
5587@samp{fib(@var{n})} in just @var{n} steps. In the process it builds
5588up a table of all Fibonacci numbers up to @var{n}. After we have
5589computed the result for a particular @var{n}, we can get it back
5590(and the results for all smaller @var{n}) later in just one step.
5591
5592All Calc operations will run somewhat slower whenever @code{EvalRules}
5593contains any rules. You should type @kbd{s u EvalRules @key{RET}} now to
5594un-store the variable.
5595
5596(@bullet{}) @strong{Exercise 2.} Sometimes it is possible to reformulate
5597a problem to reduce the amount of recursion necessary to solve it.
5598Create a rule that, in about @var{n} simple steps and without recourse
5599to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
5600@samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
5601@var{n}th and @var{n+1}st Fibonacci numbers, respectively. This rule is
5602rather clunky to use, so add a couple more rules to make the ``user
5603interface'' the same as for our first version: enter @samp{fib(@var{n})},
5604get back a plain number. @xref{Rewrites Answer 2, 2}. (@bullet{})
5605
5606There are many more things that rewrites can do. For example, there
5607are @samp{&&&} and @samp{|||} pattern operators that create ``and''
5608and ``or'' combinations of rules. As one really simple example, we
5609could combine our first two Fibonacci rules thusly:
5610
5611@example
5612[fib(1 ||| 2) := 1, fib(n) := ... ]
5613@end example
5614
5615@noindent
5616That means ``@code{fib} of something matching either 1 or 2 rewrites
5617to 1.''
5618
5619You can also make meta-variables optional by enclosing them in @code{opt}.
5620For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
5621@samp{2 + x} or @samp{3 x} or @samp{x}. The pattern @samp{opt(a) + opt(b) x}
5622matches all of these forms, filling in a default of zero for @samp{a}
5623and one for @samp{b}.
5624
5625(@bullet{}) @strong{Exercise 3.} Your friend Joe had @samp{2 + 3 x}
5626on the stack and tried to use the rule
5627@samp{opt(a) + opt(b) x := f(a, b, x)}. What happened?
5628@xref{Rewrites Answer 3, 3}. (@bullet{})
5629
5630(@bullet{}) @strong{Exercise 4.} Starting with a positive integer @expr{a},
5631divide @expr{a} by two if it is even, otherwise compute @expr{3 a + 1}.
5632Now repeat this step over and over. A famous unproved conjecture
5633is that for any starting @expr{a}, the sequence always eventually
5634reaches 1. Given the formula @samp{seq(@var{a}, 0)}, write a set of
5635rules that convert this into @samp{seq(1, @var{n})} where @var{n}
5636is the number of steps it took the sequence to reach the value 1.
5637Now enhance the rules to accept @samp{seq(@var{a})} as a starting
5638configuration, and to stop with just the number @var{n} by itself.
5639Now make the result be a vector of values in the sequence, from @var{a}
5640to 1. (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
5641and @var{y}.) For example, rewriting @samp{seq(6)} should yield the
5642vector @expr{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
5643@xref{Rewrites Answer 4, 4}. (@bullet{})
5644
5645(@bullet{}) @strong{Exercise 5.} Define, using rewrite rules, a function
5646@samp{nterms(@var{x})} that returns the number of terms in the sum
5647@var{x}, or 1 if @var{x} is not a sum. (A @dfn{sum} for our purposes
5648is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
5649so that @expr{2 - 3 (x + y) + x y} is a sum of three terms.)
5650@xref{Rewrites Answer 5, 5}. (@bullet{})
5651
5652(@bullet{}) @strong{Exercise 6.} A Taylor series for a function is an
5653infinite series that exactly equals the value of that function at
5654values of @expr{x} near zero.
5655
5656@ifnottex
5657@example
5658cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
5659@end example
5660@end ifnottex
5661@tex
4009494e
GM
5662\beforedisplay
5663$$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
5664\afterdisplay
5665@end tex
5666
5667The @kbd{a t} command produces a @dfn{truncated Taylor series} which
5668is obtained by dropping all the terms higher than, say, @expr{x^2}.
5669Calc represents the truncated Taylor series as a polynomial in @expr{x}.
5670Mathematicians often write a truncated series using a ``big-O'' notation
5671that records what was the lowest term that was truncated.
5672
5673@ifnottex
5674@example
5675cos(x) = 1 - x^2 / 2! + O(x^3)
5676@end example
5677@end ifnottex
5678@tex
4009494e
GM
5679\beforedisplay
5680$$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
5681\afterdisplay
5682@end tex
5683
5684@noindent
5685The meaning of @expr{O(x^3)} is ``a quantity which is negligibly small
5686if @expr{x^3} is considered negligibly small as @expr{x} goes to zero.''
5687
5688The exercise is to create rewrite rules that simplify sums and products of
5689power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
5690For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
5691on the stack, we want to be able to type @kbd{*} and get the result
5692@samp{x - 2:3 x^3 + O(x^4)}. Don't worry if the terms of the sum are
d2bd74ff
JB
5693rearranged. (This one is rather tricky; the solution at the end of
5694this chapter uses 6 rewrite rules. Hint: The @samp{constant(x)}
5695condition tests whether @samp{x} is a number.) @xref{Rewrites Answer
56966, 6}. (@bullet{})
4009494e
GM
5697
5698Just for kicks, try adding the rule @code{2+3 := 6} to @code{EvalRules}.
5699What happens? (Be sure to remove this rule afterward, or you might get
5700a nasty surprise when you use Calc to balance your checkbook!)
5701
5702@xref{Rewrite Rules}, for the whole story on rewrite rules.
5703
5704@node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
5705@section Programming Tutorial
5706
5707@noindent
5708The Calculator is written entirely in Emacs Lisp, a highly extensible
5709language. If you know Lisp, you can program the Calculator to do
5710anything you like. Rewrite rules also work as a powerful programming
5711system. But Lisp and rewrite rules take a while to master, and often
5712all you want to do is define a new function or repeat a command a few
5713times. Calc has features that allow you to do these things easily.
5714
5715One very limited form of programming is defining your own functions.
5716Calc's @kbd{Z F} command allows you to define a function name and
5717key sequence to correspond to any formula. Programming commands use
5718the shift-@kbd{Z} prefix; the user commands they create use the lower
5719case @kbd{z} prefix.
5720
5721@smallexample
5722@group
d2bd74ff 57231: x + x^2 / 2 + x^3 / 6 + 1 1: x + x^2 / 2 + x^3 / 6 + 1
4009494e
GM
5724 . .
5725
5726 ' 1 + x + x^2/2! + x^3/3! @key{RET} Z F e myexp @key{RET} @key{RET} @key{RET} y
5727@end group
5728@end smallexample
5729
5730This polynomial is a Taylor series approximation to @samp{exp(x)}.
5731The @kbd{Z F} command asks a number of questions. The above answers
5732say that the key sequence for our function should be @kbd{z e}; the
5733@kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
5734function in algebraic formulas should also be @code{myexp}; the
5735default argument list @samp{(x)} is acceptable; and finally @kbd{y}
5736answers the question ``leave it in symbolic form for non-constant
5737arguments?''
5738
5739@smallexample
5740@group
57411: 1.3495 2: 1.3495 3: 1.3495
5742 . 1: 1.34986 2: 1.34986
5743 . 1: myexp(a + 1)
5744 .
5745
5746 .3 z e .3 E ' a+1 @key{RET} z e
5747@end group
5748@end smallexample
5749
5750@noindent
5751First we call our new @code{exp} approximation with 0.3 as an
5752argument, and compare it with the true @code{exp} function. Then
5753we note that, as requested, if we try to give @kbd{z e} an
5754argument that isn't a plain number, it leaves the @code{myexp}
5755function call in symbolic form. If we had answered @kbd{n} to the
5756final question, @samp{myexp(a + 1)} would have evaluated by plugging
5757in @samp{a + 1} for @samp{x} in the defining formula.
5758
5759@cindex Sine integral Si(x)
5760@ignore
5761@starindex
5762@end ignore
5763@tindex Si
5764(@bullet{}) @strong{Exercise 1.} The ``sine integral'' function
5765@texline @math{{\rm Si}(x)}
40ba43b4 5766@infoline @expr{Si(x)}
4009494e
GM
5767is defined as the integral of @samp{sin(t)/t} for
5768@expr{t = 0} to @expr{x} in radians. (It was invented because this
5769integral has no solution in terms of basic functions; if you give it
5770to Calc's @kbd{a i} command, it will ponder it for a long time and then
5771give up.) We can use the numerical integration command, however,
5772which in algebraic notation is written like @samp{ninteg(f(t), t, 0, x)}
5773with any integrand @samp{f(t)}. Define a @kbd{z s} command and
5774@code{Si} function that implement this. You will need to edit the
5775default argument list a bit. As a test, @samp{Si(1)} should return
57760.946083. (If you don't get this answer, you might want to check that
5777Calc is in Radians mode. Also, @code{ninteg} will run a lot faster if
5778you reduce the precision to, say, six digits beforehand.)
5779@xref{Programming Answer 1, 1}. (@bullet{})
5780
5781The simplest way to do real ``programming'' of Emacs is to define a
5782@dfn{keyboard macro}. A keyboard macro is simply a sequence of
5783keystrokes which Emacs has stored away and can play back on demand.
5784For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
5785you may wish to program a keyboard macro to type this for you.
5786
5787@smallexample
5788@group
57891: y = sqrt(x) 1: x = y^2
5790 . .
5791
5792 ' y=sqrt(x) @key{RET} C-x ( H a S x @key{RET} C-x )
5793
d2bd74ff 57941: y = cos(x) 1: x = s1 arccos(y) + 2 n1 pi
4009494e
GM
5795 . .
5796
5797 ' y=cos(x) @key{RET} X
5798@end group
5799@end smallexample
5800
5801@noindent
5802When you type @kbd{C-x (}, Emacs begins recording. But it is also
5803still ready to execute your keystrokes, so you're really ``training''
5804Emacs by walking it through the procedure once. When you type
5805@w{@kbd{C-x )}}, the macro is recorded. You can now type @kbd{X} to
5806re-execute the same keystrokes.
5807
5808You can give a name to your macro by typing @kbd{Z K}.
5809
5810@smallexample
5811@group
58121: . 1: y = x^4 1: x = s2 sqrt(s1 sqrt(y))
5813 . .
5814
5815 Z K x @key{RET} ' y=x^4 @key{RET} z x
5816@end group
5817@end smallexample
5818
5819@noindent
5820Notice that we use shift-@kbd{Z} to define the command, and lower-case
5821@kbd{z} to call it up.
5822
5823Keyboard macros can call other macros.
5824
5825@smallexample
5826@group
58271: abs(x) 1: x = s1 y 1: 2 / x 1: x = 2 / y
5828 . . . .
5829
5830 ' abs(x) @key{RET} C-x ( ' y @key{RET} a = z x C-x ) ' 2/x @key{RET} X
5831@end group
5832@end smallexample
5833
5834(@bullet{}) @strong{Exercise 2.} Define a keyboard macro to negate
5835the item in level 3 of the stack, without disturbing the rest of
5836the stack. @xref{Programming Answer 2, 2}. (@bullet{})
5837
5838(@bullet{}) @strong{Exercise 3.} Define keyboard macros to compute
5839the following functions:
5840
5841@enumerate
5842@item
40ba43b4 5843Compute
4009494e 5844@texline @math{\displaystyle{\sin x \over x}},
40ba43b4 5845@infoline @expr{sin(x) / x},
4009494e
GM
5846where @expr{x} is the number on the top of the stack.
5847
5848@item
5849Compute the base-@expr{b} logarithm, just like the @kbd{B} key except
5850the arguments are taken in the opposite order.
5851
5852@item
5853Produce a vector of integers from 1 to the integer on the top of
5854the stack.
5855@end enumerate
5856@noindent
5857@xref{Programming Answer 3, 3}. (@bullet{})
5858
5859(@bullet{}) @strong{Exercise 4.} Define a keyboard macro to compute
5860the average (mean) value of a list of numbers.
5861@xref{Programming Answer 4, 4}. (@bullet{})
5862
5863In many programs, some of the steps must execute several times.
5864Calc has @dfn{looping} commands that allow this. Loops are useful
5865inside keyboard macros, but actually work at any time.
5866
5867@smallexample
5868@group
58691: x^6 2: x^6 1: 360 x^2
5870 . 1: 4 .
5871 .
5872
5873 ' x^6 @key{RET} 4 Z < a d x @key{RET} Z >
5874@end group
5875@end smallexample
5876
5877@noindent
5878Here we have computed the fourth derivative of @expr{x^6} by
5879enclosing a derivative command in a ``repeat loop'' structure.
5880This structure pops a repeat count from the stack, then
5881executes the body of the loop that many times.
5882
5883If you make a mistake while entering the body of the loop,
5884type @w{@kbd{Z C-g}} to cancel the loop command.
5885
5886@cindex Fibonacci numbers
5887Here's another example:
5888
5889@smallexample
5890@group
58913: 1 2: 10946
58922: 1 1: 17711
58931: 20 .
5894 .
5895
58961 @key{RET} @key{RET} 20 Z < @key{TAB} C-j + Z >
5897@end group
5898@end smallexample
5899
5900@noindent
5901The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
5902numbers, respectively. (To see what's going on, try a few repetitions
5903of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
5904key if you have one, makes a copy of the number in level 2.)
5905
5906@cindex Golden ratio
5907@cindex Phi, golden ratio
5908A fascinating property of the Fibonacci numbers is that the @expr{n}th
40ba43b4 5909Fibonacci number can be found directly by computing
4009494e
GM
5910@texline @math{\phi^n / \sqrt{5}}
5911@infoline @expr{phi^n / sqrt(5)}
40ba43b4 5912and then rounding to the nearest integer, where
4009494e 5913@texline @math{\phi} (``phi''),
40ba43b4
PE
5914@infoline @expr{phi},
5915the ``golden ratio,'' is
4009494e 5916@texline @math{(1 + \sqrt{5}) / 2}.
40ba43b4 5917@infoline @expr{(1 + sqrt(5)) / 2}.
4009494e
GM
5918(For convenience, this constant is available from the @code{phi}
5919variable, or the @kbd{I H P} command.)
5920
5921@smallexample
5922@group
59231: 1.61803 1: 24476.0000409 1: 10945.9999817 1: 10946
5924 . . . .
5925
5926 I H P 21 ^ 5 Q / R
5927@end group
5928@end smallexample
5929
5930@cindex Continued fractions
5931(@bullet{}) @strong{Exercise 5.} The @dfn{continued fraction}
40ba43b4 5932representation of
4009494e 5933@texline @math{\phi}
40ba43b4
PE
5934@infoline @expr{phi}
5935is
4009494e
GM
5936@texline @math{1 + 1/(1 + 1/(1 + 1/( \ldots )))}.
5937@infoline @expr{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
5938We can compute an approximate value by carrying this however far
40ba43b4 5939and then replacing the innermost
4009494e 5940@texline @math{1/( \ldots )}
40ba43b4 5941@infoline @expr{1/( ...@: )}
4009494e
GM
5942by 1. Approximate
5943@texline @math{\phi}
40ba43b4 5944@infoline @expr{phi}
4009494e
GM
5945using a twenty-term continued fraction.
5946@xref{Programming Answer 5, 5}. (@bullet{})
5947
5948(@bullet{}) @strong{Exercise 6.} Linear recurrences like the one for
5949Fibonacci numbers can be expressed in terms of matrices. Given a
5950vector @w{@expr{[a, b]}} determine a matrix which, when multiplied by this
5951vector, produces the vector @expr{[b, c]}, where @expr{a}, @expr{b} and
5952@expr{c} are three successive Fibonacci numbers. Now write a program
5953that, given an integer @expr{n}, computes the @expr{n}th Fibonacci number
5954using matrix arithmetic. @xref{Programming Answer 6, 6}. (@bullet{})
5955
5956@cindex Harmonic numbers
5957A more sophisticated kind of loop is the @dfn{for} loop. Suppose
5958we wish to compute the 20th ``harmonic'' number, which is equal to
5959the sum of the reciprocals of the integers from 1 to 20.
5960
5961@smallexample
5962@group
59633: 0 1: 3.597739
59642: 1 .
59651: 20
5966 .
5967
59680 @key{RET} 1 @key{RET} 20 Z ( & + 1 Z )
5969@end group
5970@end smallexample
5971
5972@noindent
5973The ``for'' loop pops two numbers, the lower and upper limits, then
5974repeats the body of the loop as an internal counter increases from
5975the lower limit to the upper one. Just before executing the loop
5976body, it pushes the current loop counter. When the loop body
5977finishes, it pops the ``step,'' i.e., the amount by which to
5978increment the loop counter. As you can see, our loop always
5979uses a step of one.
5980
5981This harmonic number function uses the stack to hold the running
5982total as well as for the various loop housekeeping functions. If
5983you find this disorienting, you can sum in a variable instead:
5984
5985@smallexample
5986@group
59871: 0 2: 1 . 1: 3.597739
5988 . 1: 20 .
5989 .
5990
5991 0 t 7 1 @key{RET} 20 Z ( & s + 7 1 Z ) r 7
5992@end group
5993@end smallexample
5994
5995@noindent
5996The @kbd{s +} command adds the top-of-stack into the value in a
5997variable (and removes that value from the stack).
5998
5999It's worth noting that many jobs that call for a ``for'' loop can
6000also be done more easily by Calc's high-level operations. Two
6001other ways to compute harmonic numbers are to use vector mapping
6002and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
6003or to use the summation command @kbd{a +}. Both of these are
6004probably easier than using loops. However, there are some
6005situations where loops really are the way to go:
6006
6007(@bullet{}) @strong{Exercise 7.} Use a ``for'' loop to find the first
6008harmonic number which is greater than 4.0.
6009@xref{Programming Answer 7, 7}. (@bullet{})
6010
6011Of course, if we're going to be using variables in our programs,
6012we have to worry about the programs clobbering values that the
6013caller was keeping in those same variables. This is easy to
6014fix, though:
6015
6016@smallexample
6017@group
6018 . 1: 0.6667 1: 0.6667 3: 0.6667
6019 . . 2: 3.597739
6020 1: 0.6667
6021 .
6022
6023 Z ` p 4 @key{RET} 2 @key{RET} 3 / s 7 s s a @key{RET} Z ' r 7 s r a @key{RET}
6024@end group
6025@end smallexample
6026
6027@noindent
6028When we type @kbd{Z `} (that's a back-quote character), Calc saves
6029its mode settings and the contents of the ten ``quick variables''
6030for later reference. When we type @kbd{Z '} (that's an apostrophe
6031now), Calc restores those saved values. Thus the @kbd{p 4} and
6032@kbd{s 7} commands have no effect outside this sequence. Wrapping
6033this around the body of a keyboard macro ensures that it doesn't
6034interfere with what the user of the macro was doing. Notice that
6035the contents of the stack, and the values of named variables,
6036survive past the @kbd{Z '} command.
6037
6038@cindex Bernoulli numbers, approximate
6039The @dfn{Bernoulli numbers} are a sequence with the interesting
6040property that all of the odd Bernoulli numbers are zero, and the
6041even ones, while difficult to compute, can be roughly approximated
40ba43b4 6042by the formula
4009494e 6043@texline @math{\displaystyle{2 n! \over (2 \pi)^n}}.
40ba43b4 6044@infoline @expr{2 n!@: / (2 pi)^n}.
4009494e
GM
6045Let's write a keyboard macro to compute (approximate) Bernoulli numbers.
6046(Calc has a command, @kbd{k b}, to compute exact Bernoulli numbers, but
6047this command is very slow for large @expr{n} since the higher Bernoulli
6048numbers are very large fractions.)
6049
6050@smallexample
6051@group
60521: 10 1: 0.0756823
6053 . .
6054
6055 10 C-x ( @key{RET} 2 % Z [ @key{DEL} 0 Z : ' 2 $! / (2 pi)^$ @key{RET} = Z ] C-x )
6056@end group
6057@end smallexample
6058
6059@noindent
6060You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
6061@kbd{Z ]} as ``end-if.'' There is no need for an explicit ``if''
6062command. For the purposes of @w{@kbd{Z [}}, the condition is ``true''
6063if the value it pops from the stack is a nonzero number, or ``false''
6064if it pops zero or something that is not a number (like a formula).
6065Here we take our integer argument modulo 2; this will be nonzero
6066if we're asking for an odd Bernoulli number.
6067
6068The actual tenth Bernoulli number is @expr{5/66}.
6069
6070@smallexample
6071@group
60723: 0.0756823 1: 0 1: 0.25305 1: 0 1: 1.16659
60732: 5:66 . . . .
60741: 0.0757575
6075 .
6076
607710 k b @key{RET} c f M-0 @key{DEL} 11 X @key{DEL} 12 X @key{DEL} 13 X @key{DEL} 14 X
6078@end group
6079@end smallexample
6080
6081Just to exercise loops a bit more, let's compute a table of even
6082Bernoulli numbers.
6083
6084@smallexample
6085@group
60863: [] 1: [0.10132, 0.03079, 0.02340, 0.033197, ...]
60872: 2 .
60881: 30
6089 .
6090
6091 [ ] 2 @key{RET} 30 Z ( X | 2 Z )
6092@end group
6093@end smallexample
6094
6095@noindent
6096The vertical-bar @kbd{|} is the vector-concatenation command. When
6097we execute it, the list we are building will be in stack level 2
6098(initially this is an empty list), and the next Bernoulli number
6099will be in level 1. The effect is to append the Bernoulli number
6100onto the end of the list. (To create a table of exact fractional
6101Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
6102sequence of keystrokes.)
6103
6104With loops and conditionals, you can program essentially anything
6105in Calc. One other command that makes looping easier is @kbd{Z /},
6106which takes a condition from the stack and breaks out of the enclosing
6107loop if the condition is true (non-zero). You can use this to make
6108``while'' and ``until'' style loops.
6109
6110If you make a mistake when entering a keyboard macro, you can edit
6111it using @kbd{Z E}. First, you must attach it to a key with @kbd{Z K}.
6112One technique is to enter a throwaway dummy definition for the macro,
6113then enter the real one in the edit command.
6114
6115@smallexample
6116@group
61171: 3 1: 3 Calc Macro Edit Mode.
6118 . . Original keys: 1 <return> 2 +
6119
6120 1 ;; calc digits
6121 RET ;; calc-enter
6122 2 ;; calc digits
6123 + ;; calc-plus
6124
6125C-x ( 1 @key{RET} 2 + C-x ) Z K h @key{RET} Z E h
6126@end group
6127@end smallexample
6128
6129@noindent
6130A keyboard macro is stored as a pure keystroke sequence. The
6131@file{edmacro} package (invoked by @kbd{Z E}) scans along the
6132macro and tries to decode it back into human-readable steps.
6133Descriptions of the keystrokes are given as comments, which begin with
6134@samp{;;}, and which are ignored when the edited macro is saved.
6135Spaces and line breaks are also ignored when the edited macro is saved.
6136To enter a space into the macro, type @code{SPC}. All the special
6137characters @code{RET}, @code{LFD}, @code{TAB}, @code{SPC}, @code{DEL},
6138and @code{NUL} must be written in all uppercase, as must the prefixes
6139@code{C-} and @code{M-}.
6140
6141Let's edit in a new definition, for computing harmonic numbers.
6142First, erase the four lines of the old definition. Then, type
6143in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
6144to copy it from this page of the Info file; you can of course skip
6145typing the comments, which begin with @samp{;;}).
6146
6147@smallexample
6148Z` ;; calc-kbd-push (Save local values)
61490 ;; calc digits (Push a zero onto the stack)
6150st ;; calc-store-into (Store it in the following variable)
61511 ;; calc quick variable (Quick variable q1)
40ba43b4 61521 ;; calc digits (Initial value for the loop)
4009494e
GM
6153TAB ;; calc-roll-down (Swap initial and final)
6154Z( ;; calc-kbd-for (Begin the "for" loop)
6155& ;; calc-inv (Take the reciprocal)
6156s+ ;; calc-store-plus (Add to the following variable)
61571 ;; calc quick variable (Quick variable q1)
61581 ;; calc digits (The loop step is 1)
6159Z) ;; calc-kbd-end-for (End the "for" loop)
6160sr ;; calc-recall (Recall the final accumulated value)
61611 ;; calc quick variable (Quick variable q1)
6162Z' ;; calc-kbd-pop (Restore values)
6163@end smallexample
6164
6165@noindent
6166Press @kbd{C-c C-c} to finish editing and return to the Calculator.
6167
6168@smallexample
6169@group
61701: 20 1: 3.597739
6171 . .
6172
6173 20 z h
6174@end group
6175@end smallexample
6176
6177The @file{edmacro} package defines a handy @code{read-kbd-macro} command
6178which reads the current region of the current buffer as a sequence of
40ba43b4 6179keystroke names, and defines that sequence on the @kbd{X}
4009494e
GM
6180(and @kbd{C-x e}) key. Because this is so useful, Calc puts this
6181command on the @kbd{C-x * m} key. Try reading in this macro in the
40ba43b4 6182following form: Press @kbd{C-@@} (or @kbd{C-@key{SPC}}) at
4009494e
GM
6183one end of the text below, then type @kbd{C-x * m} at the other.
6184
6185@example
6186@group
6187Z ` 0 t 1
6188 1 TAB
6189 Z ( & s + 1 1 Z )
6190 r 1
6191Z '
6192@end group
6193@end example
6194
6195(@bullet{}) @strong{Exercise 8.} A general algorithm for solving
6196equations numerically is @dfn{Newton's Method}. Given the equation
6197@expr{f(x) = 0} for any function @expr{f}, and an initial guess
6198@expr{x_0} which is reasonably close to the desired solution, apply
6199this formula over and over:
6200
6201@ifnottex
6202@example
6203new_x = x - f(x)/f'(x)
6204@end example
6205@end ifnottex
6206@tex
6207\beforedisplay
db37d257 6208$$ x_{\rm new} = x - {f(x) \over f^{\prime}(x)} $$
4009494e
GM
6209\afterdisplay
6210@end tex
6211
6212@noindent
6213where @expr{f'(x)} is the derivative of @expr{f}. The @expr{x}
6214values will quickly converge to a solution, i.e., eventually
6215@texline @math{x_{\rm new}}
40ba43b4 6216@infoline @expr{new_x}
4009494e
GM
6217and @expr{x} will be equal to within the limits
6218of the current precision. Write a program which takes a formula
6219involving the variable @expr{x}, and an initial guess @expr{x_0},
6220on the stack, and produces a value of @expr{x} for which the formula
40ba43b4 6221is zero. Use it to find a solution of
4009494e
GM
6222@texline @math{\sin(\cos x) = 0.5}
6223@infoline @expr{sin(cos(x)) = 0.5}
6224near @expr{x = 4.5}. (Use angles measured in radians.) Note that
6225the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
6226method when it is able. @xref{Programming Answer 8, 8}. (@bullet{})
6227
6228@cindex Digamma function
6229@cindex Gamma constant, Euler's
6230@cindex Euler's gamma constant
40ba43b4 6231(@bullet{}) @strong{Exercise 9.} The @dfn{digamma} function
4009494e
GM
6232@texline @math{\psi(z) (``psi'')}
6233@infoline @expr{psi(z)}
40ba43b4 6234is defined as the derivative of
4009494e 6235@texline @math{\ln \Gamma(z)}.
40ba43b4 6236@infoline @expr{ln(gamma(z))}.
4009494e
GM
6237For large values of @expr{z}, it can be approximated by the infinite sum
6238
6239@ifnottex
6240@example
6241psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
6242@end example
6243@end ifnottex
6244@tex
6245\beforedisplay
6246$$ \psi(z) \approx \ln z - {1\over2z} -
6247 \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
6248$$
6249\afterdisplay
6250@end tex
6251
6252@noindent
40ba43b4 6253where
4009494e 6254@texline @math{\sum}
40ba43b4 6255@infoline @expr{sum}
4009494e
GM
6256represents the sum over @expr{n} from 1 to infinity
6257(or to some limit high enough to give the desired accuracy), and
6258the @code{bern} function produces (exact) Bernoulli numbers.
6259While this sum is not guaranteed to converge, in practice it is safe.
6260An interesting mathematical constant is Euler's gamma, which is equal
6261to about 0.5772. One way to compute it is by the formula,
6262@texline @math{\gamma = -\psi(1)}.
40ba43b4 6263@infoline @expr{gamma = -psi(1)}.
4009494e
GM
6264Unfortunately, 1 isn't a large enough argument
6265for the above formula to work (5 is a much safer value for @expr{z}).
40ba43b4 6266Fortunately, we can compute
4009494e 6267@texline @math{\psi(1)}
40ba43b4
PE
6268@infoline @expr{psi(1)}
6269from
4009494e 6270@texline @math{\psi(5)}
40ba43b4
PE
6271@infoline @expr{psi(5)}
6272using the recurrence
4009494e 6273@texline @math{\psi(z+1) = \psi(z) + {1 \over z}}.
40ba43b4
PE
6274@infoline @expr{psi(z+1) = psi(z) + 1/z}.
6275Your task: Develop a program to compute
4009494e 6276@texline @math{\psi(z)};
40ba43b4 6277@infoline @expr{psi(z)};
4009494e
GM
6278it should ``pump up'' @expr{z}
6279if necessary to be greater than 5, then use the above summation
6280formula. Use looping commands to compute the sum. Use your function
40ba43b4 6281to compute
4009494e 6282@texline @math{\gamma}
40ba43b4 6283@infoline @expr{gamma}
4009494e
GM
6284to twelve decimal places. (Calc has a built-in command
6285for Euler's constant, @kbd{I P}, which you can use to check your answer.)
6286@xref{Programming Answer 9, 9}. (@bullet{})
6287
6288@cindex Polynomial, list of coefficients
6289(@bullet{}) @strong{Exercise 10.} Given a polynomial in @expr{x} and
6290a number @expr{m} on the stack, where the polynomial is of degree
6291@expr{m} or less (i.e., does not have any terms higher than @expr{x^m}),
6292write a program to convert the polynomial into a list-of-coefficients
6293notation. For example, @expr{5 x^4 + (x + 1)^2} with @expr{m = 6}
6294should produce the list @expr{[1, 2, 1, 0, 5, 0, 0]}. Also develop
6295a way to convert from this form back to the standard algebraic form.
6296@xref{Programming Answer 10, 10}. (@bullet{})
6297
6298@cindex Recursion
6299(@bullet{}) @strong{Exercise 11.} The @dfn{Stirling numbers of the
6300first kind} are defined by the recurrences,
6301
6302@ifnottex
6303@example
6304s(n,n) = 1 for n >= 0,
6305s(n,0) = 0 for n > 0,
6306s(n+1,m) = s(n,m-1) - n s(n,m) for n >= m >= 1.
6307@end example
6308@end ifnottex
6309@tex
4009494e
GM
6310\beforedisplay
6311$$ \eqalign{ s(n,n) &= 1 \qquad \hbox{for } n \ge 0, \cr
6312 s(n,0) &= 0 \qquad \hbox{for } n > 0, \cr
6313 s(n+1,m) &= s(n,m-1) - n \, s(n,m) \qquad
6314 \hbox{for } n \ge m \ge 1.}
6315$$
6316\afterdisplay
6317\vskip5pt
6318(These numbers are also sometimes written $\displaystyle{n \brack m}$.)
6319@end tex
6320
6321This can be implemented using a @dfn{recursive} program in Calc; the
6322program must invoke itself in order to calculate the two righthand
6323terms in the general formula. Since it always invokes itself with
6324``simpler'' arguments, it's easy to see that it must eventually finish
6325the computation. Recursion is a little difficult with Emacs keyboard
6326macros since the macro is executed before its definition is complete.
6327So here's the recommended strategy: Create a ``dummy macro'' and assign
6328it to a key with, e.g., @kbd{Z K s}. Now enter the true definition,
6329using the @kbd{z s} command to call itself recursively, then assign it
6330to the same key with @kbd{Z K s}. Now the @kbd{z s} command will run
6331the complete recursive program. (Another way is to use @w{@kbd{Z E}}
6332or @kbd{C-x * m} (@code{read-kbd-macro}) to read the whole macro at once,
6333thus avoiding the ``training'' phase.) The task: Write a program
6334that computes Stirling numbers of the first kind, given @expr{n} and
6335@expr{m} on the stack. Test it with @emph{small} inputs like
6336@expr{s(4,2)}. (There is a built-in command for Stirling numbers,
6337@kbd{k s}, which you can use to check your answers.)
6338@xref{Programming Answer 11, 11}. (@bullet{})
6339
6340The programming commands we've seen in this part of the tutorial
6341are low-level, general-purpose operations. Often you will find
6342that a higher-level function, such as vector mapping or rewrite
6343rules, will do the job much more easily than a detailed, step-by-step
6344program can:
6345
6346(@bullet{}) @strong{Exercise 12.} Write another program for
6347computing Stirling numbers of the first kind, this time using
6348rewrite rules. Once again, @expr{n} and @expr{m} should be taken
6349from the stack. @xref{Programming Answer 12, 12}. (@bullet{})
6350
6351@example
6352
6353@end example
6354This ends the tutorial section of the Calc manual. Now you know enough
6355about Calc to use it effectively for many kinds of calculations. But
6356Calc has many features that were not even touched upon in this tutorial.
6357@c [not-split]
6358The rest of this manual tells the whole story.
6359@c [when-split]
6360@c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
6361
6362@page
6363@node Answers to Exercises, , Programming Tutorial, Tutorial
6364@section Answers to Exercises
6365
6366@noindent
6367This section includes answers to all the exercises in the Calc tutorial.
6368
6369@menu
6370* RPN Answer 1:: 1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -
6371* RPN Answer 2:: 2*4 + 7*9.5 + 5/4
6372* RPN Answer 3:: Operating on levels 2 and 3
6373* RPN Answer 4:: Joe's complex problems
6374* Algebraic Answer 1:: Simulating Q command
6375* Algebraic Answer 2:: Joe's algebraic woes
6376* Algebraic Answer 3:: 1 / 0
6377* Modes Answer 1:: 3#0.1 = 3#0.0222222?
6378* Modes Answer 2:: 16#f.e8fe15
6379* Modes Answer 3:: Joe's rounding bug
6380* Modes Answer 4:: Why floating point?
6381* Arithmetic Answer 1:: Why the \ command?
6382* Arithmetic Answer 2:: Tripping up the B command
6383* Vector Answer 1:: Normalizing a vector
6384* Vector Answer 2:: Average position
6385* Matrix Answer 1:: Row and column sums
6386* Matrix Answer 2:: Symbolic system of equations
6387* Matrix Answer 3:: Over-determined system
6388* List Answer 1:: Powers of two
6389* List Answer 2:: Least-squares fit with matrices
6390* List Answer 3:: Geometric mean
6391* List Answer 4:: Divisor function
6392* List Answer 5:: Duplicate factors
6393* List Answer 6:: Triangular list
6394* List Answer 7:: Another triangular list
6395* List Answer 8:: Maximum of Bessel function
6396* List Answer 9:: Integers the hard way
6397* List Answer 10:: All elements equal
6398* List Answer 11:: Estimating pi with darts
6399* List Answer 12:: Estimating pi with matchsticks
6400* List Answer 13:: Hash codes
6401* List Answer 14:: Random walk
6402* Types Answer 1:: Square root of pi times rational
6403* Types Answer 2:: Infinities
6404* Types Answer 3:: What can "nan" be?
6405* Types Answer 4:: Abbey Road
6406* Types Answer 5:: Friday the 13th
6407* Types Answer 6:: Leap years
6408* Types Answer 7:: Erroneous donut
6409* Types Answer 8:: Dividing intervals
6410* Types Answer 9:: Squaring intervals
6411* Types Answer 10:: Fermat's primality test
6412* Types Answer 11:: pi * 10^7 seconds
6413* Types Answer 12:: Abbey Road on CD
6414* Types Answer 13:: Not quite pi * 10^7 seconds
6415* Types Answer 14:: Supercomputers and c
6416* Types Answer 15:: Sam the Slug
6417* Algebra Answer 1:: Squares and square roots
6418* Algebra Answer 2:: Building polynomial from roots
6419* Algebra Answer 3:: Integral of x sin(pi x)
6420* Algebra Answer 4:: Simpson's rule
6421* Rewrites Answer 1:: Multiplying by conjugate
6422* Rewrites Answer 2:: Alternative fib rule
6423* Rewrites Answer 3:: Rewriting opt(a) + opt(b) x
6424* Rewrites Answer 4:: Sequence of integers
6425* Rewrites Answer 5:: Number of terms in sum
6426* Rewrites Answer 6:: Truncated Taylor series
6427* Programming Answer 1:: Fresnel's C(x)
6428* Programming Answer 2:: Negate third stack element
6429* Programming Answer 3:: Compute sin(x) / x, etc.
6430* Programming Answer 4:: Average value of a list
6431* Programming Answer 5:: Continued fraction phi
6432* Programming Answer 6:: Matrix Fibonacci numbers
6433* Programming Answer 7:: Harmonic number greater than 4
6434* Programming Answer 8:: Newton's method
6435* Programming Answer 9:: Digamma function
6436* Programming Answer 10:: Unpacking a polynomial
6437* Programming Answer 11:: Recursive Stirling numbers
6438* Programming Answer 12:: Stirling numbers with rewrites
6439@end menu
6440
6441@c The following kludgery prevents the individual answers from
6442@c being entered on the table of contents.
6443@tex
6444\global\let\oldwrite=\write
6445\gdef\skipwrite#1#2{\let\write=\oldwrite}
6446\global\let\oldchapternofonts=\chapternofonts
6447\gdef\chapternofonts{\let\write=\skipwrite\oldchapternofonts}
6448@end tex
6449
6450@node RPN Answer 1, RPN Answer 2, Answers to Exercises, Answers to Exercises
6451@subsection RPN Tutorial Exercise 1
6452
6453@noindent
6454@kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -}
6455
40ba43b4 6456The result is
4009494e
GM
6457@texline @math{1 - (2 \times (3 + 4)) = -13}.
6458@infoline @expr{1 - (2 * (3 + 4)) = -13}.
6459
6460@node RPN Answer 2, RPN Answer 3, RPN Answer 1, Answers to Exercises
6461@subsection RPN Tutorial Exercise 2
6462
6463@noindent
6464@texline @math{2\times4 + 7\times9.5 + {5\over4} = 75.75}
6465@infoline @expr{2*4 + 7*9.5 + 5/4 = 75.75}
6466
40ba43b4 6467After computing the intermediate term
4009494e 6468@texline @math{2\times4 = 8},
40ba43b4 6469@infoline @expr{2*4 = 8},
4009494e
GM
6470you can leave that result on the stack while you compute the second
6471term. With both of these results waiting on the stack you can then
6472compute the final term, then press @kbd{+ +} to add everything up.
6473
6474@smallexample
6475@group
64762: 2 1: 8 3: 8 2: 8
64771: 4 . 2: 7 1: 66.5
6478 . 1: 9.5 .
6479 .
6480
6481 2 @key{RET} 4 * 7 @key{RET} 9.5 *
6482
6483@end group
6484@end smallexample
6485@noindent
6486@smallexample
6487@group
64884: 8 3: 8 2: 8 1: 75.75
64893: 66.5 2: 66.5 1: 67.75 .
64902: 5 1: 1.25 .
64911: 4 .
6492 .
6493
6494 5 @key{RET} 4 / + +
6495@end group
6496@end smallexample
6497
6498Alternatively, you could add the first two terms before going on
6499with the third term.
6500
6501@smallexample
6502@group
65032: 8 1: 74.5 3: 74.5 2: 74.5 1: 75.75
65041: 66.5 . 2: 5 1: 1.25 .
6505 . 1: 4 .
6506 .
6507
6508 ... + 5 @key{RET} 4 / +
6509@end group
6510@end smallexample
6511
6512On an old-style RPN calculator this second method would have the
6513advantage of using only three stack levels. But since Calc's stack
6514can grow arbitrarily large this isn't really an issue. Which method
6515you choose is purely a matter of taste.
6516
6517@node RPN Answer 3, RPN Answer 4, RPN Answer 2, Answers to Exercises
6518@subsection RPN Tutorial Exercise 3
6519
6520@noindent
6521The @key{TAB} key provides a way to operate on the number in level 2.
6522
6523@smallexample
6524@group
65253: 10 3: 10 4: 10 3: 10 3: 10
65262: 20 2: 30 3: 30 2: 30 2: 21
65271: 30 1: 20 2: 20 1: 21 1: 30
6528 . . 1: 1 . .
6529 .
6530
6531 @key{TAB} 1 + @key{TAB}
6532@end group
6533@end smallexample
6534
6535Similarly, @kbd{M-@key{TAB}} gives you access to the number in level 3.
6536
6537@smallexample
6538@group
65393: 10 3: 21 3: 21 3: 30 3: 11
65402: 21 2: 30 2: 30 2: 11 2: 21
65411: 30 1: 10 1: 11 1: 21 1: 30
6542 . . . . .
6543
6544 M-@key{TAB} 1 + M-@key{TAB} M-@key{TAB}
6545@end group
6546@end smallexample
6547
6548@node RPN Answer 4, Algebraic Answer 1, RPN Answer 3, Answers to Exercises
6549@subsection RPN Tutorial Exercise 4
6550
6551@noindent
6552Either @kbd{( 2 , 3 )} or @kbd{( 2 @key{SPC} 3 )} would have worked,
6553but using both the comma and the space at once yields:
6554
6555@smallexample
6556@group
65571: ( ... 2: ( ... 1: (2, ... 2: (2, ... 2: (2, ...
6558 . 1: 2 . 1: (2, ... 1: (2, 3)
6559 . . .
6560
6561 ( 2 , @key{SPC} 3 )
6562@end group
6563@end smallexample
6564
6565Joe probably tried to type @kbd{@key{TAB} @key{DEL}} to swap the
6566extra incomplete object to the top of the stack and delete it.
6567But a feature of Calc is that @key{DEL} on an incomplete object
6568deletes just one component out of that object, so he had to press
6569@key{DEL} twice to finish the job.
6570
6571@smallexample
6572@group
65732: (2, ... 2: (2, 3) 2: (2, 3) 1: (2, 3)
65741: (2, 3) 1: (2, ... 1: ( ... .
6575 . . .
6576
6577 @key{TAB} @key{DEL} @key{DEL}
6578@end group
6579@end smallexample
6580
6581(As it turns out, deleting the second-to-top stack entry happens often
6582enough that Calc provides a special key, @kbd{M-@key{DEL}}, to do just that.
6583@kbd{M-@key{DEL}} is just like @kbd{@key{TAB} @key{DEL}}, except that it doesn't exhibit
6584the ``feature'' that tripped poor Joe.)
6585
6586@node Algebraic Answer 1, Algebraic Answer 2, RPN Answer 4, Answers to Exercises
6587@subsection Algebraic Entry Tutorial Exercise 1
6588
6589@noindent
6590Type @kbd{' sqrt($) @key{RET}}.
6591
6592If the @kbd{Q} key is broken, you could use @kbd{' $^0.5 @key{RET}}.
6593Or, RPN style, @kbd{0.5 ^}.
6594
6595(Actually, @samp{$^1:2}, using the fraction one-half as the power, is
6596a closer equivalent, since @samp{9^0.5} yields @expr{3.0} whereas
6597@samp{sqrt(9)} and @samp{9^1:2} yield the exact integer @expr{3}.)
6598
6599@node Algebraic Answer 2, Algebraic Answer 3, Algebraic Answer 1, Answers to Exercises
6600@subsection Algebraic Entry Tutorial Exercise 2
6601
6602@noindent
6603In the formula @samp{2 x (1+y)}, @samp{x} was interpreted as a function
6604name with @samp{1+y} as its argument. Assigning a value to a variable
6605has no relation to a function by the same name. Joe needed to use an
6606explicit @samp{*} symbol here: @samp{2 x*(1+y)}.
6607
6608@node Algebraic Answer 3, Modes Answer 1, Algebraic Answer 2, Answers to Exercises
6609@subsection Algebraic Entry Tutorial Exercise 3
6610
6611@noindent
6612The result from @kbd{1 @key{RET} 0 /} will be the formula @expr{1 / 0}.
6613The ``function'' @samp{/} cannot be evaluated when its second argument
6614is zero, so it is left in symbolic form. When you now type @kbd{0 *},
6615the result will be zero because Calc uses the general rule that ``zero
6616times anything is zero.''
6617
6618@c [fix-ref Infinities]
6619The @kbd{m i} command enables an @dfn{Infinite mode} in which @expr{1 / 0}
6620results in a special symbol that represents ``infinity.'' If you
6621multiply infinity by zero, Calc uses another special new symbol to
6622show that the answer is ``indeterminate.'' @xref{Infinities}, for
6623further discussion of infinite and indeterminate values.
6624
6625@node Modes Answer 1, Modes Answer 2, Algebraic Answer 3, Answers to Exercises
6626@subsection Modes Tutorial Exercise 1
6627
6628@noindent
6629Calc always stores its numbers in decimal, so even though one-third has
6630an exact base-3 representation (@samp{3#0.1}), it is still stored as
66310.3333333 (chopped off after 12 or however many decimal digits) inside
6632the calculator's memory. When this inexact number is converted back
6633to base 3 for display, it may still be slightly inexact. When we
6634multiply this number by 3, we get 0.999999, also an inexact value.
6635
6636When Calc displays a number in base 3, it has to decide how many digits
6637to show. If the current precision is 12 (decimal) digits, that corresponds
6638to @samp{12 / log10(3) = 25.15} base-3 digits. Because 25.15 is not an
6639exact integer, Calc shows only 25 digits, with the result that stored
6640numbers carry a little bit of extra information that may not show up on
6641the screen. When Joe entered @samp{3#0.2}, the stored number 0.666666
6642happened to round to a pleasing value when it lost that last 0.15 of a
6643digit, but it was still inexact in Calc's memory. When he divided by 2,
6644he still got the dreaded inexact value 0.333333. (Actually, he divided
66450.666667 by 2 to get 0.333334, which is why he got something a little
6646higher than @code{3#0.1} instead of a little lower.)
6647
6648If Joe didn't want to be bothered with all this, he could have typed
6649@kbd{M-24 d n} to display with one less digit than the default. (If
6650you give @kbd{d n} a negative argument, it uses default-minus-that,
6651so @kbd{M-- d n} would be an easier way to get the same effect.) Those
6652inexact results would still be lurking there, but they would now be
6653rounded to nice, natural-looking values for display purposes. (Remember,
6654@samp{0.022222} in base 3 is like @samp{0.099999} in base 10; rounding
6655off one digit will round the number up to @samp{0.1}.) Depending on the
6656nature of your work, this hiding of the inexactness may be a benefit or
6657a danger. With the @kbd{d n} command, Calc gives you the choice.
6658
6659Incidentally, another consequence of all this is that if you type
6660@kbd{M-30 d n} to display more digits than are ``really there,''
6661you'll see garbage digits at the end of the number. (In decimal
6662display mode, with decimally-stored numbers, these garbage digits are
6663always zero so they vanish and you don't notice them.) Because Calc
6664rounds off that 0.15 digit, there is the danger that two numbers could
6665be slightly different internally but still look the same. If you feel
6666uneasy about this, set the @kbd{d n} precision to be a little higher
6667than normal; you'll get ugly garbage digits, but you'll always be able
6668to tell two distinct numbers apart.
6669
6670An interesting side note is that most computers store their
6671floating-point numbers in binary, and convert to decimal for display.
6672Thus everyday programs have the same problem: Decimal 0.1 cannot be
6673represented exactly in binary (try it: @kbd{0.1 d 2}), so @samp{0.1 * 10}
6674comes out as an inexact approximation to 1 on some machines (though
6675they generally arrange to hide it from you by rounding off one digit as
6676we did above). Because Calc works in decimal instead of binary, you can
6677be sure that numbers that look exact @emph{are} exact as long as you stay
6678in decimal display mode.
6679
6680It's not hard to show that any number that can be represented exactly
6681in binary, octal, or hexadecimal is also exact in decimal, so the kinds
6682of problems we saw in this exercise are likely to be severe only when
6683you use a relatively unusual radix like 3.
6684
6685@node Modes Answer 2, Modes Answer 3, Modes Answer 1, Answers to Exercises
6686@subsection Modes Tutorial Exercise 2
6687
6688If the radix is 15 or higher, we can't use the letter @samp{e} to mark
6689the exponent because @samp{e} is interpreted as a digit. When Calc
6690needs to display scientific notation in a high radix, it writes
6691@samp{16#F.E8F*16.^15}. You can enter a number like this as an
6692algebraic entry. Also, pressing @kbd{e} without any digits before it
6693normally types @kbd{1e}, but in a high radix it types @kbd{16.^} and
6694puts you in algebraic entry: @kbd{16#f.e8f @key{RET} e 15 @key{RET} *} is another
6695way to enter this number.
6696
6697The reason Calc puts a decimal point in the @samp{16.^} is to prevent
6698huge integers from being generated if the exponent is large (consider
6699@samp{16#1.23*16^1000}, where we compute @samp{16^1000} as a giant
6700exact integer and then throw away most of the digits when we multiply
6701it by the floating-point @samp{16#1.23}). While this wouldn't normally
6702matter for display purposes, it could give you a nasty surprise if you
6703copied that number into a file and later moved it back into Calc.
6704
6705@node Modes Answer 3, Modes Answer 4, Modes Answer 2, Answers to Exercises
6706@subsection Modes Tutorial Exercise 3
6707
6708@noindent
6709The answer he got was @expr{0.5000000000006399}.
6710
6711The problem is not that the square operation is inexact, but that the
6712sine of 45 that was already on the stack was accurate to only 12 places.
6713Arbitrary-precision calculations still only give answers as good as
6714their inputs.
6715
6716The real problem is that there is no 12-digit number which, when
6717squared, comes out to 0.5 exactly. The @kbd{f [} and @kbd{f ]}
6718commands decrease or increase a number by one unit in the last
6719place (according to the current precision). They are useful for
6720determining facts like this.
6721
6722@smallexample
6723@group
67241: 0.707106781187 1: 0.500000000001
6725 . .
6726
6727 45 S 2 ^
6728
6729@end group
6730@end smallexample
6731@noindent
6732@smallexample
6733@group
67341: 0.707106781187 1: 0.707106781186 1: 0.499999999999
6735 . . .
6736
6737 U @key{DEL} f [ 2 ^
6738@end group
6739@end smallexample
6740
6741A high-precision calculation must be carried out in high precision
6742all the way. The only number in the original problem which was known
6743exactly was the quantity 45 degrees, so the precision must be raised
6744before anything is done after the number 45 has been entered in order
6745for the higher precision to be meaningful.
6746
6747@node Modes Answer 4, Arithmetic Answer 1, Modes Answer 3, Answers to Exercises
6748@subsection Modes Tutorial Exercise 4
6749
6750@noindent
6751Many calculations involve real-world quantities, like the width and
6752height of a piece of wood or the volume of a jar. Such quantities
6753can't be measured exactly anyway, and if the data that is input to
6754a calculation is inexact, doing exact arithmetic on it is a waste
6755of time.
6756
6757Fractions become unwieldy after too many calculations have been
6758done with them. For example, the sum of the reciprocals of the
6759integers from 1 to 10 is 7381:2520. The sum from 1 to 30 is
67609304682830147:2329089562800. After a point it will take a long
6761time to add even one more term to this sum, but a floating-point
6762calculation of the sum will not have this problem.
6763
6764Also, rational numbers cannot express the results of all calculations.
6765There is no fractional form for the square root of two, so if you type
6766@w{@kbd{2 Q}}, Calc has no choice but to give you a floating-point answer.
6767
6768@node Arithmetic Answer 1, Arithmetic Answer 2, Modes Answer 4, Answers to Exercises
6769@subsection Arithmetic Tutorial Exercise 1
6770
6771@noindent
6772Dividing two integers that are larger than the current precision may
6773give a floating-point result that is inaccurate even when rounded
6774down to an integer. Consider @expr{123456789 / 2} when the current
6775precision is 6 digits. The true answer is @expr{61728394.5}, but
40ba43b4 6776with a precision of 6 this will be rounded to
4009494e
GM
6777@texline @math{12345700.0/2.0 = 61728500.0}.
6778@infoline @expr{12345700.@: / 2.@: = 61728500.}.
6779The result, when converted to an integer, will be off by 106.
6780
6781Here are two solutions: Raise the precision enough that the
6782floating-point round-off error is strictly to the right of the
6783decimal point. Or, convert to Fraction mode so that @expr{123456789 / 2}
6784produces the exact fraction @expr{123456789:2}, which can be rounded
6785down by the @kbd{F} command without ever switching to floating-point
6786format.
6787
6788@node Arithmetic Answer 2, Vector Answer 1, Arithmetic Answer 1, Answers to Exercises
6789@subsection Arithmetic Tutorial Exercise 2
6790
6791@noindent
6792@kbd{27 @key{RET} 9 B} could give the exact result @expr{3:2}, but it
6793does a floating-point calculation instead and produces @expr{1.5}.
6794
6795Calc will find an exact result for a logarithm if the result is an integer
6796or (when in Fraction mode) the reciprocal of an integer. But there is
6797no efficient way to search the space of all possible rational numbers
6798for an exact answer, so Calc doesn't try.
6799
6800@node Vector Answer 1, Vector Answer 2, Arithmetic Answer 2, Answers to Exercises
6801@subsection Vector Tutorial Exercise 1
6802
6803@noindent
6804Duplicate the vector, compute its length, then divide the vector
6805by its length: @kbd{@key{RET} A /}.
6806
6807@smallexample
6808@group
68091: [1, 2, 3] 2: [1, 2, 3] 1: [0.27, 0.53, 0.80] 1: 1.
6810 . 1: 3.74165738677 . .
6811 .
6812
6813 r 1 @key{RET} A / A
6814@end group
6815@end smallexample
6816
6817The final @kbd{A} command shows that the normalized vector does
6818indeed have unit length.
6819
6820@node Vector Answer 2, Matrix Answer 1, Vector Answer 1, Answers to Exercises
6821@subsection Vector Tutorial Exercise 2
6822
6823@noindent
6824The average position is equal to the sum of the products of the
6825positions times their corresponding probabilities. This is the
6826definition of the dot product operation. So all you need to do
6827is to put the two vectors on the stack and press @kbd{*}.
6828
6829@node Matrix Answer 1, Matrix Answer 2, Vector Answer 2, Answers to Exercises
6830@subsection Matrix Tutorial Exercise 1
6831
6832@noindent
6833The trick is to multiply by a vector of ones. Use @kbd{r 4 [1 1 1] *} to
6834get the row sum. Similarly, use @kbd{[1 1] r 4 *} to get the column sum.
6835
6836@node Matrix Answer 2, Matrix Answer 3, Matrix Answer 1, Answers to Exercises
6837@subsection Matrix Tutorial Exercise 2
6838
6839@ifnottex
6840@example
6841@group
6842 x + a y = 6
6843 x + b y = 10
6844@end group
6845@end example
6846@end ifnottex
6847@tex
4009494e
GM
6848\beforedisplay
6849$$ \eqalign{ x &+ a y = 6 \cr
6850 x &+ b y = 10}
6851$$
6852\afterdisplay
6853@end tex
6854
6855Just enter the righthand side vector, then divide by the lefthand side
6856matrix as usual.
6857
6858@smallexample
6859@group
d2bd74ff 68601: [6, 10] 2: [6, 10] 1: [4 a / (a - b) + 6, 4 / (b - a) ]
4009494e
GM
6861 . 1: [ [ 1, a ] .
6862 [ 1, b ] ]
6863 .
6864
6865' [6 10] @key{RET} ' [1 a; 1 b] @key{RET} /
6866@end group
6867@end smallexample
6868
6869This can be made more readable using @kbd{d B} to enable Big display
6870mode:
6871
6872@smallexample
6873@group
d2bd74ff
JB
6874 4 a 4
68751: [----- + 6, -----]
6876 a - b b - a
4009494e
GM
6877@end group
6878@end smallexample
6879
6880Type @kbd{d N} to return to Normal display mode afterwards.
6881
6882@node Matrix Answer 3, List Answer 1, Matrix Answer 2, Answers to Exercises
6883@subsection Matrix Tutorial Exercise 3
6884
6885@noindent
40ba43b4 6886To solve
4009494e 6887@texline @math{A^T A \, X = A^T B},
40ba43b4 6888@infoline @expr{trn(A) * A * X = trn(A) * B},
4009494e
GM
6889first we compute
6890@texline @math{A' = A^T A}
40ba43b4
PE
6891@infoline @expr{A2 = trn(A) * A}
6892and
4009494e 6893@texline @math{B' = A^T B};
40ba43b4
PE
6894@infoline @expr{B2 = trn(A) * B};
6895now, we have a system
4009494e 6896@texline @math{A' X = B'}
40ba43b4 6897@infoline @expr{A2 * X = B2}
4009494e
GM
6898which we can solve using Calc's @samp{/} command.
6899
6900@ifnottex
6901@example
6902@group
6903 a + 2b + 3c = 6
6904 4a + 5b + 6c = 2
6905 7a + 6b = 3
6906 2a + 4b + 6c = 11
6907@end group
6908@end example
6909@end ifnottex
6910@tex
4009494e
GM
6911\beforedisplayh
6912$$ \openup1\jot \tabskip=0pt plus1fil
6913\halign to\displaywidth{\tabskip=0pt
6914 $\hfil#$&$\hfil{}#{}$&
6915 $\hfil#$&$\hfil{}#{}$&
6916 $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
6917 a&+&2b&+&3c&=6 \cr
6918 4a&+&5b&+&6c&=2 \cr
6919 7a&+&6b& & &=3 \cr
6920 2a&+&4b&+&6c&=11 \cr}
6921$$
6922\afterdisplayh
6923@end tex
6924
6925The first step is to enter the coefficient matrix. We'll store it in
6926quick variable number 7 for later reference. Next, we compute the
6927@texline @math{B'}
40ba43b4 6928@infoline @expr{B2}
4009494e
GM
6929vector.
6930
6931@smallexample
6932@group
69331: [ [ 1, 2, 3 ] 2: [ [ 1, 4, 7, 2 ] 1: [57, 84, 96]
6934 [ 4, 5, 6 ] [ 2, 5, 6, 4 ] .
6935 [ 7, 6, 0 ] [ 3, 6, 0, 6 ] ]
6936 [ 2, 4, 6 ] ] 1: [6, 2, 3, 11]
6937 . .
6938
6939' [1 2 3; 4 5 6; 7 6 0; 2 4 6] @key{RET} s 7 v t [6 2 3 11] *
6940@end group
6941@end smallexample
6942
6943@noindent
40ba43b4 6944Now we compute the matrix
4009494e 6945@texline @math{A'}
40ba43b4 6946@infoline @expr{A2}
4009494e
GM
6947and divide.
6948
6949@smallexample
6950@group
69512: [57, 84, 96] 1: [-11.64, 14.08, -3.64]
69521: [ [ 70, 72, 39 ] .
6953 [ 72, 81, 60 ]
6954 [ 39, 60, 81 ] ]
6955 .
6956
6957 r 7 v t r 7 * /
6958@end group
6959@end smallexample
6960
6961@noindent
6962(The actual computed answer will be slightly inexact due to
6963round-off error.)
6964
40ba43b4 6965Notice that the answers are similar to those for the
4009494e
GM
6966@texline @math{3\times3}
6967@infoline 3x3
40ba43b4 6968system solved in the text. That's because the fourth equation that was
4009494e
GM
6969added to the system is almost identical to the first one multiplied
6970by two. (If it were identical, we would have gotten the exact same
40ba43b4 6971answer since the
4009494e
GM
6972@texline @math{4\times3}
6973@infoline 4x3
40ba43b4 6974system would be equivalent to the original
4009494e
GM
6975@texline @math{3\times3}
6976@infoline 3x3
6977system.)
6978
6979Since the first and fourth equations aren't quite equivalent, they
6980can't both be satisfied at once. Let's plug our answers back into
6981the original system of equations to see how well they match.
6982
6983@smallexample
6984@group
69852: [-11.64, 14.08, -3.64] 1: [5.6, 2., 3., 11.2]
69861: [ [ 1, 2, 3 ] .
6987 [ 4, 5, 6 ]
6988 [ 7, 6, 0 ]
6989 [ 2, 4, 6 ] ]
6990 .
6991
6992 r 7 @key{TAB} *
6993@end group
6994@end smallexample
6995
6996@noindent
6997This is reasonably close to our original @expr{B} vector,
6998@expr{[6, 2, 3, 11]}.
6999
7000@node List Answer 1, List Answer 2, Matrix Answer 3, Answers to Exercises
7001@subsection List Tutorial Exercise 1
7002
7003@noindent
7004We can use @kbd{v x} to build a vector of integers. This needs to be
7005adjusted to get the range of integers we desire. Mapping @samp{-}
7006across the vector will accomplish this, although it turns out the
7007plain @samp{-} key will work just as well.
7008
7009@smallexample
7010@group
70112: 2 2: 2
70121: [1, 2, 3, 4, 5, 6, 7, 8, 9] 1: [-4, -3, -2, -1, 0, 1, 2, 3, 4]
7013 . .
7014
7015 2 v x 9 @key{RET} 5 V M - or 5 -
7016@end group
7017@end smallexample
7018
7019@noindent
7020Now we use @kbd{V M ^} to map the exponentiation operator across the
7021vector.
7022
7023@smallexample
7024@group
70251: [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
7026 .
7027
7028 V M ^
7029@end group
7030@end smallexample
7031
7032@node List Answer 2, List Answer 3, List Answer 1, Answers to Exercises
7033@subsection List Tutorial Exercise 2
7034
7035@noindent
7036Given @expr{x} and @expr{y} vectors in quick variables 1 and 2 as before,
7037the first job is to form the matrix that describes the problem.
7038
7039@ifnottex
7040@example
7041 m*x + b*1 = y
7042@end example
7043@end ifnottex
7044@tex
4009494e
GM
7045\beforedisplay
7046$$ m \times x + b \times 1 = y $$
7047\afterdisplay
7048@end tex
7049
40ba43b4 7050Thus we want a
4009494e
GM
7051@texline @math{19\times2}
7052@infoline 19x2
7053matrix with our @expr{x} vector as one column and
7054ones as the other column. So, first we build the column of ones, then
7055we combine the two columns to form our @expr{A} matrix.
7056
7057@smallexample
7058@group
70592: [1.34, 1.41, 1.49, ... ] 1: [ [ 1.34, 1 ]
70601: [1, 1, 1, ...] [ 1.41, 1 ]
7061 . [ 1.49, 1 ]
7062 @dots{}
7063
7064 r 1 1 v b 19 @key{RET} M-2 v p v t s 3
7065@end group
7066@end smallexample
7067
7068@noindent
40ba43b4 7069Now we compute
4009494e 7070@texline @math{A^T y}
40ba43b4
PE
7071@infoline @expr{trn(A) * y}
7072and
4009494e 7073@texline @math{A^T A}
40ba43b4 7074@infoline @expr{trn(A) * A}
4009494e
GM
7075and divide.
7076
7077@smallexample
7078@group
70791: [33.36554, 13.613] 2: [33.36554, 13.613]
7080 . 1: [ [ 98.0003, 41.63 ]
7081 [ 41.63, 19 ] ]
7082 .
7083
7084 v t r 2 * r 3 v t r 3 *
7085@end group
7086@end smallexample
7087
7088@noindent
7089(Hey, those numbers look familiar!)
7090
7091@smallexample
7092@group
70931: [0.52141679, -0.425978]
7094 .
7095
7096 /
7097@end group
7098@end smallexample
7099
40ba43b4 7100Since we were solving equations of the form
4009494e 7101@texline @math{m \times x + b \times 1 = y},
40ba43b4 7102@infoline @expr{m*x + b*1 = y},
4009494e
GM
7103these numbers should be @expr{m} and @expr{b}, respectively. Sure
7104enough, they agree exactly with the result computed using @kbd{V M} and
7105@kbd{V R}!
7106
7107The moral of this story: @kbd{V M} and @kbd{V R} will probably solve
7108your problem, but there is often an easier way using the higher-level
7109arithmetic functions!
7110
7111@c [fix-ref Curve Fitting]
7112In fact, there is a built-in @kbd{a F} command that does least-squares
7113fits. @xref{Curve Fitting}.
7114
7115@node List Answer 3, List Answer 4, List Answer 2, Answers to Exercises
7116@subsection List Tutorial Exercise 3
7117
7118@noindent
7119Move to one end of the list and press @kbd{C-@@} (or @kbd{C-@key{SPC}} or
7120whatever) to set the mark, then move to the other end of the list
7121and type @w{@kbd{C-x * g}}.
7122
7123@smallexample
7124@group
71251: [2.3, 6, 22, 15.1, 7, 15, 14, 7.5, 2.5]
7126 .
7127@end group
7128@end smallexample
7129
7130To make things interesting, let's assume we don't know at a glance
7131how many numbers are in this list. Then we could type:
7132
7133@smallexample
7134@group
71352: [2.3, 6, 22, ... ] 2: [2.3, 6, 22, ... ]
71361: [2.3, 6, 22, ... ] 1: 126356422.5
7137 . .
7138
7139 @key{RET} V R *
7140
7141@end group
7142@end smallexample
7143@noindent
7144@smallexample
7145@group
71462: 126356422.5 2: 126356422.5 1: 7.94652913734
71471: [2.3, 6, 22, ... ] 1: 9 .
7148 . .
7149
7150 @key{TAB} v l I ^
7151@end group
7152@end smallexample
7153
7154@noindent
7155(The @kbd{I ^} command computes the @var{n}th root of a number.
7156You could also type @kbd{& ^} to take the reciprocal of 9 and
7157then raise the number to that power.)
7158
7159@node List Answer 4, List Answer 5, List Answer 3, Answers to Exercises
7160@subsection List Tutorial Exercise 4
7161
7162@noindent
40ba43b4 7163A number @expr{j} is a divisor of @expr{n} if
4009494e 7164@texline @math{n \mathbin{\hbox{\code{\%}}} j = 0}.
40ba43b4 7165@infoline @samp{n % j = 0}.
4009494e
GM
7166The first step is to get a vector that identifies the divisors.
7167
7168@smallexample
7169@group
71702: 30 2: [0, 0, 0, 2, ...] 1: [1, 1, 1, 0, ...]
71711: [1, 2, 3, 4, ...] 1: 0 .
7172 . .
7173
7174 30 @key{RET} v x 30 @key{RET} s 1 V M % 0 V M a = s 2
7175@end group
7176@end smallexample
7177
7178@noindent
7179This vector has 1's marking divisors of 30 and 0's marking non-divisors.
7180
7181The zeroth divisor function is just the total number of divisors.
7182The first divisor function is the sum of the divisors.
7183
7184@smallexample
7185@group
71861: 8 3: 8 2: 8 2: 8
7187 2: [1, 2, 3, 4, ...] 1: [1, 2, 3, 0, ...] 1: 72
7188 1: [1, 1, 1, 0, ...] . .
7189 .
7190
7191 V R + r 1 r 2 V M * V R +
7192@end group
7193@end smallexample
7194
7195@noindent
7196Once again, the last two steps just compute a dot product for which
7197a simple @kbd{*} would have worked equally well.
7198
7199@node List Answer 5, List Answer 6, List Answer 4, Answers to Exercises
7200@subsection List Tutorial Exercise 5
7201
7202@noindent
7203The obvious first step is to obtain the list of factors with @kbd{k f}.
7204This list will always be in sorted order, so if there are duplicates
7205they will be right next to each other. A suitable method is to compare
7206the list with a copy of itself shifted over by one.
7207
7208@smallexample
7209@group
72101: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19] 2: [3, 7, 7, 7, 19, 0]
7211 . 1: [3, 7, 7, 7, 19, 0] 1: [0, 3, 7, 7, 7, 19]
7212 . .
7213
7214 19551 k f @key{RET} 0 | @key{TAB} 0 @key{TAB} |
7215
7216@end group
7217@end smallexample
7218@noindent
7219@smallexample
7220@group
72211: [0, 0, 1, 1, 0, 0] 1: 2 1: 0
7222 . . .
7223
7224 V M a = V R + 0 a =
7225@end group
7226@end smallexample
7227
7228@noindent
7229Note that we have to arrange for both vectors to have the same length
7230so that the mapping operation works; no prime factor will ever be
7231zero, so adding zeros on the left and right is safe. From then on
7232the job is pretty straightforward.
7233
40ba43b4 7234Incidentally, Calc provides the
4009494e 7235@texline @dfn{M@"obius} @math{\mu}
40ba43b4 7236@infoline @dfn{Moebius mu}
4009494e
GM
7237function which is zero if and only if its argument is square-free. It
7238would be a much more convenient way to do the above test in practice.
7239
7240@node List Answer 6, List Answer 7, List Answer 5, Answers to Exercises
7241@subsection List Tutorial Exercise 6
7242
7243@noindent
7244First use @kbd{v x 6 @key{RET}} to get a list of integers, then @kbd{V M v x}
7245to get a list of lists of integers!
7246
7247@node List Answer 7, List Answer 8, List Answer 6, Answers to Exercises
7248@subsection List Tutorial Exercise 7
7249
7250@noindent
7251Here's one solution. First, compute the triangular list from the previous
7252exercise and type @kbd{1 -} to subtract one from all the elements.
7253
7254@smallexample
7255@group
72561: [ [0],
7257 [0, 1],
7258 [0, 1, 2],
7259 @dots{}
7260
7261 1 -
7262@end group
7263@end smallexample
7264
7265The numbers down the lefthand edge of the list we desire are called
7266the ``triangular numbers'' (now you know why!). The @expr{n}th
7267triangular number is the sum of the integers from 1 to @expr{n}, and
40ba43b4 7268can be computed directly by the formula
4009494e
GM
7269@texline @math{n (n+1) \over 2}.
7270@infoline @expr{n * (n+1) / 2}.
7271
7272@smallexample
7273@group
72742: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
72751: [0, 1, 2, 3, 4, 5] 1: [0, 1, 3, 6, 10, 15]
7276 . .
7277
7278 v x 6 @key{RET} 1 - V M ' $ ($+1)/2 @key{RET}
7279@end group
7280@end smallexample
7281
7282@noindent
7283Adding this list to the above list of lists produces the desired
7284result:
7285
7286@smallexample
7287@group
72881: [ [0],
7289 [1, 2],
7290 [3, 4, 5],
7291 [6, 7, 8, 9],
7292 [10, 11, 12, 13, 14],
7293 [15, 16, 17, 18, 19, 20] ]
7294 .
7295
7296 V M +
7297@end group
7298@end smallexample
7299
7300If we did not know the formula for triangular numbers, we could have
7301computed them using a @kbd{V U +} command. We could also have
7302gotten them the hard way by mapping a reduction across the original
7303triangular list.
7304
7305@smallexample
7306@group
73072: [ [0], [0, 1], ... ] 2: [ [0], [0, 1], ... ]
73081: [ [0], [0, 1], ... ] 1: [0, 1, 3, 6, 10, 15]
7309 . .
7310
7311 @key{RET} V M V R +
7312@end group
7313@end smallexample
7314
7315@noindent
7316(This means ``map a @kbd{V R +} command across the vector,'' and
7317since each element of the main vector is itself a small vector,
7318@kbd{V R +} computes the sum of its elements.)
7319
7320@node List Answer 8, List Answer 9, List Answer 7, Answers to Exercises
7321@subsection List Tutorial Exercise 8
7322
7323@noindent
7324The first step is to build a list of values of @expr{x}.
7325
7326@smallexample
7327@group
73281: [1, 2, 3, ..., 21] 1: [0, 1, 2, ..., 20] 1: [0, 0.25, 0.5, ..., 5]
7329 . . .
7330
7331 v x 21 @key{RET} 1 - 4 / s 1
7332@end group
7333@end smallexample
7334
7335Next, we compute the Bessel function values.
7336
7337@smallexample
7338@group
73391: [0., 0.124, 0.242, ..., -0.328]
7340 .
7341
7342 V M ' besJ(1,$) @key{RET}
7343@end group
7344@end smallexample
7345
7346@noindent
7347(Another way to do this would be @kbd{1 @key{TAB} V M f j}.)
7348
7349A way to isolate the maximum value is to compute the maximum using
7350@kbd{V R X}, then compare all the Bessel values with that maximum.
7351
7352@smallexample
7353@group
73542: [0., 0.124, 0.242, ... ] 1: [0, 0, 0, ... ] 2: [0, 0, 0, ... ]
73551: 0.5801562 . 1: 1
7356 . .
7357
7358 @key{RET} V R X V M a = @key{RET} V R + @key{DEL}
7359@end group
7360@end smallexample
7361
7362@noindent
7363It's a good idea to verify, as in the last step above, that only
40ba43b4 7364one value is equal to the maximum. (After all, a plot of
4009494e
GM
7365@texline @math{\sin x}
7366@infoline @expr{sin(x)}
7367might have many points all equal to the maximum value, 1.)
7368
7369The vector we have now has a single 1 in the position that indicates
7370the maximum value of @expr{x}. Now it is a simple matter to convert
7371this back into the corresponding value itself.
7372
7373@smallexample
7374@group
73752: [0, 0, 0, ... ] 1: [0, 0., 0., ... ] 1: 1.75
73761: [0, 0.25, 0.5, ... ] . .
7377 .
7378
7379 r 1 V M * V R +
7380@end group
7381@end smallexample
7382
7383If @kbd{a =} had produced more than one @expr{1} value, this method
7384would have given the sum of all maximum @expr{x} values; not very
7385useful! In this case we could have used @kbd{v m} (@code{calc-mask-vector})
7386instead. This command deletes all elements of a ``data'' vector that
7387correspond to zeros in a ``mask'' vector, leaving us with, in this
7388example, a vector of maximum @expr{x} values.
7389
7390The built-in @kbd{a X} command maximizes a function using more
7391efficient methods. Just for illustration, let's use @kbd{a X}
7392to maximize @samp{besJ(1,x)} over this same interval.
7393
7394@smallexample
7395@group
73962: besJ(1, x) 1: [1.84115, 0.581865]
73971: [0 .. 5] .
7398 .
7399
7400' besJ(1,x), [0..5] @key{RET} a X x @key{RET}
7401@end group
7402@end smallexample
7403
7404@noindent
7405The output from @kbd{a X} is a vector containing the value of @expr{x}
7406that maximizes the function, and the function's value at that maximum.
7407As you can see, our simple search got quite close to the right answer.
7408
7409@node List Answer 9, List Answer 10, List Answer 8, Answers to Exercises
7410@subsection List Tutorial Exercise 9
7411
7412@noindent
7413Step one is to convert our integer into vector notation.
7414
7415@smallexample
7416@group
74171: 25129925999 3: 25129925999
7418 . 2: 10
7419 1: [11, 10, 9, ..., 1, 0]
7420 .
7421
7422 25129925999 @key{RET} 10 @key{RET} 12 @key{RET} v x 12 @key{RET} -
7423
7424@end group
7425@end smallexample
7426@noindent
7427@smallexample
7428@group
74291: 25129925999 1: [0, 2, 25, 251, 2512, ... ]
74302: [100000000000, ... ] .
7431 .
7432
7433 V M ^ s 1 V M \
7434@end group
7435@end smallexample
7436
7437@noindent
7438(Recall, the @kbd{\} command computes an integer quotient.)
7439
7440@smallexample
7441@group
74421: [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
7443 .
7444
7445 10 V M % s 2
7446@end group
7447@end smallexample
7448
7449Next we must increment this number. This involves adding one to
7450the last digit, plus handling carries. There is a carry to the
7451left out of a digit if that digit is a nine and all the digits to
7452the right of it are nines.
7453
7454@smallexample
7455@group
74561: [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1] 1: [1, 1, 1, 0, 0, 1, ... ]
7457 . .
7458
7459 9 V M a = v v
7460
7461@end group
7462@end smallexample
7463@noindent
7464@smallexample
7465@group
74661: [1, 1, 1, 0, 0, 0, ... ] 1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
7467 . .
7468
7469 V U * v v 1 |
7470@end group
7471@end smallexample
7472
7473@noindent
7474Accumulating @kbd{*} across a vector of ones and zeros will preserve
7475only the initial run of ones. These are the carries into all digits
7476except the rightmost digit. Concatenating a one on the right takes
7477care of aligning the carries properly, and also adding one to the
7478rightmost digit.
7479
7480@smallexample
7481@group
74822: [0, 0, 0, 0, ... ] 1: [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
74831: [0, 0, 2, 5, ... ] .
7484 .
7485
7486 0 r 2 | V M + 10 V M %
7487@end group
7488@end smallexample
7489
7490@noindent
7491Here we have concatenated 0 to the @emph{left} of the original number;
7492this takes care of shifting the carries by one with respect to the
7493digits that generated them.
7494
7495Finally, we must convert this list back into an integer.
7496
7497@smallexample
7498@group
74993: [0, 0, 2, 5, ... ] 2: [0, 0, 2, 5, ... ]
75002: 1000000000000 1: [1000000000000, 100000000000, ... ]
75011: [100000000000, ... ] .
7502 .
7503
7504 10 @key{RET} 12 ^ r 1 |
7505
7506@end group
7507@end smallexample
7508@noindent
7509@smallexample
7510@group
75111: [0, 0, 20000000000, 5000000000, ... ] 1: 25129926000
7512 . .
7513
7514 V M * V R +
7515@end group
7516@end smallexample
7517
7518@noindent
7519Another way to do this final step would be to reduce the formula
7520@w{@samp{10 $$ + $}} across the vector of digits.
7521
7522@smallexample
7523@group
75241: [0, 0, 2, 5, ... ] 1: 25129926000
7525 . .
7526
7527 V R ' 10 $$ + $ @key{RET}
7528@end group
7529@end smallexample
7530
7531@node List Answer 10, List Answer 11, List Answer 9, Answers to Exercises
7532@subsection List Tutorial Exercise 10
7533
7534@noindent
7535For the list @expr{[a, b, c, d]}, the result is @expr{((a = b) = c) = d},
7536which will compare @expr{a} and @expr{b} to produce a 1 or 0, which is
7537then compared with @expr{c} to produce another 1 or 0, which is then
7538compared with @expr{d}. This is not at all what Joe wanted.
7539
7540Here's a more correct method:
7541
7542@smallexample
7543@group
75441: [7, 7, 7, 8, 7] 2: [7, 7, 7, 8, 7]
7545 . 1: 7
7546 .
7547
7548 ' [7,7,7,8,7] @key{RET} @key{RET} v r 1 @key{RET}
7549
7550@end group
7551@end smallexample
7552@noindent
7553@smallexample
7554@group
75551: [1, 1, 1, 0, 1] 1: 0
7556 . .
7557
7558 V M a = V R *
7559@end group
7560@end smallexample
7561
7562@node List Answer 11, List Answer 12, List Answer 10, Answers to Exercises
7563@subsection List Tutorial Exercise 11
7564
7565@noindent
7566The circle of unit radius consists of those points @expr{(x,y)} for which
7567@expr{x^2 + y^2 < 1}. We start by generating a vector of @expr{x^2}
7568and a vector of @expr{y^2}.
7569
7570We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7571commands.
7572
7573@smallexample
7574@group
75752: [2., 2., ..., 2.] 2: [2., 2., ..., 2.]
75761: [2., 2., ..., 2.] 1: [1.16, 1.98, ..., 0.81]
7577 . .
7578
7579 v . t . 2. v b 100 @key{RET} @key{RET} V M k r
7580
7581@end group
7582@end smallexample
7583@noindent
7584@smallexample
7585@group
75862: [2., 2., ..., 2.] 1: [0.026, 0.96, ..., 0.036]
75871: [0.026, 0.96, ..., 0.036] 2: [0.53, 0.81, ..., 0.094]
7588 . .
7589
7590 1 - 2 V M ^ @key{TAB} V M k r 1 - 2 V M ^
7591@end group
7592@end smallexample
7593
7594Now we sum the @expr{x^2} and @expr{y^2} values, compare with 1 to
7595get a vector of 1/0 truth values, then sum the truth values.
7596
7597@smallexample
7598@group
75991: [0.56, 1.78, ..., 0.13] 1: [1, 0, ..., 1] 1: 84
7600 . . .
7601
7602 + 1 V M a < V R +
7603@end group
7604@end smallexample
7605
7606@noindent
7607The ratio @expr{84/100} should approximate the ratio @cpiover{4}.
7608
7609@smallexample
7610@group
76111: 0.84 1: 3.36 2: 3.36 1: 1.0695
7612 . . 1: 3.14159 .
7613
7614 100 / 4 * P /
7615@end group
7616@end smallexample
7617
7618@noindent
7619Our estimate, 3.36, is off by about 7%. We could get a better estimate
7620by taking more points (say, 1000), but it's clear that this method is
7621not very efficient!
7622
7623(Naturally, since this example uses random numbers your own answer
7624will be slightly different from the one shown here!)
7625
7626If you typed @kbd{v .} and @kbd{t .} before, type them again to
7627return to full-sized display of vectors.
7628
7629@node List Answer 12, List Answer 13, List Answer 11, Answers to Exercises
7630@subsection List Tutorial Exercise 12
7631
7632@noindent
7633This problem can be made a lot easier by taking advantage of some
7634symmetries. First of all, after some thought it's clear that the
7635@expr{y} axis can be ignored altogether. Just pick a random @expr{x}
40ba43b4 7636component for one end of the match, pick a random direction
4009494e
GM
7637@texline @math{\theta},
7638@infoline @expr{theta},
40ba43b4 7639and see if @expr{x} and
4009494e 7640@texline @math{x + \cos \theta}
40ba43b4 7641@infoline @expr{x + cos(theta)}
4009494e
GM
7642(which is the @expr{x} coordinate of the other endpoint) cross a line.
7643The lines are at integer coordinates, so this happens when the two
7644numbers surround an integer.
7645
7646Since the two endpoints are equivalent, we may as well choose the leftmost
7647of the two endpoints as @expr{x}. Then @expr{theta} is an angle pointing
7648to the right, in the range -90 to 90 degrees. (We could use radians, but
7649it would feel like cheating to refer to @cpiover{2} radians while trying
7650to estimate @cpi{}!)
7651
7652In fact, since the field of lines is infinite we can choose the
7653coordinates 0 and 1 for the lines on either side of the leftmost
7654endpoint. The rightmost endpoint will be between 0 and 1 if the
7655match does not cross a line, or between 1 and 2 if it does. So:
40ba43b4 7656Pick random @expr{x} and
4009494e 7657@texline @math{\theta},
40ba43b4 7658@infoline @expr{theta},
4009494e
GM
7659compute
7660@texline @math{x + \cos \theta},
7661@infoline @expr{x + cos(theta)},
7662and count how many of the results are greater than one. Simple!
7663
7664We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7665commands.
7666
7667@smallexample
7668@group
76691: [0.52, 0.71, ..., 0.72] 2: [0.52, 0.71, ..., 0.72]
7670 . 1: [78.4, 64.5, ..., -42.9]
7671 .
7672
7673v . t . 1. v b 100 @key{RET} V M k r 180. v b 100 @key{RET} V M k r 90 -
7674@end group
7675@end smallexample
7676
7677@noindent
7678(The next step may be slow, depending on the speed of your computer.)
7679
7680@smallexample
7681@group
76822: [0.52, 0.71, ..., 0.72] 1: [0.72, 1.14, ..., 1.45]
76831: [0.20, 0.43, ..., 0.73] .
7684 .
7685
7686 m d V M C +
7687
7688@end group
7689@end smallexample
7690@noindent
7691@smallexample
7692@group
76931: [0, 1, ..., 1] 1: 0.64 1: 3.125
7694 . . .
7695
7696 1 V M a > V R + 100 / 2 @key{TAB} /
7697@end group
7698@end smallexample
7699
7700Let's try the third method, too. We'll use random integers up to
7701one million. The @kbd{k r} command with an integer argument picks
7702a random integer.
7703
7704@smallexample
7705@group
77062: [1000000, 1000000, ..., 1000000] 2: [78489, 527587, ..., 814975]
77071: [1000000, 1000000, ..., 1000000] 1: [324014, 358783, ..., 955450]
7708 . .
7709
7710 1000000 v b 100 @key{RET} @key{RET} V M k r @key{TAB} V M k r
7711
7712@end group
7713@end smallexample
7714@noindent
7715@smallexample
7716@group
77171: [1, 1, ..., 25] 1: [1, 1, ..., 0] 1: 0.56
7718 . . .
7719
7720 V M k g 1 V M a = V R + 100 /
7721
7722@end group
7723@end smallexample
7724@noindent
7725@smallexample
7726@group
77271: 10.714 1: 3.273
7728 . .
7729
7730 6 @key{TAB} / Q
7731@end group
7732@end smallexample
7733
7734For a proof of this property of the GCD function, see section 4.5.2,
7735exercise 10, of Knuth's @emph{Art of Computer Programming}, volume II.
7736
7737If you typed @kbd{v .} and @kbd{t .} before, type them again to
7738return to full-sized display of vectors.
7739
7740@node List Answer 13, List Answer 14, List Answer 12, Answers to Exercises
7741@subsection List Tutorial Exercise 13
7742
7743@noindent
7744First, we put the string on the stack as a vector of ASCII codes.
7745
7746@smallexample
7747@group
77481: [84, 101, 115, ..., 51]
7749 .
7750
7751 "Testing, 1, 2, 3 @key{RET}
7752@end group
7753@end smallexample
7754
7755@noindent
7756Note that the @kbd{"} key, like @kbd{$}, initiates algebraic entry so
7757there was no need to type an apostrophe. Also, Calc didn't mind that
7758we omitted the closing @kbd{"}. (The same goes for all closing delimiters
7759like @kbd{)} and @kbd{]} at the end of a formula.
7760
7761We'll show two different approaches here. In the first, we note that
7762if the input vector is @expr{[a, b, c, d]}, then the hash code is
7763@expr{3 (3 (3a + b) + c) + d = 27a + 9b + 3c + d}. In other words,
7764it's a sum of descending powers of three times the ASCII codes.
7765
7766@smallexample
7767@group
77682: [84, 101, 115, ..., 51] 2: [84, 101, 115, ..., 51]
77691: 16 1: [15, 14, 13, ..., 0]
7770 . .
7771
7772 @key{RET} v l v x 16 @key{RET} -
7773
7774@end group
7775@end smallexample
7776@noindent
7777@smallexample
7778@group
77792: [84, 101, 115, ..., 51] 1: 1960915098 1: 121
77801: [14348907, ..., 1] . .
7781 .
7782
7783 3 @key{TAB} V M ^ * 511 %
7784@end group
7785@end smallexample
7786
7787@noindent
7788Once again, @kbd{*} elegantly summarizes most of the computation.
7789But there's an even more elegant approach: Reduce the formula
7790@kbd{3 $$ + $} across the vector. Recall that this represents a
7791function of two arguments that computes its first argument times three
7792plus its second argument.
7793
7794@smallexample
7795@group
77961: [84, 101, 115, ..., 51] 1: 1960915098
7797 . .
7798
7799 "Testing, 1, 2, 3 @key{RET} V R ' 3$$+$ @key{RET}
7800@end group
7801@end smallexample
7802
7803@noindent
7804If you did the decimal arithmetic exercise, this will be familiar.
7805Basically, we're turning a base-3 vector of digits into an integer,
7806except that our ``digits'' are much larger than real digits.
7807
7808Instead of typing @kbd{511 %} again to reduce the result, we can be
7809cleverer still and notice that rather than computing a huge integer
7810and taking the modulo at the end, we can take the modulo at each step
7811without affecting the result. While this means there are more
7812arithmetic operations, the numbers we operate on remain small so
7813the operations are faster.
7814
7815@smallexample
7816@group
78171: [84, 101, 115, ..., 51] 1: 121
7818 . .
7819
7820 "Testing, 1, 2, 3 @key{RET} V R ' (3$$+$)%511 @key{RET}
7821@end group
7822@end smallexample
7823
7824Why does this work? Think about a two-step computation:
7825@w{@expr{3 (3a + b) + c}}. Taking a result modulo 511 basically means
7826subtracting off enough 511's to put the result in the desired range.
7827So the result when we take the modulo after every step is,
7828
7829@ifnottex
7830@example
78313 (3 a + b - 511 m) + c - 511 n
7832@end example
7833@end ifnottex
7834@tex
4009494e
GM
7835\beforedisplay
7836$$ 3 (3 a + b - 511 m) + c - 511 n $$
7837\afterdisplay
7838@end tex
7839
7840@noindent
7841for some suitable integers @expr{m} and @expr{n}. Expanding out by
7842the distributive law yields
7843
7844@ifnottex
7845@example
78469 a + 3 b + c - 511*3 m - 511 n
7847@end example
7848@end ifnottex
7849@tex
4009494e
GM
7850\beforedisplay
7851$$ 9 a + 3 b + c - 511\times3 m - 511 n $$
7852\afterdisplay
7853@end tex
7854
7855@noindent
7856The @expr{m} term in the latter formula is redundant because any
7857contribution it makes could just as easily be made by the @expr{n}
7858term. So we can take it out to get an equivalent formula with
7859@expr{n' = 3m + n},
7860
7861@ifnottex
7862@example
78639 a + 3 b + c - 511 n'
7864@end example
7865@end ifnottex
7866@tex
4009494e 7867\beforedisplay
db37d257 7868$$ 9 a + 3 b + c - 511 n^{\prime} $$
4009494e
GM
7869\afterdisplay
7870@end tex
7871
7872@noindent
7873which is just the formula for taking the modulo only at the end of
7874the calculation. Therefore the two methods are essentially the same.
7875
7876Later in the tutorial we will encounter @dfn{modulo forms}, which
7877basically automate the idea of reducing every intermediate result
7878modulo some value @var{m}.
7879
7880@node List Answer 14, Types Answer 1, List Answer 13, Answers to Exercises
7881@subsection List Tutorial Exercise 14
7882
7883We want to use @kbd{H V U} to nest a function which adds a random
7884step to an @expr{(x,y)} coordinate. The function is a bit long, but
7885otherwise the problem is quite straightforward.
7886
7887@smallexample
7888@group
78892: [0, 0] 1: [ [ 0, 0 ]
78901: 50 [ 0.4288, -0.1695 ]
7891 . [ -0.4787, -0.9027 ]
7892 ...
7893
7894 [0,0] 50 H V U ' <# + [random(2.0)-1, random(2.0)-1]> @key{RET}
7895@end group
7896@end smallexample
7897
7898Just as the text recommended, we used @samp{< >} nameless function
7899notation to keep the two @code{random} calls from being evaluated
7900before nesting even begins.
7901
7902We now have a vector of @expr{[x, y]} sub-vectors, which by Calc's
7903rules acts like a matrix. We can transpose this matrix and unpack
7904to get a pair of vectors, @expr{x} and @expr{y}, suitable for graphing.
7905
7906@smallexample
7907@group
79082: [ 0, 0.4288, -0.4787, ... ]
79091: [ 0, -0.1696, -0.9027, ... ]
7910 .
7911
7912 v t v u g f
7913@end group
7914@end smallexample
7915
7916Incidentally, because the @expr{x} and @expr{y} are completely
7917independent in this case, we could have done two separate commands
7918to create our @expr{x} and @expr{y} vectors of numbers directly.
7919
7920To make a random walk of unit steps, we note that @code{sincos} of
7921a random direction exactly gives us an @expr{[x, y]} step of unit
7922length; in fact, the new nesting function is even briefer, though
7923we might want to lower the precision a bit for it.
7924
7925@smallexample
7926@group
79272: [0, 0] 1: [ [ 0, 0 ]
79281: 50 [ 0.1318, 0.9912 ]
7929 . [ -0.5965, 0.3061 ]
7930 ...
7931
7932 [0,0] 50 m d p 6 @key{RET} H V U ' <# + sincos(random(360.0))> @key{RET}
7933@end group
7934@end smallexample
7935
7936Another @kbd{v t v u g f} sequence will graph this new random walk.
7937
7938An interesting twist on these random walk functions would be to use
7939complex numbers instead of 2-vectors to represent points on the plane.
7940In the first example, we'd use something like @samp{random + random*(0,1)},
7941and in the second we could use polar complex numbers with random phase
7942angles. (This exercise was first suggested in this form by Randal
7943Schwartz.)
7944
7945@node Types Answer 1, Types Answer 2, List Answer 14, Answers to Exercises
7946@subsection Types Tutorial Exercise 1
7947
7948@noindent
7949If the number is the square root of @cpi{} times a rational number,
7950then its square, divided by @cpi{}, should be a rational number.
7951
7952@smallexample
7953@group
79541: 1.26508260337 1: 0.509433962268 1: 2486645810:4881193627
7955 . . .
7956
7957 2 ^ P / c F
7958@end group
7959@end smallexample
7960
7961@noindent
7962Technically speaking this is a rational number, but not one that is
7963likely to have arisen in the original problem. More likely, it just
7964happens to be the fraction which most closely represents some
7965irrational number to within 12 digits.
7966
7967But perhaps our result was not quite exact. Let's reduce the
7968precision slightly and try again:
7969
7970@smallexample
7971@group
79721: 0.509433962268 1: 27:53
7973 . .
7974
7975 U p 10 @key{RET} c F
7976@end group
7977@end smallexample
7978
7979@noindent
7980Aha! It's unlikely that an irrational number would equal a fraction
7981this simple to within ten digits, so our original number was probably
7982@texline @math{\sqrt{27 \pi / 53}}.
7983@infoline @expr{sqrt(27 pi / 53)}.
7984
7985Notice that we didn't need to re-round the number when we reduced the
7986precision. Remember, arithmetic operations always round their inputs
7987to the current precision before they begin.
7988
7989@node Types Answer 2, Types Answer 3, Types Answer 1, Answers to Exercises
7990@subsection Types Tutorial Exercise 2
7991
7992@noindent
7993@samp{inf / inf = nan}. Perhaps @samp{1} is the ``obvious'' answer.
7994But if @w{@samp{17 inf = inf}}, then @samp{17 inf / inf = inf / inf = 17}, too.
7995
7996@samp{exp(inf) = inf}. It's tempting to say that the exponential
7997of infinity must be ``bigger'' than ``regular'' infinity, but as
74edaf1f 7998far as Calc is concerned all infinities are the same size.
4009494e
GM
7999In other words, as @expr{x} goes to infinity, @expr{e^x} also goes
8000to infinity, but the fact the @expr{e^x} grows much faster than
8001@expr{x} is not relevant here.
8002
8003@samp{exp(-inf) = 0}. Here we have a finite answer even though
8004the input is infinite.
8005
8006@samp{sqrt(-inf) = (0, 1) inf}. Remember that @expr{(0, 1)}
8007represents the imaginary number @expr{i}. Here's a derivation:
8008@samp{sqrt(-inf) = @w{sqrt((-1) * inf)} = sqrt(-1) * sqrt(inf)}.
8009The first part is, by definition, @expr{i}; the second is @code{inf}
8010because, once again, all infinities are the same size.
8011
8012@samp{sqrt(uinf) = uinf}. In fact, we do know something about the
8013direction because @code{sqrt} is defined to return a value in the
8014right half of the complex plane. But Calc has no notation for this,
8015so it settles for the conservative answer @code{uinf}.
8016
8017@samp{abs(uinf) = inf}. No matter which direction @expr{x} points,
8018@samp{abs(x)} always points along the positive real axis.
8019
8020@samp{ln(0) = -inf}. Here we have an infinite answer to a finite
8021input. As in the @expr{1 / 0} case, Calc will only use infinities
8022here if you have turned on Infinite mode. Otherwise, it will
8023treat @samp{ln(0)} as an error.
8024
8025@node Types Answer 3, Types Answer 4, Types Answer 2, Answers to Exercises
8026@subsection Types Tutorial Exercise 3
8027
8028@noindent
8029We can make @samp{inf - inf} be any real number we like, say,
8030@expr{a}, just by claiming that we added @expr{a} to the first
8031infinity but not to the second. This is just as true for complex
8032values of @expr{a}, so @code{nan} can stand for a complex number.
8033(And, similarly, @code{uinf} can stand for an infinity that points
8034in any direction in the complex plane, such as @samp{(0, 1) inf}).
8035
8036In fact, we can multiply the first @code{inf} by two. Surely
8037@w{@samp{2 inf - inf = inf}}, but also @samp{2 inf - inf = inf - inf = nan}.
8038So @code{nan} can even stand for infinity. Obviously it's just
8039as easy to make it stand for minus infinity as for plus infinity.
8040
8041The moral of this story is that ``infinity'' is a slippery fish
8042indeed, and Calc tries to handle it by having a very simple model
8043for infinities (only the direction counts, not the ``size''); but
8044Calc is careful to write @code{nan} any time this simple model is
8045unable to tell what the true answer is.
8046
8047@node Types Answer 4, Types Answer 5, Types Answer 3, Answers to Exercises
8048@subsection Types Tutorial Exercise 4
8049
8050@smallexample
8051@group
80522: 0@@ 47' 26" 1: 0@@ 2' 47.411765"
80531: 17 .
8054 .
8055
8056 0@@ 47' 26" @key{RET} 17 /
8057@end group
8058@end smallexample
8059
8060@noindent
8061The average song length is two minutes and 47.4 seconds.
8062
8063@smallexample
8064@group
80652: 0@@ 2' 47.411765" 1: 0@@ 3' 7.411765" 1: 0@@ 53' 6.000005"
80661: 0@@ 0' 20" . .
8067 .
8068
8069 20" + 17 *
8070@end group
8071@end smallexample
8072
8073@noindent
8074The album would be 53 minutes and 6 seconds long.
8075
8076@node Types Answer 5, Types Answer 6, Types Answer 4, Answers to Exercises
8077@subsection Types Tutorial Exercise 5
8078
8079@noindent
8080Let's suppose it's January 14, 1991. The easiest thing to do is
8081to keep trying 13ths of months until Calc reports a Friday.
8082We can do this by manually entering dates, or by using @kbd{t I}:
8083
8084@smallexample
8085@group
80861: <Wed Feb 13, 1991> 1: <Wed Mar 13, 1991> 1: <Sat Apr 13, 1991>
8087 . . .
8088
8089 ' <2/13> @key{RET} @key{DEL} ' <3/13> @key{RET} t I
8090@end group
8091@end smallexample
8092
8093@noindent
8094(Calc assumes the current year if you don't say otherwise.)
8095
8096This is getting tedious---we can keep advancing the date by typing
8097@kbd{t I} over and over again, but let's automate the job by using
8098vector mapping. The @kbd{t I} command actually takes a second
8099``how-many-months'' argument, which defaults to one. This
8100argument is exactly what we want to map over:
8101
8102@smallexample
8103@group
81042: <Sat Apr 13, 1991> 1: [<Mon May 13, 1991>, <Thu Jun 13, 1991>,
81051: [1, 2, 3, 4, 5, 6] <Sat Jul 13, 1991>, <Tue Aug 13, 1991>,
8106 . <Fri Sep 13, 1991>, <Sun Oct 13, 1991>]
8107 .
8108
8109 v x 6 @key{RET} V M t I
8110@end group
8111@end smallexample
8112
8113@noindent
8114Et voil@`a, September 13, 1991 is a Friday.
8115
8116@smallexample
8117@group
81181: 242
8119 .
8120
8121' <sep 13> - <jan 14> @key{RET}
8122@end group
8123@end smallexample
8124
8125@noindent
8126And the answer to our original question: 242 days to go.
8127
8128@node Types Answer 6, Types Answer 7, Types Answer 5, Answers to Exercises
8129@subsection Types Tutorial Exercise 6
8130
8131@noindent
8132The full rule for leap years is that they occur in every year divisible
8133by four, except that they don't occur in years divisible by 100, except
8134that they @emph{do} in years divisible by 400. We could work out the
8135answer by carefully counting the years divisible by four and the
8136exceptions, but there is a much simpler way that works even if we
8137don't know the leap year rule.
8138
8139Let's assume the present year is 1991. Years have 365 days, except
8140that leap years (whenever they occur) have 366 days. So let's count
8141the number of days between now and then, and compare that to the
8142number of years times 365. The number of extra days we find must be
8143equal to the number of leap years there were.
8144
8145@smallexample
8146@group
81471: <Mon Jan 1, 10001> 2: <Mon Jan 1, 10001> 1: 2925593
8148 . 1: <Tue Jan 1, 1991> .
8149 .
8150
8151 ' <jan 1 10001> @key{RET} ' <jan 1 1991> @key{RET} -
8152
8153@end group
8154@end smallexample
8155@noindent
8156@smallexample
8157@group
81583: 2925593 2: 2925593 2: 2925593 1: 1943
81592: 10001 1: 8010 1: 2923650 .
81601: 1991 . .
8161 .
8162
8163 10001 @key{RET} 1991 - 365 * -
8164@end group
8165@end smallexample
8166
8167@c [fix-ref Date Forms]
8168@noindent
8169There will be 1943 leap years before the year 10001. (Assuming,
8170of course, that the algorithm for computing leap years remains
8171unchanged for that long. @xref{Date Forms}, for some interesting
8172background information in that regard.)
8173
8174@node Types Answer 7, Types Answer 8, Types Answer 6, Answers to Exercises
8175@subsection Types Tutorial Exercise 7
8176
8177@noindent
8178The relative errors must be converted to absolute errors so that
8179@samp{+/-} notation may be used.
8180
8181@smallexample
8182@group
81831: 1. 2: 1.
8184 . 1: 0.2
8185 .
8186
8187 20 @key{RET} .05 * 4 @key{RET} .05 *
8188@end group
8189@end smallexample
8190
8191Now we simply chug through the formula.
8192
8193@smallexample
8194@group
81951: 19.7392088022 1: 394.78 +/- 19.739 1: 6316.5 +/- 706.21
8196 . . .
8197
8198 2 P 2 ^ * 20 p 1 * 4 p .2 @key{RET} 2 ^ *
8199@end group
8200@end smallexample
8201
8202It turns out the @kbd{v u} command will unpack an error form as
8203well as a vector. This saves us some retyping of numbers.
8204
8205@smallexample
8206@group
82073: 6316.5 +/- 706.21 2: 6316.5 +/- 706.21
82082: 6316.5 1: 0.1118
82091: 706.21 .
8210 .
8211
8212 @key{RET} v u @key{TAB} /
8213@end group
8214@end smallexample
8215
8216@noindent
8217Thus the volume is 6316 cubic centimeters, within about 11 percent.
8218
8219@node Types Answer 8, Types Answer 9, Types Answer 7, Answers to Exercises
8220@subsection Types Tutorial Exercise 8
8221
8222@noindent
8223The first answer is pretty simple: @samp{1 / (0 .. 10) = (0.1 .. inf)}.
8224Since a number in the interval @samp{(0 .. 10)} can get arbitrarily
8225close to zero, its reciprocal can get arbitrarily large, so the answer
8226is an interval that effectively means, ``any number greater than 0.1''
8227but with no upper bound.
8228
8229The second answer, similarly, is @samp{1 / (-10 .. 0) = (-inf .. -0.1)}.
8230
8231Calc normally treats division by zero as an error, so that the formula
8232@w{@samp{1 / 0}} is left unsimplified. Our third problem,
8233@w{@samp{1 / [0 .. 10]}}, also (potentially) divides by zero because zero
8234is now a member of the interval. So Calc leaves this one unevaluated, too.
8235
8236If you turn on Infinite mode by pressing @kbd{m i}, you will
8237instead get the answer @samp{[0.1 .. inf]}, which includes infinity
8238as a possible value.
8239
8240The fourth calculation, @samp{1 / (-10 .. 10)}, has the same problem.
8241Zero is buried inside the interval, but it's still a possible value.
8242It's not hard to see that the actual result of @samp{1 / (-10 .. 10)}
8243will be either greater than @mathit{0.1}, or less than @mathit{-0.1}. Thus
8244the interval goes from minus infinity to plus infinity, with a ``hole''
8245in it from @mathit{-0.1} to @mathit{0.1}. Calc doesn't have any way to
8246represent this, so it just reports @samp{[-inf .. inf]} as the answer.
8247It may be disappointing to hear ``the answer lies somewhere between
8248minus infinity and plus infinity, inclusive,'' but that's the best
8249that interval arithmetic can do in this case.
8250
8251@node Types Answer 9, Types Answer 10, Types Answer 8, Answers to Exercises
8252@subsection Types Tutorial Exercise 9
8253
8254@smallexample
8255@group
82561: [-3 .. 3] 2: [-3 .. 3] 2: [0 .. 9]
8257 . 1: [0 .. 9] 1: [-9 .. 9]
8258 . .
8259
8260 [ 3 n .. 3 ] @key{RET} 2 ^ @key{TAB} @key{RET} *
8261@end group
8262@end smallexample
8263
8264@noindent
8265In the first case the result says, ``if a number is between @mathit{-3} and
82663, its square is between 0 and 9.'' The second case says, ``the product
8267of two numbers each between @mathit{-3} and 3 is between @mathit{-9} and 9.''
8268
8269An interval form is not a number; it is a symbol that can stand for
8270many different numbers. Two identical-looking interval forms can stand
8271for different numbers.
8272
8273The same issue arises when you try to square an error form.
8274
8275@node Types Answer 10, Types Answer 11, Types Answer 9, Answers to Exercises
8276@subsection Types Tutorial Exercise 10
8277
8278@noindent
8279Testing the first number, we might arbitrarily choose 17 for @expr{x}.
8280
8281@smallexample
8282@group
82831: 17 mod 811749613 2: 17 mod 811749613 1: 533694123 mod 811749613
8284 . 811749612 .
8285 .
8286
8287 17 M 811749613 @key{RET} 811749612 ^
8288@end group
8289@end smallexample
8290
8291@noindent
8292Since 533694123 is (considerably) different from 1, the number 811749613
8293must not be prime.
8294
8295It's awkward to type the number in twice as we did above. There are
8296various ways to avoid this, and algebraic entry is one. In fact, using
8297a vector mapping operation we can perform several tests at once. Let's
8298use this method to test the second number.
8299
8300@smallexample
8301@group
83022: [17, 42, 100000] 1: [1 mod 15485863, 1 mod ... ]
83031: 15485863 .
8304 .
8305
8306 [17 42 100000] 15485863 @key{RET} V M ' ($$ mod $)^($-1) @key{RET}
8307@end group
8308@end smallexample
8309
8310@noindent
8311The result is three ones (modulo @expr{n}), so it's very probable that
831215485863 is prime. (In fact, this number is the millionth prime.)
8313
8314Note that the functions @samp{($$^($-1)) mod $} or @samp{$$^($-1) % $}
8315would have been hopelessly inefficient, since they would have calculated
8316the power using full integer arithmetic.
8317
8318Calc has a @kbd{k p} command that does primality testing. For small
8319numbers it does an exact test; for large numbers it uses a variant
8320of the Fermat test we used here. You can use @kbd{k p} repeatedly
8321to prove that a large integer is prime with any desired probability.
8322
8323@node Types Answer 11, Types Answer 12, Types Answer 10, Answers to Exercises
8324@subsection Types Tutorial Exercise 11
8325
8326@noindent
8327There are several ways to insert a calculated number into an HMS form.
8328One way to convert a number of seconds to an HMS form is simply to
8329multiply the number by an HMS form representing one second:
8330
8331@smallexample
8332@group
83331: 31415926.5359 2: 31415926.5359 1: 8726@@ 38' 46.5359"
8334 . 1: 0@@ 0' 1" .
8335 .
8336
8337 P 1e7 * 0@@ 0' 1" *
8338
8339@end group
8340@end smallexample
8341@noindent
8342@smallexample
8343@group
83442: 8726@@ 38' 46.5359" 1: 6@@ 6' 2.5359" mod 24@@ 0' 0"
83451: 15@@ 27' 16" mod 24@@ 0' 0" .
8346 .
8347
8348 x time @key{RET} +
8349@end group
8350@end smallexample
8351
8352@noindent
8353It will be just after six in the morning.
8354
8355The algebraic @code{hms} function can also be used to build an
8356HMS form:
8357
8358@smallexample
8359@group
83601: hms(0, 0, 10000000. pi) 1: 8726@@ 38' 46.5359"
8361 . .
8362
8363 ' hms(0, 0, 1e7 pi) @key{RET} =
8364@end group
8365@end smallexample
8366
8367@noindent
8368The @kbd{=} key is necessary to evaluate the symbol @samp{pi} to
8369the actual number 3.14159...
8370
8371@node Types Answer 12, Types Answer 13, Types Answer 11, Answers to Exercises
8372@subsection Types Tutorial Exercise 12
8373
8374@noindent
8375As we recall, there are 17 songs of about 2 minutes and 47 seconds
8376each.
8377
8378@smallexample
8379@group
83802: 0@@ 2' 47" 1: [0@@ 3' 7" .. 0@@ 3' 47"]
83811: [0@@ 0' 20" .. 0@@ 1' 0"] .
8382 .
8383
8384 [ 0@@ 20" .. 0@@ 1' ] +
8385
8386@end group
8387@end smallexample
8388@noindent
8389@smallexample
8390@group
83911: [0@@ 52' 59." .. 1@@ 4' 19."]
8392 .
8393
8394 17 *
8395@end group
8396@end smallexample
8397
8398@noindent
8399No matter how long it is, the album will fit nicely on one CD.
8400
8401@node Types Answer 13, Types Answer 14, Types Answer 12, Answers to Exercises
8402@subsection Types Tutorial Exercise 13
8403
8404@noindent
8405Type @kbd{' 1 yr @key{RET} u c s @key{RET}}. The answer is 31557600 seconds.
8406
8407@node Types Answer 14, Types Answer 15, Types Answer 13, Answers to Exercises
8408@subsection Types Tutorial Exercise 14
8409
8410@noindent
8411How long will it take for a signal to get from one end of the computer
8412to the other?
8413
8414@smallexample
8415@group
84161: m / c 1: 3.3356 ns
8417 . .
8418
8419 ' 1 m / c @key{RET} u c ns @key{RET}
8420@end group
8421@end smallexample
8422
8423@noindent
8424(Recall, @samp{c} is a ``unit'' corresponding to the speed of light.)
8425
8426@smallexample
8427@group
d2bd74ff
JB
84281: 3.3356 ns 1: 0.81356
84292: 4.1 ns .
4009494e
GM
8430 .
8431
d2bd74ff 8432 ' 4.1 ns @key{RET} /
4009494e
GM
8433@end group
8434@end smallexample
8435
8436@noindent
8437Thus a signal could take up to 81 percent of a clock cycle just to
8438go from one place to another inside the computer, assuming the signal
8439could actually attain the full speed of light. Pretty tight!
8440
8441@node Types Answer 15, Algebra Answer 1, Types Answer 14, Answers to Exercises
8442@subsection Types Tutorial Exercise 15
8443
8444@noindent
8445The speed limit is 55 miles per hour on most highways. We want to
8446find the ratio of Sam's speed to the US speed limit.
8447
8448@smallexample
8449@group
84501: 55 mph 2: 55 mph 3: 11 hr mph / yd
8451 . 1: 5 yd / hr .
8452 .
8453
8454 ' 55 mph @key{RET} ' 5 yd/hr @key{RET} /
8455@end group
8456@end smallexample
8457
8458The @kbd{u s} command cancels out these units to get a plain
8459number. Now we take the logarithm base two to find the final
8460answer, assuming that each successive pill doubles his speed.
8461
8462@smallexample
8463@group
84641: 19360. 2: 19360. 1: 14.24
8465 . 1: 2 .
8466 .
8467
8468 u s 2 B
8469@end group
8470@end smallexample
8471
8472@noindent
8473Thus Sam can take up to 14 pills without a worry.
8474
8475@node Algebra Answer 1, Algebra Answer 2, Types Answer 15, Answers to Exercises
8476@subsection Algebra Tutorial Exercise 1
8477
8478@noindent
8479@c [fix-ref Declarations]
8480The result @samp{sqrt(x)^2} is simplified back to @expr{x} by the
8481Calculator, but @samp{sqrt(x^2)} is not. (Consider what happens
8482if @w{@expr{x = -4}}.) If @expr{x} is real, this formula could be
8483simplified to @samp{abs(x)}, but for general complex arguments even
8484that is not safe. (@xref{Declarations}, for a way to tell Calc
8485that @expr{x} is known to be real.)
8486
8487@node Algebra Answer 2, Algebra Answer 3, Algebra Answer 1, Answers to Exercises
8488@subsection Algebra Tutorial Exercise 2
8489
8490@noindent
8491Suppose our roots are @expr{[a, b, c]}. We want a polynomial which
8492is zero when @expr{x} is any of these values. The trivial polynomial
8493@expr{x-a} is zero when @expr{x=a}, so the product @expr{(x-a)(x-b)(x-c)}
8494will do the job. We can use @kbd{a c x} to write this in a more
8495familiar form.
8496
8497@smallexample
8498@group
84991: 34 x - 24 x^3 1: [1.19023, -1.19023, 0]
8500 . .
8501
8502 r 2 a P x @key{RET}
8503
8504@end group
8505@end smallexample
8506@noindent
8507@smallexample
8508@group
d2bd74ff 85091: [x - 1.19023, x + 1.19023, x] 1: x*(x + 1.19023) (x - 1.19023)
4009494e
GM
8510 . .
8511
8512 V M ' x-$ @key{RET} V R *
8513
8514@end group
8515@end smallexample
8516@noindent
8517@smallexample
8518@group
85191: x^3 - 1.41666 x 1: 34 x - 24 x^3
8520 . .
8521
8522 a c x @key{RET} 24 n * a x
8523@end group
8524@end smallexample
8525
8526@noindent
8527Sure enough, our answer (multiplied by a suitable constant) is the
8528same as the original polynomial.
8529
8530@node Algebra Answer 3, Algebra Answer 4, Algebra Answer 2, Answers to Exercises
8531@subsection Algebra Tutorial Exercise 3
8532
8533@smallexample
8534@group
d2bd74ff 85351: x sin(pi x) 1: sin(pi x) / pi^2 - x cos(pi x) / pi
4009494e
GM
8536 . .
8537
8538 ' x sin(pi x) @key{RET} m r a i x @key{RET}
8539
8540@end group
8541@end smallexample
8542@noindent
8543@smallexample
8544@group
85451: [y, 1]
d2bd74ff 85462: sin(pi x) / pi^2 - x cos(pi x) / pi
4009494e
GM
8547 .
8548
8549 ' [y,1] @key{RET} @key{TAB}
8550
8551@end group
8552@end smallexample
8553@noindent
8554@smallexample
8555@group
d2bd74ff 85561: [sin(pi y) / pi^2 - y cos(pi y) / pi, 1 / pi]
4009494e
GM
8557 .
8558
8559 V M $ @key{RET}
8560
8561@end group
8562@end smallexample
8563@noindent
8564@smallexample
8565@group
d2bd74ff 85661: sin(pi y) / pi^2 - y cos(pi y) / pi - 1 / pi
4009494e
GM
8567 .
8568
8569 V R -
8570
8571@end group
8572@end smallexample
8573@noindent
8574@smallexample
8575@group
d2bd74ff 85761: sin(3.14159 y) / 9.8696 - y cos(3.14159 y) / 3.14159 - 0.3183
4009494e
GM
8577 .
8578
8579 =
8580
8581@end group
8582@end smallexample
8583@noindent
8584@smallexample
8585@group
85861: [0., -0.95493, 0.63662, -1.5915, 1.2732]
8587 .
8588
8589 v x 5 @key{RET} @key{TAB} V M $ @key{RET}
8590@end group
8591@end smallexample
8592
8593@node Algebra Answer 4, Rewrites Answer 1, Algebra Answer 3, Answers to Exercises
8594@subsection Algebra Tutorial Exercise 4
8595
8596@noindent
8597The hard part is that @kbd{V R +} is no longer sufficient to add up all
8598the contributions from the slices, since the slices have varying
8599coefficients. So first we must come up with a vector of these
8600coefficients. Here's one way:
8601
8602@smallexample
8603@group
86042: -1 2: 3 1: [4, 2, ..., 4]
86051: [1, 2, ..., 9] 1: [-1, 1, ..., -1] .
8606 . .
8607
8608 1 n v x 9 @key{RET} V M ^ 3 @key{TAB} -
8609
8610@end group
8611@end smallexample
8612@noindent
8613@smallexample
8614@group
86151: [4, 2, ..., 4, 1] 1: [1, 4, 2, ..., 4, 1]
8616 . .
8617
8618 1 | 1 @key{TAB} |
8619@end group
8620@end smallexample
8621
8622@noindent
8623Now we compute the function values. Note that for this method we need
8624eleven values, including both endpoints of the desired interval.
8625
8626@smallexample
8627@group
86282: [1, 4, 2, ..., 4, 1]
86291: [1, 1.1, 1.2, ... , 1.8, 1.9, 2.]
8630 .
8631
8632 11 @key{RET} 1 @key{RET} .1 @key{RET} C-u v x
8633
8634@end group
8635@end smallexample
8636@noindent
8637@smallexample
8638@group
86392: [1, 4, 2, ..., 4, 1]
86401: [0., 0.084941, 0.16993, ... ]
8641 .
8642
8643 ' sin(x) ln(x) @key{RET} m r p 5 @key{RET} V M $ @key{RET}
8644@end group
8645@end smallexample
8646
8647@noindent
8648Once again this calls for @kbd{V M * V R +}; a simple @kbd{*} does the
8649same thing.
8650
8651@smallexample
8652@group
86531: 11.22 1: 1.122 1: 0.374
8654 . . .
8655
8656 * .1 * 3 /
8657@end group
8658@end smallexample
8659
8660@noindent
8661Wow! That's even better than the result from the Taylor series method.
8662
8663@node Rewrites Answer 1, Rewrites Answer 2, Algebra Answer 4, Answers to Exercises
8664@subsection Rewrites Tutorial Exercise 1
8665
8666@noindent
8667We'll use Big mode to make the formulas more readable.
8668
8669@smallexample
8670@group
d2bd74ff
JB
8671 ___
8672 V 2 + 2
86731: (2 + sqrt(2)) / (1 + sqrt(2)) 1: ---------
8674 . ___
8675 V 2 + 1
4009494e
GM
8676
8677 .
8678
8679 ' (2+sqrt(2)) / (1+sqrt(2)) @key{RET} d B
8680@end group
8681@end smallexample
8682
8683@noindent
8684Multiplying by the conjugate helps because @expr{(a+b) (a-b) = a^2 - b^2}.
8685
8686@smallexample
8687@group
8688 ___ ___
86891: (2 + V 2 ) (V 2 - 1)
8690 .
8691
8692 a r a/(b+c) := a*(b-c) / (b^2-c^2) @key{RET}
8693
8694@end group
8695@end smallexample
8696@noindent
8697@smallexample
8698@group
d2bd74ff
JB
8699 ___
87001: V 2
8701 .
4009494e 8702
d2bd74ff 8703 a r a*(b+c) := a*b + a*c
4009494e
GM
8704@end group
8705@end smallexample
8706
8707@noindent
8708(We could have used @kbd{a x} instead of a rewrite rule for the
8709second step.)
8710
8711The multiply-by-conjugate rule turns out to be useful in many
8712different circumstances, such as when the denominator involves
8713sines and cosines or the imaginary constant @code{i}.
8714
8715@node Rewrites Answer 2, Rewrites Answer 3, Rewrites Answer 1, Answers to Exercises
8716@subsection Rewrites Tutorial Exercise 2
8717
8718@noindent
8719Here is the rule set:
8720
8721@smallexample
8722@group
8723[ fib(n) := fib(n, 1, 1) :: integer(n) :: n >= 1,
8724 fib(1, x, y) := x,
8725 fib(n, x, y) := fib(n-1, y, x+y) ]
8726@end group
8727@end smallexample
8728
8729@noindent
8730The first rule turns a one-argument @code{fib} that people like to write
8731into a three-argument @code{fib} that makes computation easier. The
8732second rule converts back from three-argument form once the computation
8733is done. The third rule does the computation itself. It basically
8734says that if @expr{x} and @expr{y} are two consecutive Fibonacci numbers,
8735then @expr{y} and @expr{x+y} are the next (overlapping) pair of Fibonacci
8736numbers.
8737
8738Notice that because the number @expr{n} was ``validated'' by the
8739conditions on the first rule, there is no need to put conditions on
8740the other rules because the rule set would never get that far unless
8741the input were valid. That further speeds computation, since no
8742extra conditions need to be checked at every step.
8743
8744Actually, a user with a nasty sense of humor could enter a bad
8745three-argument @code{fib} call directly, say, @samp{fib(0, 1, 1)},
8746which would get the rules into an infinite loop. One thing that would
8747help keep this from happening by accident would be to use something like
8748@samp{ZzFib} instead of @code{fib} as the name of the three-argument
8749function.
8750
8751@node Rewrites Answer 3, Rewrites Answer 4, Rewrites Answer 2, Answers to Exercises
8752@subsection Rewrites Tutorial Exercise 3
8753
8754@noindent
8755He got an infinite loop. First, Calc did as expected and rewrote
8756@w{@samp{2 + 3 x}} to @samp{f(2, 3, x)}. Then it looked for ways to
8757apply the rule again, and found that @samp{f(2, 3, x)} looks like
8758@samp{a + b x} with @w{@samp{a = 0}} and @samp{b = 1}, so it rewrote to
8759@samp{f(0, 1, f(2, 3, x))}. It then wrapped another @samp{f(0, 1, ...)}
8760around that, and so on, ad infinitum. Joe should have used @kbd{M-1 a r}
8761to make sure the rule applied only once.
8762
8763(Actually, even the first step didn't work as he expected. What Calc
8764really gives for @kbd{M-1 a r} in this situation is @samp{f(3 x, 1, 2)},
8765treating 2 as the ``variable,'' and @samp{3 x} as a constant being added
8766to it. While this may seem odd, it's just as valid a solution as the
8767``obvious'' one. One way to fix this would be to add the condition
8768@samp{:: variable(x)} to the rule, to make sure the thing that matches
8769@samp{x} is indeed a variable, or to change @samp{x} to @samp{quote(x)}
8770on the lefthand side, so that the rule matches the actual variable
8771@samp{x} rather than letting @samp{x} stand for something else.)
8772
8773@node Rewrites Answer 4, Rewrites Answer 5, Rewrites Answer 3, Answers to Exercises
8774@subsection Rewrites Tutorial Exercise 4
8775
8776@noindent
8777@ignore
8778@starindex
8779@end ignore
8780@tindex seq
8781Here is a suitable set of rules to solve the first part of the problem:
8782
8783@smallexample
8784@group
8785[ seq(n, c) := seq(n/2, c+1) :: n%2 = 0,
8786 seq(n, c) := seq(3n+1, c+1) :: n%2 = 1 :: n > 1 ]
8787@end group
8788@end smallexample
8789
8790Given the initial formula @samp{seq(6, 0)}, application of these
8791rules produces the following sequence of formulas:
8792
8793@example
8794seq( 3, 1)
8795seq(10, 2)
8796seq( 5, 3)
8797seq(16, 4)
8798seq( 8, 5)
8799seq( 4, 6)
8800seq( 2, 7)
8801seq( 1, 8)
8802@end example
8803
8804@noindent
8805whereupon neither of the rules match, and rewriting stops.
8806
8807We can pretty this up a bit with a couple more rules:
8808
8809@smallexample
8810@group
8811[ seq(n) := seq(n, 0),
8812 seq(1, c) := c,
8813 ... ]
8814@end group
8815@end smallexample
8816
8817@noindent
8818Now, given @samp{seq(6)} as the starting configuration, we get 8
8819as the result.
8820
8821The change to return a vector is quite simple:
8822
8823@smallexample
8824@group
8825[ seq(n) := seq(n, []) :: integer(n) :: n > 0,
8826 seq(1, v) := v | 1,
8827 seq(n, v) := seq(n/2, v | n) :: n%2 = 0,
8828 seq(n, v) := seq(3n+1, v | n) :: n%2 = 1 ]
8829@end group
8830@end smallexample
8831
8832@noindent
8833Given @samp{seq(6)}, the result is @samp{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
8834
8835Notice that the @expr{n > 1} guard is no longer necessary on the last
8836rule since the @expr{n = 1} case is now detected by another rule.
8837But a guard has been added to the initial rule to make sure the
8838initial value is suitable before the computation begins.
8839
8840While still a good idea, this guard is not as vitally important as it
8841was for the @code{fib} function, since calling, say, @samp{seq(x, [])}
8842will not get into an infinite loop. Calc will not be able to prove
8843the symbol @samp{x} is either even or odd, so none of the rules will
8844apply and the rewrites will stop right away.
8845
8846@node Rewrites Answer 5, Rewrites Answer 6, Rewrites Answer 4, Answers to Exercises
8847@subsection Rewrites Tutorial Exercise 5
8848
8849@noindent
8850@ignore
8851@starindex
8852@end ignore
8853@tindex nterms
8854If @expr{x} is the sum @expr{a + b}, then `@tfn{nterms(}@var{x}@tfn{)}' must
8855be `@tfn{nterms(}@var{a}@tfn{)}' plus `@tfn{nterms(}@var{b}@tfn{)}'. If @expr{x}
8856is not a sum, then `@tfn{nterms(}@var{x}@tfn{)}' = 1.
8857
8858@smallexample
8859@group
8860[ nterms(a + b) := nterms(a) + nterms(b),
8861 nterms(x) := 1 ]
8862@end group
8863@end smallexample
8864
8865@noindent
8866Here we have taken advantage of the fact that earlier rules always
8867match before later rules; @samp{nterms(x)} will only be tried if we
8868already know that @samp{x} is not a sum.
8869
8870@node Rewrites Answer 6, Programming Answer 1, Rewrites Answer 5, Answers to Exercises
8871@subsection Rewrites Tutorial Exercise 6
8872
8873@noindent
8874Here is a rule set that will do the job:
8875
8876@smallexample
8877@group
8878[ a*(b + c) := a*b + a*c,
8879 opt(a) O(x^n) + opt(b) O(x^m) := O(x^n) :: n <= m
8880 :: constant(a) :: constant(b),
8881 opt(a) O(x^n) + opt(b) x^m := O(x^n) :: n <= m
8882 :: constant(a) :: constant(b),
8883 a O(x^n) := O(x^n) :: constant(a),
8884 x^opt(m) O(x^n) := O(x^(n+m)),
8885 O(x^n) O(x^m) := O(x^(n+m)) ]
8886@end group
8887@end smallexample
8888
8889If we really want the @kbd{+} and @kbd{*} keys to operate naturally
8890on power series, we should put these rules in @code{EvalRules}. For
8891testing purposes, it is better to put them in a different variable,
8892say, @code{O}, first.
8893
8894The first rule just expands products of sums so that the rest of the
8895rules can assume they have an expanded-out polynomial to work with.
8896Note that this rule does not mention @samp{O} at all, so it will
8897apply to any product-of-sum it encounters---this rule may surprise
8898you if you put it into @code{EvalRules}!
8899
8900In the second rule, the sum of two O's is changed to the smaller O.
8901The optional constant coefficients are there mostly so that
8902@samp{O(x^2) - O(x^3)} and @samp{O(x^3) - O(x^2)} are handled
8903as well as @samp{O(x^2) + O(x^3)}.
8904
8905The third rule absorbs higher powers of @samp{x} into O's.
8906
8907The fourth rule says that a constant times a negligible quantity
8908is still negligible. (This rule will also match @samp{O(x^3) / 4},
8909with @samp{a = 1/4}.)
8910
8911The fifth rule rewrites, for example, @samp{x^2 O(x^3)} to @samp{O(x^5)}.
8912(It is easy to see that if one of these forms is negligible, the other
8913is, too.) Notice the @samp{x^opt(m)} to pick up terms like
8914@w{@samp{x O(x^3)}}. Optional powers will match @samp{x} as @samp{x^1}
8915but not 1 as @samp{x^0}. This turns out to be exactly what we want here.
8916
8917The sixth rule is the corresponding rule for products of two O's.
8918
8919Another way to solve this problem would be to create a new ``data type''
8920that represents truncated power series. We might represent these as
8921function calls @samp{series(@var{coefs}, @var{x})} where @var{coefs} is
8922a vector of coefficients for @expr{x^0}, @expr{x^1}, @expr{x^2}, and so
8923on. Rules would exist for sums and products of such @code{series}
8924objects, and as an optional convenience could also know how to combine a
8925@code{series} object with a normal polynomial. (With this, and with a
8926rule that rewrites @samp{O(x^n)} to the equivalent @code{series} form,
8927you could still enter power series in exactly the same notation as
8928before.) Operations on such objects would probably be more efficient,
8929although the objects would be a bit harder to read.
8930
8931@c [fix-ref Compositions]
8932Some other symbolic math programs provide a power series data type
8933similar to this. Mathematica, for example, has an object that looks
8934like @samp{PowerSeries[@var{x}, @var{x0}, @var{coefs}, @var{nmin},
8935@var{nmax}, @var{den}]}, where @var{x0} is the point about which the
8936power series is taken (we've been assuming this was always zero),
8937and @var{nmin}, @var{nmax}, and @var{den} allow pseudo-power-series
8938with fractional or negative powers. Also, the @code{PowerSeries}
8939objects have a special display format that makes them look like
8940@samp{2 x^2 + O(x^4)} when they are printed out. (@xref{Compositions},
8941for a way to do this in Calc, although for something as involved as
8942this it would probably be better to write the formatting routine
8943in Lisp.)
8944
8945@node Programming Answer 1, Programming Answer 2, Rewrites Answer 6, Answers to Exercises
8946@subsection Programming Tutorial Exercise 1
8947
8948@noindent
8949Just enter the formula @samp{ninteg(sin(t)/t, t, 0, x)}, type
8950@kbd{Z F}, and answer the questions. Since this formula contains two
8951variables, the default argument list will be @samp{(t x)}. We want to
8952change this to @samp{(x)} since @expr{t} is really a dummy variable
8953to be used within @code{ninteg}.
8954
8955The exact keystrokes are @kbd{Z F s Si @key{RET} @key{RET} C-b C-b @key{DEL} @key{DEL} @key{RET} y}.
8956(The @kbd{C-b C-b @key{DEL} @key{DEL}} are what fix the argument list.)
8957
8958@node Programming Answer 2, Programming Answer 3, Programming Answer 1, Answers to Exercises
8959@subsection Programming Tutorial Exercise 2
8960
8961@noindent
8962One way is to move the number to the top of the stack, operate on
8963it, then move it back: @kbd{C-x ( M-@key{TAB} n M-@key{TAB} M-@key{TAB} C-x )}.
8964
8965Another way is to negate the top three stack entries, then negate
8966again the top two stack entries: @kbd{C-x ( M-3 n M-2 n C-x )}.
8967
8968Finally, it turns out that a negative prefix argument causes a
8969command like @kbd{n} to operate on the specified stack entry only,
8970which is just what we want: @kbd{C-x ( M-- 3 n C-x )}.
8971
8972Just for kicks, let's also do it algebraically:
8973@w{@kbd{C-x ( ' -$$$, $$, $ @key{RET} C-x )}}.
8974
8975@node Programming Answer 3, Programming Answer 4, Programming Answer 2, Answers to Exercises
8976@subsection Programming Tutorial Exercise 3
8977
8978@noindent
8979Each of these functions can be computed using the stack, or using
8980algebraic entry, whichever way you prefer:
8981
8982@noindent
40ba43b4 8983Computing
4009494e
GM
8984@texline @math{\displaystyle{\sin x \over x}}:
8985@infoline @expr{sin(x) / x}:
8986
8987Using the stack: @kbd{C-x ( @key{RET} S @key{TAB} / C-x )}.
8988
8989Using algebraic entry: @kbd{C-x ( ' sin($)/$ @key{RET} C-x )}.
8990
8991@noindent
8992Computing the logarithm:
8993
8994Using the stack: @kbd{C-x ( @key{TAB} B C-x )}
8995
8996Using algebraic entry: @kbd{C-x ( ' log($,$$) @key{RET} C-x )}.
8997
8998@noindent
8999Computing the vector of integers:
9000
9001Using the stack: @kbd{C-x ( 1 @key{RET} 1 C-u v x C-x )}. (Recall that
9002@kbd{C-u v x} takes the vector size, starting value, and increment
9003from the stack.)
9004
9005Alternatively: @kbd{C-x ( ~ v x C-x )}. (The @kbd{~} key pops a
9006number from the stack and uses it as the prefix argument for the
9007next command.)
9008
9009Using algebraic entry: @kbd{C-x ( ' index($) @key{RET} C-x )}.
9010
9011@node Programming Answer 4, Programming Answer 5, Programming Answer 3, Answers to Exercises
9012@subsection Programming Tutorial Exercise 4
9013
9014@noindent
9015Here's one way: @kbd{C-x ( @key{RET} V R + @key{TAB} v l / C-x )}.
9016
9017@node Programming Answer 5, Programming Answer 6, Programming Answer 4, Answers to Exercises
9018@subsection Programming Tutorial Exercise 5
9019
9020@smallexample
9021@group
90222: 1 1: 1.61803398502 2: 1.61803398502
90231: 20 . 1: 1.61803398875
9024 . .
9025
9026 1 @key{RET} 20 Z < & 1 + Z > I H P
9027@end group
9028@end smallexample
9029
9030@noindent
9031This answer is quite accurate.
9032
9033@node Programming Answer 6, Programming Answer 7, Programming Answer 5, Answers to Exercises
9034@subsection Programming Tutorial Exercise 6
9035
9036@noindent
9037Here is the matrix:
9038
9039@example
9040[ [ 0, 1 ] * [a, b] = [b, a + b]
9041 [ 1, 1 ] ]
9042@end example
9043
9044@noindent
9045Thus @samp{[0, 1; 1, 1]^n * [1, 1]} computes Fibonacci numbers @expr{n+1}
9046and @expr{n+2}. Here's one program that does the job:
9047
9048@example
9049C-x ( ' [0, 1; 1, 1] ^ ($-1) * [1, 1] @key{RET} v u @key{DEL} C-x )
9050@end example
9051
9052@noindent
9053This program is quite efficient because Calc knows how to raise a
40ba43b4 9054matrix (or other value) to the power @expr{n} in only
4009494e
GM
9055@texline @math{\log_2 n}
9056@infoline @expr{log(n,2)}
9057steps. For example, this program can compute the 1000th Fibonacci
9058number (a 209-digit integer!) in about 10 steps; even though the
9059@kbd{Z < ... Z >} solution had much simpler steps, it would have
9060required so many steps that it would not have been practical.
9061
9062@node Programming Answer 7, Programming Answer 8, Programming Answer 6, Answers to Exercises
9063@subsection Programming Tutorial Exercise 7
9064
9065@noindent
9066The trick here is to compute the harmonic numbers differently, so that
9067the loop counter itself accumulates the sum of reciprocals. We use
9068a separate variable to hold the integer counter.
9069
9070@smallexample
9071@group
90721: 1 2: 1 1: .
9073 . 1: 4
9074 .
9075
9076 1 t 1 1 @key{RET} 4 Z ( t 2 r 1 1 + s 1 & Z )
9077@end group
9078@end smallexample
9079
9080@noindent
9081The body of the loop goes as follows: First save the harmonic sum
9082so far in variable 2. Then delete it from the stack; the for loop
9083itself will take care of remembering it for us. Next, recall the
9084count from variable 1, add one to it, and feed its reciprocal to
9085the for loop to use as the step value. The for loop will increase
9086the ``loop counter'' by that amount and keep going until the
9087loop counter exceeds 4.
9088
9089@smallexample
9090@group
90912: 31 3: 31
90921: 3.99498713092 2: 3.99498713092
9093 . 1: 4.02724519544
9094 .
9095
9096 r 1 r 2 @key{RET} 31 & +
9097@end group
9098@end smallexample
9099
9100Thus we find that the 30th harmonic number is 3.99, and the 31st
9101harmonic number is 4.02.
9102
9103@node Programming Answer 8, Programming Answer 9, Programming Answer 7, Answers to Exercises
9104@subsection Programming Tutorial Exercise 8
9105
9106@noindent
9107The first step is to compute the derivative @expr{f'(x)} and thus
40ba43b4 9108the formula
4009494e
GM
9109@texline @math{\displaystyle{x - {f(x) \over f'(x)}}}.
9110@infoline @expr{x - f(x)/f'(x)}.
9111
9112(Because this definition is long, it will be repeated in concise form
9113below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
9114entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9115keystrokes without executing them. In the following diagrams we'll
9116pretend Calc actually executed the keystrokes as you typed them,
9117just for purposes of illustration.)
9118
9119@smallexample
9120@group
91212: sin(cos(x)) - 0.5 3: 4.5
91221: 4.5 2: sin(cos(x)) - 0.5
9123 . 1: -(sin(x) cos(cos(x)))
9124 .
9125
9126' sin(cos(x))-0.5 @key{RET} 4.5 m r C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET}
9127
9128@end group
9129@end smallexample
9130@noindent
9131@smallexample
9132@group
91332: 4.5
91341: x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x))
9135 .
9136
9137 / ' x @key{RET} @key{TAB} - t 1
9138@end group
9139@end smallexample
9140
9141Now, we enter the loop. We'll use a repeat loop with a 20-repetition
9142limit just in case the method fails to converge for some reason.
9143(Normally, the @w{@kbd{Z /}} command will stop the loop before all 20
9144repetitions are done.)
9145
9146@smallexample
9147@group
91481: 4.5 3: 4.5 2: 4.5
9149 . 2: x + (sin(cos(x)) ... 1: 5.24196456928
9150 1: 4.5 .
9151 .
9152
9153 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
9154@end group
9155@end smallexample
9156
9157This is the new guess for @expr{x}. Now we compare it with the
9158old one to see if we've converged.
9159
9160@smallexample
9161@group
91623: 5.24196 2: 5.24196 1: 5.24196 1: 5.26345856348
91632: 5.24196 1: 0 . .
91641: 4.5 .
9165 .
9166
9167 @key{RET} M-@key{TAB} a = Z / Z > Z ' C-x )
9168@end group
9169@end smallexample
9170
9171The loop converges in just a few steps to this value. To check
9172the result, we can simply substitute it back into the equation.
9173
9174@smallexample
9175@group
91762: 5.26345856348
91771: 0.499999999997
9178 .
9179
9180 @key{RET} ' sin(cos($)) @key{RET}
9181@end group
9182@end smallexample
9183
9184Let's test the new definition again:
9185
9186@smallexample
9187@group
91882: x^2 - 9 1: 3.
91891: 1 .
9190 .
9191
9192 ' x^2-9 @key{RET} 1 X
9193@end group
9194@end smallexample
9195
9196Once again, here's the full Newton's Method definition:
9197
9198@example
9199@group
9200C-x ( Z ` @key{TAB} @key{RET} a d x @key{RET} / ' x @key{RET} @key{TAB} - t 1
9201 20 Z < @key{RET} r 1 @key{TAB} s l x @key{RET}
9202 @key{RET} M-@key{TAB} a = Z /
9203 Z >
9204 Z '
9205C-x )
9206@end group
9207@end example
9208
9209@c [fix-ref Nesting and Fixed Points]
9210It turns out that Calc has a built-in command for applying a formula
9211repeatedly until it converges to a number. @xref{Nesting and Fixed Points},
9212to see how to use it.
9213
9214@c [fix-ref Root Finding]
9215Also, of course, @kbd{a R} is a built-in command that uses Newton's
9216method (among others) to look for numerical solutions to any equation.
9217@xref{Root Finding}.
9218
9219@node Programming Answer 9, Programming Answer 10, Programming Answer 8, Answers to Exercises
9220@subsection Programming Tutorial Exercise 9
9221
9222@noindent
9223The first step is to adjust @expr{z} to be greater than 5. A simple
9224``for'' loop will do the job here. If @expr{z} is less than 5, we
40ba43b4 9225reduce the problem using
4009494e
GM
9226@texline @math{\psi(z) = \psi(z+1) - 1/z}.
9227@infoline @expr{psi(z) = psi(z+1) - 1/z}. We go
40ba43b4 9228on to compute
4009494e 9229@texline @math{\psi(z+1)},
40ba43b4 9230@infoline @expr{psi(z+1)},
4009494e
GM
9231and remember to add back a factor of @expr{-1/z} when we're done. This
9232step is repeated until @expr{z > 5}.
9233
9234(Because this definition is long, it will be repeated in concise form
9235below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
9236entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9237keystrokes without executing them. In the following diagrams we'll
9238pretend Calc actually executed the keystrokes as you typed them,
9239just for purposes of illustration.)
9240
9241@smallexample
9242@group
92431: 1. 1: 1.
9244 . .
9245
9246 1.0 @key{RET} C-x ( Z ` s 1 0 t 2
9247@end group
9248@end smallexample
9249
9250Here, variable 1 holds @expr{z} and variable 2 holds the adjustment
9251factor. If @expr{z < 5}, we use a loop to increase it.
9252
9253(By the way, we started with @samp{1.0} instead of the integer 1 because
9254otherwise the calculation below will try to do exact fractional arithmetic,
9255and will never converge because fractions compare equal only if they
9256are exactly equal, not just equal to within the current precision.)
9257
9258@smallexample
9259@group
92603: 1. 2: 1. 1: 6.
92612: 1. 1: 1 .
92621: 5 .
9263 .
9264
9265 @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9266@end group
9267@end smallexample
9268
40ba43b4 9269Now we compute the initial part of the sum:
4009494e
GM
9270@texline @math{\ln z - {1 \over 2z}}
9271@infoline @expr{ln(z) - 1/2z}
9272minus the adjustment factor.
9273
9274@smallexample
9275@group
92762: 1.79175946923 2: 1.7084261359 1: -0.57490719743
92771: 0.0833333333333 1: 2.28333333333 .
9278 . .
9279
9280 L r 1 2 * & - r 2 -
9281@end group
9282@end smallexample
9283
9284Now we evaluate the series. We'll use another ``for'' loop counting
9285up the value of @expr{2 n}. (Calc does have a summation command,
9286@kbd{a +}, but we'll use loops just to get more practice with them.)
9287
9288@smallexample
9289@group
92903: -0.5749 3: -0.5749 4: -0.5749 2: -0.5749
92912: 2 2: 1:6 3: 1:6 1: 2.3148e-3
92921: 40 1: 2 2: 2 .
9293 . . 1: 36.
9294 .
9295
9296 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
9297
9298@end group
9299@end smallexample
9300@noindent
9301@smallexample
9302@group
93033: -0.5749 3: -0.5772 2: -0.5772 1: -0.577215664892
93042: -0.5749 2: -0.5772 1: 0 .
93051: 2.3148e-3 1: -0.5749 .
9306 . .
9307
9308 @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z / 2 Z ) Z ' C-x )
9309@end group
9310@end smallexample
9311
40ba43b4 9312This is the value of
4009494e 9313@texline @math{-\gamma},
40ba43b4 9314@infoline @expr{- gamma},
4009494e
GM
9315with a slight bit of roundoff error. To get a full 12 digits, let's use
9316a higher precision:
9317
9318@smallexample
9319@group
93202: -0.577215664892 2: -0.577215664892
93211: 1. 1: -0.577215664901532
9322
9323 1. @key{RET} p 16 @key{RET} X
9324@end group
9325@end smallexample
9326
9327Here's the complete sequence of keystrokes:
9328
9329@example
9330@group
9331C-x ( Z ` s 1 0 t 2
9332 @key{RET} 5 a < Z [ 5 Z ( & s + 2 1 s + 1 1 Z ) r 1 Z ]
9333 L r 1 2 * & - r 2 -
9334 2 @key{RET} 40 Z ( @key{RET} k b @key{TAB} @key{RET} r 1 @key{TAB} ^ * /
9335 @key{TAB} @key{RET} M-@key{TAB} - @key{RET} M-@key{TAB} a = Z /
9336 2 Z )
9337 Z '
9338C-x )
9339@end group
9340@end example
9341
9342@node Programming Answer 10, Programming Answer 11, Programming Answer 9, Answers to Exercises
9343@subsection Programming Tutorial Exercise 10
9344
9345@noindent
9346Taking the derivative of a term of the form @expr{x^n} will produce
40ba43b4 9347a term like
4009494e 9348@texline @math{n x^{n-1}}.
40ba43b4 9349@infoline @expr{n x^(n-1)}.
4009494e
GM
9350Taking the derivative of a constant
9351produces zero. From this it is easy to see that the @expr{n}th
9352derivative of a polynomial, evaluated at @expr{x = 0}, will equal the
9353coefficient on the @expr{x^n} term times @expr{n!}.
9354
9355(Because this definition is long, it will be repeated in concise form
9356below. You can use @w{@kbd{C-x * m}} to load it from there. While you are
9357entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9358keystrokes without executing them. In the following diagrams we'll
9359pretend Calc actually executed the keystrokes as you typed them,
9360just for purposes of illustration.)
9361
9362@smallexample
9363@group
93642: 5 x^4 + (x + 1)^2 3: 5 x^4 + (x + 1)^2
93651: 6 2: 0
9366 . 1: 6
9367 .
9368
9369 ' 5 x^4 + (x+1)^2 @key{RET} 6 C-x ( Z ` [ ] t 1 0 @key{TAB}
9370@end group
9371@end smallexample
9372
9373@noindent
9374Variable 1 will accumulate the vector of coefficients.
9375
9376@smallexample
9377@group
93782: 0 3: 0 2: 5 x^4 + ...
93791: 5 x^4 + ... 2: 5 x^4 + ... 1: 1
9380 . 1: 1 .
9381 .
9382
9383 Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
9384@end group
9385@end smallexample
9386
9387@noindent
9388Note that @kbd{s | 1} appends the top-of-stack value to the vector
9389in a variable; it is completely analogous to @kbd{s + 1}. We could
9390have written instead, @kbd{r 1 @key{TAB} | t 1}.
9391
9392@smallexample
9393@group
93941: 20 x^3 + 2 x + 2 1: 0 1: [1, 2, 1, 0, 5, 0, 0]
9395 . . .
9396
9397 a d x @key{RET} 1 Z ) @key{DEL} r 1 Z ' C-x )
9398@end group
9399@end smallexample
9400
9401To convert back, a simple method is just to map the coefficients
9402against a table of powers of @expr{x}.
9403
9404@smallexample
9405@group
94062: [1, 2, 1, 0, 5, 0, 0] 2: [1, 2, 1, 0, 5, 0, 0]
94071: 6 1: [0, 1, 2, 3, 4, 5, 6]
9408 . .
9409
9410 6 @key{RET} 1 + 0 @key{RET} 1 C-u v x
9411
9412@end group
9413@end smallexample
9414@noindent
9415@smallexample
9416@group
94172: [1, 2, 1, 0, 5, 0, 0] 2: 1 + 2 x + x^2 + 5 x^4
94181: [1, x, x^2, x^3, ... ] .
9419 .
9420
9421 ' x @key{RET} @key{TAB} V M ^ *
9422@end group
9423@end smallexample
9424
9425Once again, here are the whole polynomial to/from vector programs:
9426
9427@example
9428@group
9429C-x ( Z ` [ ] t 1 0 @key{TAB}
9430 Z ( @key{TAB} @key{RET} 0 s l x @key{RET} M-@key{TAB} ! / s | 1
9431 a d x @key{RET}
9432 1 Z ) r 1
9433 Z '
9434C-x )
9435
9436C-x ( 1 + 0 @key{RET} 1 C-u v x ' x @key{RET} @key{TAB} V M ^ * C-x )
9437@end group
9438@end example
9439
9440@node Programming Answer 11, Programming Answer 12, Programming Answer 10, Answers to Exercises
9441@subsection Programming Tutorial Exercise 11
9442
9443@noindent
9444First we define a dummy program to go on the @kbd{z s} key. The true
9445@w{@kbd{z s}} key is supposed to take two numbers from the stack and
9446return one number, so @key{DEL} as a dummy definition will make
9447sure the stack comes out right.
9448
9449@smallexample
9450@group
94512: 4 1: 4 2: 4
94521: 2 . 1: 2
9453 . .
9454
9455 4 @key{RET} 2 C-x ( @key{DEL} C-x ) Z K s @key{RET} 2
9456@end group
9457@end smallexample
9458
9459The last step replaces the 2 that was eaten during the creation
9460of the dummy @kbd{z s} command. Now we move on to the real
9461definition. The recurrence needs to be rewritten slightly,
9462to the form @expr{s(n,m) = s(n-1,m-1) - (n-1) s(n-1,m)}.
9463
9464(Because this definition is long, it will be repeated in concise form
9465below. You can use @kbd{C-x * m} to load it from there.)
9466
9467@smallexample
9468@group
94692: 4 4: 4 3: 4 2: 4
94701: 2 3: 2 2: 2 1: 2
9471 . 2: 4 1: 0 .
9472 1: 2 .
9473 .
9474
9475 C-x ( M-2 @key{RET} a = Z [ @key{DEL} @key{DEL} 1 Z :
9476
9477@end group
9478@end smallexample
9479@noindent
9480@smallexample
9481@group
94824: 4 2: 4 2: 3 4: 3 4: 3 3: 3
94833: 2 1: 2 1: 2 3: 2 3: 2 2: 2
94842: 2 . . 2: 3 2: 3 1: 3
94851: 0 1: 2 1: 1 .
9486 . . .
9487
9488 @key{RET} 0 a = Z [ @key{DEL} @key{DEL} 0 Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
9489@end group
9490@end smallexample
9491
9492@noindent
9493(Note that the value 3 that our dummy @kbd{z s} produces is not correct;
9494it is merely a placeholder that will do just as well for now.)
9495
9496@smallexample
9497@group
94983: 3 4: 3 3: 3 2: 3 1: -6
94992: 3 3: 3 2: 3 1: 9 .
95001: 2 2: 3 1: 3 .
9501 . 1: 2 .
9502 .
9503
9504 M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
9505
9506@end group
9507@end smallexample
9508@noindent
9509@smallexample
9510@group
95111: -6 2: 4 1: 11 2: 11
9512 . 1: 2 . 1: 11
9513 . .
9514
9515 Z ] Z ] C-x ) Z K s @key{RET} @key{DEL} 4 @key{RET} 2 z s M-@key{RET} k s
9516@end group
9517@end smallexample
9518
9519Even though the result that we got during the definition was highly
9520bogus, once the definition is complete the @kbd{z s} command gets
9521the right answers.
9522
9523Here's the full program once again:
9524
9525@example
9526@group
9527C-x ( M-2 @key{RET} a =
9528 Z [ @key{DEL} @key{DEL} 1
9529 Z : @key{RET} 0 a =
9530 Z [ @key{DEL} @key{DEL} 0
9531 Z : @key{TAB} 1 - @key{TAB} M-2 @key{RET} 1 - z s
9532 M-@key{TAB} M-@key{TAB} @key{TAB} @key{RET} M-@key{TAB} z s * -
9533 Z ]
9534 Z ]
9535C-x )
9536@end group
9537@end example
9538
9539You can read this definition using @kbd{C-x * m} (@code{read-kbd-macro})
9540followed by @kbd{Z K s}, without having to make a dummy definition
9541first, because @code{read-kbd-macro} doesn't need to execute the
9542definition as it reads it in. For this reason, @code{C-x * m} is often
9543the easiest way to create recursive programs in Calc.
9544
9545@node Programming Answer 12, , Programming Answer 11, Answers to Exercises
9546@subsection Programming Tutorial Exercise 12
9547
9548@noindent
9549This turns out to be a much easier way to solve the problem. Let's
9550denote Stirling numbers as calls of the function @samp{s}.
9551
9552First, we store the rewrite rules corresponding to the definition of
9553Stirling numbers in a convenient variable:
9554
9555@smallexample
9556s e StirlingRules @key{RET}
9557[ s(n,n) := 1 :: n >= 0,
9558 s(n,0) := 0 :: n > 0,
9559 s(n,m) := s(n-1,m-1) - (n-1) s(n-1,m) :: n >= m :: m >= 1 ]
9560C-c C-c
9561@end smallexample
9562
9563Now, it's just a matter of applying the rules:
9564
9565@smallexample
9566@group
95672: 4 1: s(4, 2) 1: 11
95681: 2 . .
9569 .
9570
9571 4 @key{RET} 2 C-x ( ' s($$,$) @key{RET} a r StirlingRules @key{RET} C-x )
9572@end group
9573@end smallexample
9574
9575As in the case of the @code{fib} rules, it would be useful to put these
9576rules in @code{EvalRules} and to add a @samp{:: remember} condition to
9577the last rule.
9578
9579@c This ends the table-of-contents kludge from above:
9580@tex
9581\global\let\chapternofonts=\oldchapternofonts
9582@end tex
9583
9584@c [reference]
9585
9586@node Introduction, Data Types, Tutorial, Top
9587@chapter Introduction
9588
9589@noindent
9590This chapter is the beginning of the Calc reference manual.
9591It covers basic concepts such as the stack, algebraic and
9592numeric entry, undo, numeric prefix arguments, etc.
9593
9594@c [when-split]
9595@c (Chapter 2, the Tutorial, has been printed in a separate volume.)
9596
9597@menu
9598* Basic Commands::
9599* Help Commands::
9600* Stack Basics::
9601* Numeric Entry::
9602* Algebraic Entry::
9603* Quick Calculator::
9604* Prefix Arguments::
9605* Undo::
9606* Error Messages::
9607* Multiple Calculators::
9608* Troubleshooting Commands::
9609@end menu
9610
9611@node Basic Commands, Help Commands, Introduction, Introduction
9612@section Basic Commands
9613
9614@noindent
9615@pindex calc
9616@pindex calc-mode
9617@cindex Starting the Calculator
9618@cindex Running the Calculator
9619To start the Calculator in its standard interface, type @kbd{M-x calc}.
9620By default this creates a pair of small windows, @samp{*Calculator*}
9621and @samp{*Calc Trail*}. The former displays the contents of the
9622Calculator stack and is manipulated exclusively through Calc commands.
9623It is possible (though not usually necessary) to create several Calc
9624mode buffers each of which has an independent stack, undo list, and
9625mode settings. There is exactly one Calc Trail buffer; it records a
9626list of the results of all calculations that have been done. The
9627Calc Trail buffer uses a variant of Calc mode, so Calculator commands
9628still work when the trail buffer's window is selected. It is possible
9629to turn the trail window off, but the @samp{*Calc Trail*} buffer itself
9630still exists and is updated silently. @xref{Trail Commands}.
9631
9632@kindex C-x * c
9633@kindex C-x * *
9634@ignore
9635@mindex @null
9636@end ignore
9637In most installations, the @kbd{C-x * c} key sequence is a more
40ba43b4 9638convenient way to start the Calculator. Also, @kbd{C-x * *}
4009494e
GM
9639is a synonym for @kbd{C-x * c} unless you last used Calc
9640in its Keypad mode.
9641
9642@kindex x
9643@kindex M-x
9644@pindex calc-execute-extended-command
9645Most Calc commands use one or two keystrokes. Lower- and upper-case
9646letters are distinct. Commands may also be entered in full @kbd{M-x} form;
9647for some commands this is the only form. As a convenience, the @kbd{x}
9648key (@code{calc-execute-extended-command})
9649is like @kbd{M-x} except that it enters the initial string @samp{calc-}
9650for you. For example, the following key sequences are equivalent:
9651@kbd{S}, @kbd{M-x calc-sin @key{RET}}, @kbd{x sin @key{RET}}.
9652
3bc88bc9
JB
9653Although Calc is designed to be used from the keyboard, some of
9654Calc's more common commands are available from a menu. In the menu, the
9655arguments to the functions are given by referring to their stack level
9656numbers.
9657
4009494e
GM
9658@cindex Extensions module
9659@cindex @file{calc-ext} module
9660The Calculator exists in many parts. When you type @kbd{C-x * c}, the
9661Emacs ``auto-load'' mechanism will bring in only the first part, which
9662contains the basic arithmetic functions. The other parts will be
9663auto-loaded the first time you use the more advanced commands like trig
9664functions or matrix operations. This is done to improve the response time
9665of the Calculator in the common case when all you need to do is a
9666little arithmetic. If for some reason the Calculator fails to load an
9667extension module automatically, you can force it to load all the
9668extensions by using the @kbd{C-x * L} (@code{calc-load-everything})
9669command. @xref{Mode Settings}.
9670
9671If you type @kbd{M-x calc} or @kbd{C-x * c} with any numeric prefix argument,
9672the Calculator is loaded if necessary, but it is not actually started.
9673If the argument is positive, the @file{calc-ext} extensions are also
9674loaded if necessary. User-written Lisp code that wishes to make use
9675of Calc's arithmetic routines can use @samp{(calc 0)} or @samp{(calc 1)}
9676to auto-load the Calculator.
9677
9678@kindex C-x * b
9679@pindex full-calc
9680If you type @kbd{C-x * b}, then next time you use @kbd{C-x * c} you
9681will get a Calculator that uses the full height of the Emacs screen.
9682When full-screen mode is on, @kbd{C-x * c} runs the @code{full-calc}
9683command instead of @code{calc}. From the Unix shell you can type
9684@samp{emacs -f full-calc} to start a new Emacs specifically for use
9685as a calculator. When Calc is started from the Emacs command line
9686like this, Calc's normal ``quit'' commands actually quit Emacs itself.
9687
9688@kindex C-x * o
9689@pindex calc-other-window
9690The @kbd{C-x * o} command is like @kbd{C-x * c} except that the Calc
9691window is not actually selected. If you are already in the Calc
9692window, @kbd{C-x * o} switches you out of it. (The regular Emacs
9693@kbd{C-x o} command would also work for this, but it has a
9694tendency to drop you into the Calc Trail window instead, which
9695@kbd{C-x * o} takes care not to do.)
9696
9697@ignore
9698@mindex C-x * q
9699@end ignore
9700For one quick calculation, you can type @kbd{C-x * q} (@code{quick-calc})
9701which prompts you for a formula (like @samp{2+3/4}). The result is
9702displayed at the bottom of the Emacs screen without ever creating
9703any special Calculator windows. @xref{Quick Calculator}.
9704
9705@ignore
9706@mindex C-x * k
9707@end ignore
9708Finally, if you are using the X window system you may want to try
9709@kbd{C-x * k} (@code{calc-keypad}) which runs Calc with a
9710``calculator keypad'' picture as well as a stack display. Click on
9711the keys with the mouse to operate the calculator. @xref{Keypad Mode}.
9712
9713@kindex q
9714@pindex calc-quit
9715@cindex Quitting the Calculator
9716@cindex Exiting the Calculator
9717The @kbd{q} key (@code{calc-quit}) exits Calc mode and closes the
9718Calculator's window(s). It does not delete the Calculator buffers.
9719If you type @kbd{M-x calc} again, the Calculator will reappear with the
9720contents of the stack intact. Typing @kbd{C-x * c} or @kbd{C-x * *}
9721again from inside the Calculator buffer is equivalent to executing
9722@code{calc-quit}; you can think of @kbd{C-x * *} as toggling the
9723Calculator on and off.
9724
9725@kindex C-x * x
9726The @kbd{C-x * x} command also turns the Calculator off, no matter which
9727user interface (standard, Keypad, or Embedded) is currently active.
9728It also cancels @code{calc-edit} mode if used from there.
9729
9730@kindex d @key{SPC}
9731@pindex calc-refresh
9732@cindex Refreshing a garbled display
9733@cindex Garbled displays, refreshing
9734The @kbd{d @key{SPC}} key sequence (@code{calc-refresh}) redraws the contents
9735of the Calculator buffer from memory. Use this if the contents of the
9736buffer have been damaged somehow.
9737
9738@ignore
9739@mindex o
9740@end ignore
9741The @kbd{o} key (@code{calc-realign}) moves the cursor back to its
9742``home'' position at the bottom of the Calculator buffer.
9743
9744@kindex <
9745@kindex >
9746@pindex calc-scroll-left
9747@pindex calc-scroll-right
9748@cindex Horizontal scrolling
9749@cindex Scrolling
9750@cindex Wide text, scrolling
9751The @kbd{<} and @kbd{>} keys are bound to @code{calc-scroll-left} and
9752@code{calc-scroll-right}. These are just like the normal horizontal
9753scrolling commands except that they scroll one half-screen at a time by
9754default. (Calc formats its output to fit within the bounds of the
9755window whenever it can.)
9756
9757@kindex @{
9758@kindex @}
9759@pindex calc-scroll-down
9760@pindex calc-scroll-up
9761@cindex Vertical scrolling
9762The @kbd{@{} and @kbd{@}} keys are bound to @code{calc-scroll-down}
9763and @code{calc-scroll-up}. They scroll up or down by one-half the
9764height of the Calc window.
9765
9766@kindex C-x * 0
9767@pindex calc-reset
9768The @kbd{C-x * 0} command (@code{calc-reset}; that's @kbd{C-x *} followed
9769by a zero) resets the Calculator to its initial state. This clears
9770the stack, resets all the modes to their initial values (the values
9771that were saved with @kbd{m m} (@code{calc-save-modes})), clears the
9772caches (@pxref{Caches}), and so on. (It does @emph{not} erase the
9773values of any variables.) With an argument of 0, Calc will be reset to
9774its default state; namely, the modes will be given their default values.
9775With a positive prefix argument, @kbd{C-x * 0} preserves the contents of
9776the stack but resets everything else to its initial state; with a
9777negative prefix argument, @kbd{C-x * 0} preserves the contents of the
9778stack but resets everything else to its default state.
9779
4009494e
GM
9780@node Help Commands, Stack Basics, Basic Commands, Introduction
9781@section Help Commands
9782
9783@noindent
9784@cindex Help commands
9785@kindex ?
b5bdfd9f
JB
9786@kindex a ?
9787@kindex b ?
9788@kindex c ?
9789@kindex d ?
9790@kindex f ?
9791@kindex g ?
9792@kindex j ?
9793@kindex k ?
9794@kindex m ?
9795@kindex r ?
9796@kindex s ?
9797@kindex t ?
9798@kindex u ?
9799@kindex v ?
9800@kindex V ?
9801@kindex z ?
9802@kindex Z ?
4009494e
GM
9803@pindex calc-help
9804The @kbd{?} key (@code{calc-help}) displays a series of brief help messages.
44e97401 9805Some keys (such as @kbd{b} and @kbd{d}) are prefix keys, like Emacs's
4009494e
GM
9806@key{ESC} and @kbd{C-x} prefixes. You can type
9807@kbd{?} after a prefix to see a list of commands beginning with that
9808prefix. (If the message includes @samp{[MORE]}, press @kbd{?} again
9809to see additional commands for that prefix.)
9810
9811@kindex h h
9812@pindex calc-full-help
9813The @kbd{h h} (@code{calc-full-help}) command displays all the @kbd{?}
9814responses at once. When printed, this makes a nice, compact (three pages)
9815summary of Calc keystrokes.
9816
9817In general, the @kbd{h} key prefix introduces various commands that
9818provide help within Calc. Many of the @kbd{h} key functions are
9819Calc-specific analogues to the @kbd{C-h} functions for Emacs help.
9820
9821@kindex h i
9822@kindex C-x * i
9823@kindex i
9824@pindex calc-info
9825The @kbd{h i} (@code{calc-info}) command runs the Emacs Info system
9826to read this manual on-line. This is basically the same as typing
9827@kbd{C-h i} (the regular way to run the Info system), then, if Info
9828is not already in the Calc manual, selecting the beginning of the
9829manual. The @kbd{C-x * i} command is another way to read the Calc
9830manual; it is different from @kbd{h i} in that it works any time,
9831not just inside Calc. The plain @kbd{i} key is also equivalent to
9832@kbd{h i}, though this key is obsolete and may be replaced with a
9833different command in a future version of Calc.
9834
9835@kindex h t
9836@kindex C-x * t
9837@pindex calc-tutorial
9838The @kbd{h t} (@code{calc-tutorial}) command runs the Info system on
9839the Tutorial section of the Calc manual. It is like @kbd{h i},
9840except that it selects the starting node of the tutorial rather
9841than the beginning of the whole manual. (It actually selects the
9842node ``Interactive Tutorial'' which tells a few things about
9843using the Info system before going on to the actual tutorial.)
9844The @kbd{C-x * t} key is equivalent to @kbd{h t} (but it works at
9845all times).
9846
9847@kindex h s
9848@kindex C-x * s
9849@pindex calc-info-summary
9850The @kbd{h s} (@code{calc-info-summary}) command runs the Info system
9851on the Summary node of the Calc manual. @xref{Summary}. The @kbd{C-x * s}
9852key is equivalent to @kbd{h s}.
9853
9854@kindex h k
9855@pindex calc-describe-key
9856The @kbd{h k} (@code{calc-describe-key}) command looks up a key
9857sequence in the Calc manual. For example, @kbd{h k H a S} looks
9858up the documentation on the @kbd{H a S} (@code{calc-solve-for})
9859command. This works by looking up the textual description of
9860the key(s) in the Key Index of the manual, then jumping to the
9861node indicated by the index.
9862
9863Most Calc commands do not have traditional Emacs documentation
9864strings, since the @kbd{h k} command is both more convenient and
9865more instructive. This means the regular Emacs @kbd{C-h k}
9866(@code{describe-key}) command will not be useful for Calc keystrokes.
9867
9868@kindex h c
9869@pindex calc-describe-key-briefly
9870The @kbd{h c} (@code{calc-describe-key-briefly}) command reads a
9871key sequence and displays a brief one-line description of it at
9872the bottom of the screen. It looks for the key sequence in the
9873Summary node of the Calc manual; if it doesn't find the sequence
9874there, it acts just like its regular Emacs counterpart @kbd{C-h c}
9875(@code{describe-key-briefly}). For example, @kbd{h c H a S}
9876gives the description:
9877
9878@smallexample
9879H a S runs calc-solve-for: a `H a S' v => fsolve(a,v) (?=notes)
9880@end smallexample
9881
9882@noindent
9883which means the command @kbd{H a S} or @kbd{H M-x calc-solve-for}
9884takes a value @expr{a} from the stack, prompts for a value @expr{v},
9885then applies the algebraic function @code{fsolve} to these values.
9886The @samp{?=notes} message means you can now type @kbd{?} to see
9887additional notes from the summary that apply to this command.
9888
9889@kindex h f
9890@pindex calc-describe-function
9891The @kbd{h f} (@code{calc-describe-function}) command looks up an
9892algebraic function or a command name in the Calc manual. Enter an
9893algebraic function name to look up that function in the Function
40ba43b4 9894Index or enter a command name beginning with @samp{calc-} to look it
4009494e 9895up in the Command Index. This command will also look up operator
40ba43b4 9896symbols that can appear in algebraic formulas, like @samp{%} and
4009494e
GM
9897@samp{=>}.
9898
9899@kindex h v
9900@pindex calc-describe-variable
9901The @kbd{h v} (@code{calc-describe-variable}) command looks up a
9902variable in the Calc manual. Enter a variable name like @code{pi} or
9903@code{PlotRejects}.
9904
9905@kindex h b
9906@pindex describe-bindings
9907The @kbd{h b} (@code{calc-describe-bindings}) command is just like
9908@kbd{C-h b}, except that only local (Calc-related) key bindings are
9909listed.
9910
9911@kindex h n
9912The @kbd{h n} or @kbd{h C-n} (@code{calc-view-news}) command displays
9913the ``news'' or change history of Calc. This is kept in the file
9914@file{README}, which Calc looks for in the same directory as the Calc
9915source files.
9916
9917@kindex h C-c
9918@kindex h C-d
9919@kindex h C-w
9920The @kbd{h C-c}, @kbd{h C-d}, and @kbd{h C-w} keys display copying,
9921distribution, and warranty information about Calc. These work by
9922pulling up the appropriate parts of the ``Copying'' or ``Reporting
9923Bugs'' sections of the manual.
9924
9925@node Stack Basics, Numeric Entry, Help Commands, Introduction
9926@section Stack Basics
9927
9928@noindent
9929@cindex Stack basics
9930@c [fix-tut RPN Calculations and the Stack]
9931Calc uses RPN notation. If you are not familiar with RPN, @pxref{RPN
9932Tutorial}.
9933
9934To add the numbers 1 and 2 in Calc you would type the keys:
9935@kbd{1 @key{RET} 2 +}.
9936(@key{RET} corresponds to the @key{ENTER} key on most calculators.)
9937The first three keystrokes ``push'' the numbers 1 and 2 onto the stack. The
9938@kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
9939and pushes the result (3) back onto the stack. This number is ready for
9940further calculations: @kbd{5 -} pushes 5 onto the stack, then pops the
99413 and 5, subtracts them, and pushes the result (@mathit{-2}).
9942
9943Note that the ``top'' of the stack actually appears at the @emph{bottom}
9944of the buffer. A line containing a single @samp{.} character signifies
9945the end of the buffer; Calculator commands operate on the number(s)
9946directly above this line. The @kbd{d t} (@code{calc-truncate-stack})
9947command allows you to move the @samp{.} marker up and down in the stack;
9948@pxref{Truncating the Stack}.
9949
9950@kindex d l
9951@pindex calc-line-numbering
9952Stack elements are numbered consecutively, with number 1 being the top of
9953the stack. These line numbers are ordinarily displayed on the lefthand side
9954of the window. The @kbd{d l} (@code{calc-line-numbering}) command controls
9955whether these numbers appear. (Line numbers may be turned off since they
9956slow the Calculator down a bit and also clutter the display.)
9957
9958@kindex o
9959@pindex calc-realign
9960The unshifted letter @kbd{o} (@code{calc-realign}) command repositions
9961the cursor to its top-of-stack ``home'' position. It also undoes any
9962horizontal scrolling in the window. If you give it a numeric prefix
9963argument, it instead moves the cursor to the specified stack element.
9964
9965The @key{RET} (or equivalent @key{SPC}) key is only required to separate
9966two consecutive numbers.
9967(After all, if you typed @kbd{1 2} by themselves the Calculator
9968would enter the number 12.) If you press @key{RET} or @key{SPC} @emph{not}
9969right after typing a number, the key duplicates the number on the top of
9970the stack. @kbd{@key{RET} *} is thus a handy way to square a number.
9971
9972The @key{DEL} key pops and throws away the top number on the stack.
9973The @key{TAB} key swaps the top two objects on the stack.
9974@xref{Stack and Trail}, for descriptions of these and other stack-related
9975commands.
9976
9977@node Numeric Entry, Algebraic Entry, Stack Basics, Introduction
9978@section Numeric Entry
9979
9980@noindent
9981@kindex 0-9
9982@kindex .
9983@kindex e
9984@cindex Numeric entry
9985@cindex Entering numbers
9986Pressing a digit or other numeric key begins numeric entry using the
9987minibuffer. The number is pushed on the stack when you press the @key{RET}
9988or @key{SPC} keys. If you press any other non-numeric key, the number is
9989pushed onto the stack and the appropriate operation is performed. If
9990you press a numeric key which is not valid, the key is ignored.
9991
9992@cindex Minus signs
9993@cindex Negative numbers, entering
9994@kindex _
9995There are three different concepts corresponding to the word ``minus,''
9996typified by @expr{a-b} (subtraction), @expr{-x}
9997(change-sign), and @expr{-5} (negative number). Calc uses three
9998different keys for these operations, respectively:
9999@kbd{-}, @kbd{n}, and @kbd{_} (the underscore). The @kbd{-} key subtracts
10000the two numbers on the top of the stack. The @kbd{n} key changes the sign
10001of the number on the top of the stack or the number currently being entered.
10002The @kbd{_} key begins entry of a negative number or changes the sign of
10003the number currently being entered. The following sequences all enter the
10004number @mathit{-5} onto the stack: @kbd{0 @key{RET} 5 -}, @kbd{5 n @key{RET}},
10005@kbd{5 @key{RET} n}, @kbd{_ 5 @key{RET}}, @kbd{5 _ @key{RET}}.
10006
10007Some other keys are active during numeric entry, such as @kbd{#} for
10008non-decimal numbers, @kbd{:} for fractions, and @kbd{@@} for HMS forms.
10009These notations are described later in this manual with the corresponding
10010data types. @xref{Data Types}.
10011
10012During numeric entry, the only editing key available is @key{DEL}.
10013
10014@node Algebraic Entry, Quick Calculator, Numeric Entry, Introduction
10015@section Algebraic Entry
10016
10017@noindent
10018@kindex '
10019@pindex calc-algebraic-entry
10020@cindex Algebraic notation
10021@cindex Formulas, entering
8dc6104d
JB
10022The @kbd{'} (@code{calc-algebraic-entry}) command can be used to enter
10023calculations in algebraic form. This is accomplished by typing the
40ba43b4 10024apostrophe key, ', followed by the expression in standard format:
4009494e
GM
10025
10026@example
10027' 2+3*4 @key{RET}.
10028@end example
10029
10030@noindent
10031This will compute
10032@texline @math{2+(3\times4) = 14}
40ba43b4 10033@infoline @expr{2+(3*4) = 14}
4009494e
GM
10034and push it on the stack. If you wish you can
10035ignore the RPN aspect of Calc altogether and simply enter algebraic
10036expressions in this way. You may want to use @key{DEL} every so often to
10037clear previous results off the stack.
10038
10039You can press the apostrophe key during normal numeric entry to switch
8dc6104d
JB
10040the half-entered number into Algebraic entry mode. One reason to do
10041this would be to fix a typo, as the full Emacs cursor motion and editing
10042keys are available during algebraic entry but not during numeric entry.
4009494e
GM
10043
10044In the same vein, during either numeric or algebraic entry you can
10045press @kbd{`} (backquote) to switch to @code{calc-edit} mode, where
10046you complete your half-finished entry in a separate buffer.
10047@xref{Editing Stack Entries}.
10048
10049@kindex m a
10050@pindex calc-algebraic-mode
10051@cindex Algebraic Mode
10052If you prefer algebraic entry, you can use the command @kbd{m a}
10053(@code{calc-algebraic-mode}) to set Algebraic mode. In this mode,
10054digits and other keys that would normally start numeric entry instead
10055start full algebraic entry; as long as your formula begins with a digit
10056you can omit the apostrophe. Open parentheses and square brackets also
10057begin algebraic entry. You can still do RPN calculations in this mode,
10058but you will have to press @key{RET} to terminate every number:
10059@kbd{2 @key{RET} 3 @key{RET} * 4 @key{RET} +} would accomplish the same
10060thing as @kbd{2*3+4 @key{RET}}.
10061
10062@cindex Incomplete Algebraic Mode
10063If you give a numeric prefix argument like @kbd{C-u} to the @kbd{m a}
10064command, it enables Incomplete Algebraic mode; this is like regular
10065Algebraic mode except that it applies to the @kbd{(} and @kbd{[} keys
10066only. Numeric keys still begin a numeric entry in this mode.
10067
10068@kindex m t
10069@pindex calc-total-algebraic-mode
10070@cindex Total Algebraic Mode
10071The @kbd{m t} (@code{calc-total-algebraic-mode}) gives you an even
10072stronger algebraic-entry mode, in which @emph{all} regular letter and
10073punctuation keys begin algebraic entry. Use this if you prefer typing
10074@w{@kbd{sqrt( )}} instead of @kbd{Q}, @w{@kbd{factor( )}} instead of
10075@kbd{a f}, and so on. To type regular Calc commands when you are in
10076Total Algebraic mode, hold down the @key{META} key. Thus @kbd{M-q}
10077is the command to quit Calc, @kbd{M-p} sets the precision, and
10078@kbd{M-m t} (or @kbd{M-m M-t}, if you prefer) turns Total Algebraic
10079mode back off again. Meta keys also terminate algebraic entry, so
10080that @kbd{2+3 M-S} is equivalent to @kbd{2+3 @key{RET} M-S}. The symbol
10081@samp{Alg*} will appear in the mode line whenever you are in this mode.
10082
10083Pressing @kbd{'} (the apostrophe) a second time re-enters the previous
10084algebraic formula. You can then use the normal Emacs editing keys to
10085modify this formula to your liking before pressing @key{RET}.
10086
10087@kindex $
10088@cindex Formulas, referring to stack
10089Within a formula entered from the keyboard, the symbol @kbd{$}
10090represents the number on the top of the stack. If an entered formula
10091contains any @kbd{$} characters, the Calculator replaces the top of
10092stack with that formula rather than simply pushing the formula onto the
10093stack. Thus, @kbd{' 1+2 @key{RET}} pushes 3 on the stack, and @kbd{$*2
10094@key{RET}} replaces it with 6. Note that the @kbd{$} key always
10095initiates algebraic entry; the @kbd{'} is unnecessary if @kbd{$} is the
10096first character in the new formula.
10097
10098Higher stack elements can be accessed from an entered formula with the
10099symbols @kbd{$$}, @kbd{$$$}, and so on. The number of stack elements
10100removed (to be replaced by the entered values) equals the number of dollar
10101signs in the longest such symbol in the formula. For example, @samp{$$+$$$}
10102adds the second and third stack elements, replacing the top three elements
10103with the answer. (All information about the top stack element is thus lost
10104since no single @samp{$} appears in this formula.)
10105
10106A slightly different way to refer to stack elements is with a dollar
10107sign followed by a number: @samp{$1}, @samp{$2}, and so on are much
10108like @samp{$}, @samp{$$}, etc., except that stack entries referred
10109to numerically are not replaced by the algebraic entry. That is, while
10110@samp{$+1} replaces 5 on the stack with 6, @samp{$1+1} leaves the 5
10111on the stack and pushes an additional 6.
10112
10113If a sequence of formulas are entered separated by commas, each formula
10114is pushed onto the stack in turn. For example, @samp{1,2,3} pushes
10115those three numbers onto the stack (leaving the 3 at the top), and
10116@samp{$+1,$-1} replaces a 5 on the stack with 4 followed by 6. Also,
10117@samp{$,$$} exchanges the top two elements of the stack, just like the
10118@key{TAB} key.
10119
10120You can finish an algebraic entry with @kbd{M-=} or @kbd{M-@key{RET}} instead
10121of @key{RET}. This uses @kbd{=} to evaluate the variables in each
10122formula that goes onto the stack. (Thus @kbd{' pi @key{RET}} pushes
10123the variable @samp{pi}, but @kbd{' pi M-@key{RET}} pushes 3.1415.)
10124
10125If you finish your algebraic entry by pressing @key{LFD} (or @kbd{C-j})
1dcac243 10126instead of @key{RET}, Calc disables simplification
4009494e
GM
10127(as if by @kbd{m O}; @pxref{Simplification Modes}) while the entry
10128is being pushed on the stack. Thus @kbd{' 1+2 @key{RET}} pushes 3
10129on the stack, but @kbd{' 1+2 @key{LFD}} pushes the formula @expr{1+2};
10130you might then press @kbd{=} when it is time to evaluate this formula.
10131
10132@node Quick Calculator, Prefix Arguments, Algebraic Entry, Introduction
10133@section ``Quick Calculator'' Mode
10134
10135@noindent
10136@kindex C-x * q
10137@pindex quick-calc
10138@cindex Quick Calculator
10139There is another way to invoke the Calculator if all you need to do
10140is make one or two quick calculations. Type @kbd{C-x * q} (or
10141@kbd{M-x quick-calc}), then type any formula as an algebraic entry.
10142The Calculator will compute the result and display it in the echo
10143area, without ever actually putting up a Calc window.
10144
10145You can use the @kbd{$} character in a Quick Calculator formula to
10146refer to the previous Quick Calculator result. Older results are
10147not retained; the Quick Calculator has no effect on the full
10148Calculator's stack or trail. If you compute a result and then
10149forget what it was, just run @code{C-x * q} again and enter
10150@samp{$} as the formula.
10151
10152If this is the first time you have used the Calculator in this Emacs
10153session, the @kbd{C-x * q} command will create the @code{*Calculator*}
10154buffer and perform all the usual initializations; it simply will
10155refrain from putting that buffer up in a new window. The Quick
10156Calculator refers to the @code{*Calculator*} buffer for all mode
10157settings. Thus, for example, to set the precision that the Quick
10158Calculator uses, simply run the full Calculator momentarily and use
10159the regular @kbd{p} command.
10160
10161If you use @code{C-x * q} from inside the Calculator buffer, the
10162effect is the same as pressing the apostrophe key (algebraic entry).
10163
10164The result of a Quick calculation is placed in the Emacs ``kill ring''
10165as well as being displayed. A subsequent @kbd{C-y} command will
10166yank the result into the editing buffer. You can also use this
10167to yank the result into the next @kbd{C-x * q} input line as a more
10168explicit alternative to @kbd{$} notation, or to yank the result
10169into the Calculator stack after typing @kbd{C-x * c}.
10170
10171If you finish your formula by typing @key{LFD} (or @kbd{C-j}) instead
10172of @key{RET}, the result is inserted immediately into the current
10173buffer rather than going into the kill ring.
10174
10175Quick Calculator results are actually evaluated as if by the @kbd{=}
10176key (which replaces variable names by their stored values, if any).
10177If the formula you enter is an assignment to a variable using the
10178@samp{:=} operator, say, @samp{foo := 2 + 3} or @samp{foo := foo + 1},
10179then the result of the evaluation is stored in that Calc variable.
10180@xref{Store and Recall}.
10181
10182If the result is an integer and the current display radix is decimal,
10183the number will also be displayed in hex, octal and binary formats. If
10184the integer is in the range from 1 to 126, it will also be displayed as
10185an ASCII character.
10186
10187For example, the quoted character @samp{"x"} produces the vector
10188result @samp{[120]} (because 120 is the ASCII code of the lower-case
10189`x'; @pxref{Strings}). Since this is a vector, not an integer, it
10190is displayed only according to the current mode settings. But
10191running Quick Calc again and entering @samp{120} will produce the
10192result @samp{120 (16#78, 8#170, x)} which shows the number in its
10193decimal, hexadecimal, octal, and ASCII forms.
10194
10195Please note that the Quick Calculator is not any faster at loading
10196or computing the answer than the full Calculator; the name ``quick''
10197merely refers to the fact that it's much less hassle to use for
10198small calculations.
10199
10200@node Prefix Arguments, Undo, Quick Calculator, Introduction
10201@section Numeric Prefix Arguments
10202
10203@noindent
10204Many Calculator commands use numeric prefix arguments. Some, such as
10205@kbd{d s} (@code{calc-sci-notation}), set a parameter to the value of
10206the prefix argument or use a default if you don't use a prefix.
10207Others (like @kbd{d f} (@code{calc-fix-notation})) require an argument
10208and prompt for a number if you don't give one as a prefix.
10209
10210As a rule, stack-manipulation commands accept a numeric prefix argument
10211which is interpreted as an index into the stack. A positive argument
10212operates on the top @var{n} stack entries; a negative argument operates
10213on the @var{n}th stack entry in isolation; and a zero argument operates
10214on the entire stack.
10215
10216Most commands that perform computations (such as the arithmetic and
10217scientific functions) accept a numeric prefix argument that allows the
10218operation to be applied across many stack elements. For unary operations
10219(that is, functions of one argument like absolute value or complex
10220conjugate), a positive prefix argument applies that function to the top
10221@var{n} stack entries simultaneously, and a negative argument applies it
10222to the @var{n}th stack entry only. For binary operations (functions of
10223two arguments like addition, GCD, and vector concatenation), a positive
10224prefix argument ``reduces'' the function across the top @var{n}
10225stack elements (for example, @kbd{C-u 5 +} sums the top 5 stack entries;
10226@pxref{Reducing and Mapping}), and a negative argument maps the next-to-top
10227@var{n} stack elements with the top stack element as a second argument
10228(for example, @kbd{7 c-u -5 +} adds 7 to the top 5 stack elements).
10229This feature is not available for operations which use the numeric prefix
10230argument for some other purpose.
10231
10232Numeric prefixes are specified the same way as always in Emacs: Press
10233a sequence of @key{META}-digits, or press @key{ESC} followed by digits,
10234or press @kbd{C-u} followed by digits. Some commands treat plain
10235@kbd{C-u} (without any actual digits) specially.
10236
10237@kindex ~
10238@pindex calc-num-prefix
10239You can type @kbd{~} (@code{calc-num-prefix}) to pop an integer from the
10240top of the stack and enter it as the numeric prefix for the next command.
10241For example, @kbd{C-u 16 p} sets the precision to 16 digits; an alternate
10242(silly) way to do this would be @kbd{2 @key{RET} 4 ^ ~ p}, i.e., compute 2
10243to the fourth power and set the precision to that value.
10244
10245Conversely, if you have typed a numeric prefix argument the @kbd{~} key
10246pushes it onto the stack in the form of an integer.
10247
10248@node Undo, Error Messages, Prefix Arguments, Introduction
10249@section Undoing Mistakes
10250
10251@noindent
10252@kindex U
10253@kindex C-_
10254@pindex calc-undo
10255@cindex Mistakes, undoing
10256@cindex Undoing mistakes
10257@cindex Errors, undoing
10258The shift-@kbd{U} key (@code{calc-undo}) undoes the most recent operation.
10259If that operation added or dropped objects from the stack, those objects
10260are removed or restored. If it was a ``store'' operation, you are
10261queried whether or not to restore the variable to its original value.
10262The @kbd{U} key may be pressed any number of times to undo successively
10263farther back in time; with a numeric prefix argument it undoes a
ec06459c
JB
10264specified number of operations. When the Calculator is quit, as with
10265the @kbd{q} (@code{calc-quit}) command, the undo history will be
10266truncated to the length of the customizable variable
10267@code{calc-undo-length} (@pxref{Customizing Calc}), which by default
10268is @expr{100}. (Recall that @kbd{C-x * c} is synonymous with
10269@code{calc-quit} while inside the Calculator; this also truncates the
10270undo history.)
4009494e
GM
10271
10272Currently the mode-setting commands (like @code{calc-precision}) are not
10273undoable. You can undo past a point where you changed a mode, but you
10274will need to reset the mode yourself.
10275
10276@kindex D
10277@pindex calc-redo
10278@cindex Redoing after an Undo
10279The shift-@kbd{D} key (@code{calc-redo}) redoes an operation that was
10280mistakenly undone. Pressing @kbd{U} with a negative prefix argument is
10281equivalent to executing @code{calc-redo}. You can redo any number of
10282times, up to the number of recent consecutive undo commands. Redo
10283information is cleared whenever you give any command that adds new undo
10284information, i.e., if you undo, then enter a number on the stack or make
10285any other change, then it will be too late to redo.
10286
10287@kindex M-@key{RET}
10288@pindex calc-last-args
10289@cindex Last-arguments feature
10290@cindex Arguments, restoring
10291The @kbd{M-@key{RET}} key (@code{calc-last-args}) is like undo in that
10292it restores the arguments of the most recent command onto the stack;
10293however, it does not remove the result of that command. Given a numeric
10294prefix argument, this command applies to the @expr{n}th most recent
10295command which removed items from the stack; it pushes those items back
10296onto the stack.
10297
10298The @kbd{K} (@code{calc-keep-args}) command provides a related function
10299to @kbd{M-@key{RET}}. @xref{Stack and Trail}.
10300
10301It is also possible to recall previous results or inputs using the trail.
10302@xref{Trail Commands}.
10303
10304The standard Emacs @kbd{C-_} undo key is recognized as a synonym for @kbd{U}.
10305
10306@node Error Messages, Multiple Calculators, Undo, Introduction
10307@section Error Messages
10308
10309@noindent
10310@kindex w
10311@pindex calc-why
10312@cindex Errors, messages
10313@cindex Why did an error occur?
10314Many situations that would produce an error message in other calculators
10315simply create unsimplified formulas in the Emacs Calculator. For example,
10316@kbd{1 @key{RET} 0 /} pushes the formula @expr{1 / 0}; @w{@kbd{0 L}} pushes
10317the formula @samp{ln(0)}. Floating-point overflow and underflow are also
10318reasons for this to happen.
10319
10320When a function call must be left in symbolic form, Calc usually
10321produces a message explaining why. Messages that are probably
10322surprising or indicative of user errors are displayed automatically.
10323Other messages are simply kept in Calc's memory and are displayed only
10324if you type @kbd{w} (@code{calc-why}). You can also press @kbd{w} if
10325the same computation results in several messages. (The first message
10326will end with @samp{[w=more]} in this case.)
10327
10328@kindex d w
10329@pindex calc-auto-why
10330The @kbd{d w} (@code{calc-auto-why}) command controls when error messages
10331are displayed automatically. (Calc effectively presses @kbd{w} for you
10332after your computation finishes.) By default, this occurs only for
10333``important'' messages. The other possible modes are to report
10334@emph{all} messages automatically, or to report none automatically (so
10335that you must always press @kbd{w} yourself to see the messages).
10336
10337@node Multiple Calculators, Troubleshooting Commands, Error Messages, Introduction
10338@section Multiple Calculators
10339
10340@noindent
10341@pindex another-calc
10342It is possible to have any number of Calc mode buffers at once.
10343Usually this is done by executing @kbd{M-x another-calc}, which
10344is similar to @kbd{C-x * c} except that if a @samp{*Calculator*}
10345buffer already exists, a new, independent one with a name of the
10346form @samp{*Calculator*<@var{n}>} is created. You can also use the
10347command @code{calc-mode} to put any buffer into Calculator mode, but
10348this would ordinarily never be done.
10349
10350The @kbd{q} (@code{calc-quit}) command does not destroy a Calculator buffer;
10351it only closes its window. Use @kbd{M-x kill-buffer} to destroy a
10352Calculator buffer.
10353
10354Each Calculator buffer keeps its own stack, undo list, and mode settings
10355such as precision, angular mode, and display formats. In Emacs terms,
10356variables such as @code{calc-stack} are buffer-local variables. The
10357global default values of these variables are used only when a new
10358Calculator buffer is created. The @code{calc-quit} command saves
10359the stack and mode settings of the buffer being quit as the new defaults.
10360
10361There is only one trail buffer, @samp{*Calc Trail*}, used by all
10362Calculator buffers.
10363
10364@node Troubleshooting Commands, , Multiple Calculators, Introduction
10365@section Troubleshooting Commands
10366
10367@noindent
10368This section describes commands you can use in case a computation
10369incorrectly fails or gives the wrong answer.
10370
10371@xref{Reporting Bugs}, if you find a problem that appears to be due
10372to a bug or deficiency in Calc.
10373
10374@menu
10375* Autoloading Problems::
10376* Recursion Depth::
10377* Caches::
10378* Debugging Calc::
10379@end menu
10380
10381@node Autoloading Problems, Recursion Depth, Troubleshooting Commands, Troubleshooting Commands
10382@subsection Autoloading Problems
10383
10384@noindent
10385The Calc program is split into many component files; components are
10386loaded automatically as you use various commands that require them.
10387Occasionally Calc may lose track of when a certain component is
10388necessary; typically this means you will type a command and it won't
10389work because some function you've never heard of was undefined.
10390
10391@kindex C-x * L
10392@pindex calc-load-everything
10393If this happens, the easiest workaround is to type @kbd{C-x * L}
10394(@code{calc-load-everything}) to force all the parts of Calc to be
10395loaded right away. This will cause Emacs to take up a lot more
10396memory than it would otherwise, but it's guaranteed to fix the problem.
10397
10398@node Recursion Depth, Caches, Autoloading Problems, Troubleshooting Commands
10399@subsection Recursion Depth
10400
10401@noindent
10402@kindex M
10403@kindex I M
10404@pindex calc-more-recursion-depth
10405@pindex calc-less-recursion-depth
10406@cindex Recursion depth
10407@cindex ``Computation got stuck'' message
10408@cindex @code{max-lisp-eval-depth}
10409@cindex @code{max-specpdl-size}
10410Calc uses recursion in many of its calculations. Emacs Lisp keeps a
10411variable @code{max-lisp-eval-depth} which limits the amount of recursion
10412possible in an attempt to recover from program bugs. If a calculation
10413ever halts incorrectly with the message ``Computation got stuck or
10414ran too long,'' use the @kbd{M} command (@code{calc-more-recursion-depth})
10415to increase this limit. (Of course, this will not help if the
10416calculation really did get stuck due to some problem inside Calc.)
10417
10418The limit is always increased (multiplied) by a factor of two. There
10419is also an @kbd{I M} (@code{calc-less-recursion-depth}) command which
10420decreases this limit by a factor of two, down to a minimum value of 200.
10421The default value is 1000.
10422
10423These commands also double or halve @code{max-specpdl-size}, another
10424internal Lisp recursion limit. The minimum value for this limit is 600.
10425
10426@node Caches, Debugging Calc, Recursion Depth, Troubleshooting Commands
10427@subsection Caches
10428
10429@noindent
10430@cindex Caches
10431@cindex Flushing caches
10432Calc saves certain values after they have been computed once. For
10433example, the @kbd{P} (@code{calc-pi}) command initially ``knows'' the
10434constant @cpi{} to about 20 decimal places; if the current precision
10435is greater than this, it will recompute @cpi{} using a series
10436approximation. This value will not need to be recomputed ever again
10437unless you raise the precision still further. Many operations such as
10438logarithms and sines make use of similarly cached values such as
40ba43b4 10439@cpiover{4} and
4009494e 10440@texline @math{\ln 2}.
40ba43b4 10441@infoline @expr{ln(2)}.
4009494e
GM
10442The visible effect of caching is that
10443high-precision computations may seem to do extra work the first time.
10444Other things cached include powers of two (for the binary arithmetic
10445functions), matrix inverses and determinants, symbolic integrals, and
10446data points computed by the graphing commands.
10447
10448@pindex calc-flush-caches
10449If you suspect a Calculator cache has become corrupt, you can use the
10450@code{calc-flush-caches} command to reset all caches to the empty state.
10451(This should only be necessary in the event of bugs in the Calculator.)
10452The @kbd{C-x * 0} (with the zero key) command also resets caches along
10453with all other aspects of the Calculator's state.
10454
10455@node Debugging Calc, , Caches, Troubleshooting Commands
10456@subsection Debugging Calc
10457
10458@noindent
10459A few commands exist to help in the debugging of Calc commands.
10460@xref{Programming}, to see the various ways that you can write
10461your own Calc commands.
10462
10463@kindex Z T
10464@pindex calc-timing
10465The @kbd{Z T} (@code{calc-timing}) command turns on and off a mode
10466in which the timing of slow commands is reported in the Trail.
10467Any Calc command that takes two seconds or longer writes a line
10468to the Trail showing how many seconds it took. This value is
10469accurate only to within one second.
10470
10471All steps of executing a command are included; in particular, time
10472taken to format the result for display in the stack and trail is
10473counted. Some prompts also count time taken waiting for them to
10474be answered, while others do not; this depends on the exact
10475implementation of the command. For best results, if you are timing
10476a sequence that includes prompts or multiple commands, define a
10477keyboard macro to run the whole sequence at once. Calc's @kbd{X}
10478command (@pxref{Keyboard Macros}) will then report the time taken
10479to execute the whole macro.
10480
10481Another advantage of the @kbd{X} command is that while it is
10482executing, the stack and trail are not updated from step to step.
10483So if you expect the output of your test sequence to leave a result
10484that may take a long time to format and you don't wish to count
10485this formatting time, end your sequence with a @key{DEL} keystroke
10486to clear the result from the stack. When you run the sequence with
10487@kbd{X}, Calc will never bother to format the large result.
10488
10489Another thing @kbd{Z T} does is to increase the Emacs variable
10490@code{gc-cons-threshold} to a much higher value (two million; the
10491usual default in Calc is 250,000) for the duration of each command.
10492This generally prevents garbage collection during the timing of
10493the command, though it may cause your Emacs process to grow
10494abnormally large. (Garbage collection time is a major unpredictable
10495factor in the timing of Emacs operations.)
10496
10497Another command that is useful when debugging your own Lisp
10498extensions to Calc is @kbd{M-x calc-pass-errors}, which disables
10499the error handler that changes the ``@code{max-lisp-eval-depth}
10500exceeded'' message to the much more friendly ``Computation got
10501stuck or ran too long.'' This handler interferes with the Emacs
10502Lisp debugger's @code{debug-on-error} mode. Errors are reported
10503in the handler itself rather than at the true location of the
10504error. After you have executed @code{calc-pass-errors}, Lisp
10505errors will be reported correctly but the user-friendly message
10506will be lost.
10507
10508@node Data Types, Stack and Trail, Introduction, Top
10509@chapter Data Types
10510
10511@noindent
10512This chapter discusses the various types of objects that can be placed
10513on the Calculator stack, how they are displayed, and how they are
10514entered. (@xref{Data Type Formats}, for information on how these data
10515types are represented as underlying Lisp objects.)
10516
10517Integers, fractions, and floats are various ways of describing real
10518numbers. HMS forms also for many purposes act as real numbers. These
10519types can be combined to form complex numbers, modulo forms, error forms,
10520or interval forms. (But these last four types cannot be combined
10521arbitrarily:@: error forms may not contain modulo forms, for example.)
10522Finally, all these types of numbers may be combined into vectors,
10523matrices, or algebraic formulas.
10524
10525@menu
10526* Integers:: The most basic data type.
10527* Fractions:: This and above are called @dfn{rationals}.
10528* Floats:: This and above are called @dfn{reals}.
10529* Complex Numbers:: This and above are called @dfn{numbers}.
10530* Infinities::
10531* Vectors and Matrices::
10532* Strings::
10533* HMS Forms::
10534* Date Forms::
10535* Modulo Forms::
10536* Error Forms::
10537* Interval Forms::
10538* Incomplete Objects::
10539* Variables::
10540* Formulas::
10541@end menu
10542
10543@node Integers, Fractions, Data Types, Data Types
10544@section Integers
10545
10546@noindent
10547@cindex Integers
10548The Calculator stores integers to arbitrary precision. Addition,
10549subtraction, and multiplication of integers always yields an exact
10550integer result. (If the result of a division or exponentiation of
10551integers is not an integer, it is expressed in fractional or
10552floating-point form according to the current Fraction mode.
10553@xref{Fraction Mode}.)
10554
10555A decimal integer is represented as an optional sign followed by a
10556sequence of digits. Grouping (@pxref{Grouping Digits}) can be used to
10557insert a comma at every third digit for display purposes, but you
10558must not type commas during the entry of numbers.
10559
10560@kindex #
10561A non-decimal integer is represented as an optional sign, a radix
10562between 2 and 36, a @samp{#} symbol, and one or more digits. For radix 11
10563and above, the letters A through Z (upper- or lower-case) count as
10564digits and do not terminate numeric entry mode. @xref{Radix Modes}, for how
10565to set the default radix for display of integers. Numbers of any radix
10566may be entered at any time. If you press @kbd{#} at the beginning of a
10567number, the current display radix is used.
10568
10569@node Fractions, Floats, Integers, Data Types
10570@section Fractions
10571
10572@noindent
10573@cindex Fractions
10574A @dfn{fraction} is a ratio of two integers. Fractions are traditionally
10575written ``2/3'' but Calc uses the notation @samp{2:3}. (The @kbd{/} key
10576performs RPN division; the following two sequences push the number
10577@samp{2:3} on the stack: @kbd{2 :@: 3 @key{RET}}, or @kbd{2 @key{RET} 3 /}
10578assuming Fraction mode has been enabled.)
10579When the Calculator produces a fractional result it always reduces it to
10580simplest form, which may in fact be an integer.
10581
10582Fractions may also be entered in a three-part form, where @samp{2:3:4}
10583represents two-and-three-quarters. @xref{Fraction Formats}, for fraction
10584display formats.
10585
10586Non-decimal fractions are entered and displayed as
10587@samp{@var{radix}#@var{num}:@var{denom}} (or in the analogous three-part
10588form). The numerator and denominator always use the same radix.
10589
10590@node Floats, Complex Numbers, Fractions, Data Types
10591@section Floats
10592
10593@noindent
10594@cindex Floating-point numbers
10595A floating-point number or @dfn{float} is a number stored in scientific
10596notation. The number of significant digits in the fractional part is
10597governed by the current floating precision (@pxref{Precision}). The
40ba43b4 10598range of acceptable values is from
4009494e 10599@texline @math{10^{-3999999}}
40ba43b4
PE
10600@infoline @expr{10^-3999999}
10601(inclusive) to
4009494e
GM
10602@texline @math{10^{4000000}}
10603@infoline @expr{10^4000000}
10604(exclusive), plus the corresponding negative values and zero.
10605
10606Calculations that would exceed the allowable range of values (such
10607as @samp{exp(exp(20))}) are left in symbolic form by Calc. The
10608messages ``floating-point overflow'' or ``floating-point underflow''
10609indicate that during the calculation a number would have been produced
10610that was too large or too close to zero, respectively, to be represented
10611by Calc. This does not necessarily mean the final result would have
10612overflowed, just that an overflow occurred while computing the result.
10613(In fact, it could report an underflow even though the final result
10614would have overflowed!)
10615
10616If a rational number and a float are mixed in a calculation, the result
10617will in general be expressed as a float. Commands that require an integer
10618value (such as @kbd{k g} [@code{gcd}]) will also accept integer-valued
10619floats, i.e., floating-point numbers with nothing after the decimal point.
10620
10621Floats are identified by the presence of a decimal point and/or an
10622exponent. In general a float consists of an optional sign, digits
10623including an optional decimal point, and an optional exponent consisting
10624of an @samp{e}, an optional sign, and up to seven exponent digits.
10625For example, @samp{23.5e-2} is 23.5 times ten to the minus-second power,
10626or 0.235.
10627
10628Floating-point numbers are normally displayed in decimal notation with
10629all significant figures shown. Exceedingly large or small numbers are
10630displayed in scientific notation. Various other display options are
10631available. @xref{Float Formats}.
10632
10633@cindex Accuracy of calculations
10634Floating-point numbers are stored in decimal, not binary. The result
10635of each operation is rounded to the nearest value representable in the
10636number of significant digits specified by the current precision,
10637rounding away from zero in the case of a tie. Thus (in the default
10638display mode) what you see is exactly what you get. Some operations such
10639as square roots and transcendental functions are performed with several
10640digits of extra precision and then rounded down, in an effort to make the
10641final result accurate to the full requested precision. However,
10642accuracy is not rigorously guaranteed. If you suspect the validity of a
10643result, try doing the same calculation in a higher precision. The
10644Calculator's arithmetic is not intended to be IEEE-conformant in any
10645way.
10646
10647While floats are always @emph{stored} in decimal, they can be entered
10648and displayed in any radix just like integers and fractions. Since a
10649float that is entered in a radix other that 10 will be converted to
10650decimal, the number that Calc stores may not be exactly the number that
10651was entered, it will be the closest decimal approximation given the
e1dbe924 10652current precision. The notation @samp{@var{radix}#@var{ddd}.@var{ddd}}
4009494e
GM
10653is a floating-point number whose digits are in the specified radix.
10654Note that the @samp{.} is more aptly referred to as a ``radix point''
10655than as a decimal point in this case. The number @samp{8#123.4567} is
10656defined as @samp{8#1234567 * 8^-4}. If the radix is 14 or less, you can
10657use @samp{e} notation to write a non-decimal number in scientific
10658notation. The exponent is written in decimal, and is considered to be a
10659power of the radix: @samp{8#1234567e-4}. If the radix is 15 or above,
10660the letter @samp{e} is a digit, so scientific notation must be written
10661out, e.g., @samp{16#123.4567*16^2}. The first two exercises of the
10662Modes Tutorial explore some of the properties of non-decimal floats.
10663
10664@node Complex Numbers, Infinities, Floats, Data Types
10665@section Complex Numbers
10666
10667@noindent
10668@cindex Complex numbers
10669There are two supported formats for complex numbers: rectangular and
10670polar. The default format is rectangular, displayed in the form
10671@samp{(@var{real},@var{imag})} where @var{real} is the real part and
10672@var{imag} is the imaginary part, each of which may be any real number.
10673Rectangular complex numbers can also be displayed in @samp{@var{a}+@var{b}i}
10674notation; @pxref{Complex Formats}.
10675
40ba43b4 10676Polar complex numbers are displayed in the form
4009494e
GM
10677@texline `@tfn{(}@var{r}@tfn{;}@math{\theta}@tfn{)}'
10678@infoline `@tfn{(}@var{r}@tfn{;}@var{theta}@tfn{)}'
40ba43b4 10679where @var{r} is the nonnegative magnitude and
4009494e 10680@texline @math{\theta}
40ba43b4
PE
10681@infoline @var{theta}
10682is the argument or phase angle. The range of
4009494e 10683@texline @math{\theta}
40ba43b4 10684@infoline @var{theta}
4009494e
GM
10685depends on the current angular mode (@pxref{Angular Modes}); it is
10686generally between @mathit{-180} and @mathit{+180} degrees or the equivalent range
40ba43b4 10687in radians.
4009494e
GM
10688
10689Complex numbers are entered in stages using incomplete objects.
10690@xref{Incomplete Objects}.
10691
10692Operations on rectangular complex numbers yield rectangular complex
10693results, and similarly for polar complex numbers. Where the two types
10694are mixed, or where new complex numbers arise (as for the square root of
10695a negative real), the current @dfn{Polar mode} is used to determine the
10696type. @xref{Polar Mode}.
10697
10698A complex result in which the imaginary part is zero (or the phase angle
10699is 0 or 180 degrees or @cpi{} radians) is automatically converted to a real
10700number.
10701
10702@node Infinities, Vectors and Matrices, Complex Numbers, Data Types
10703@section Infinities
10704
10705@noindent
10706@cindex Infinity
10707@cindex @code{inf} variable
10708@cindex @code{uinf} variable
10709@cindex @code{nan} variable
10710@vindex inf
10711@vindex uinf
10712@vindex nan
10713The word @code{inf} represents the mathematical concept of @dfn{infinity}.
10714Calc actually has three slightly different infinity-like values:
10715@code{inf}, @code{uinf}, and @code{nan}. These are just regular
10716variable names (@pxref{Variables}); you should avoid using these
10717names for your own variables because Calc gives them special
10718treatment. Infinities, like all variable names, are normally
10719entered using algebraic entry.
10720
10721Mathematically speaking, it is not rigorously correct to treat
10722``infinity'' as if it were a number, but mathematicians often do
10723so informally. When they say that @samp{1 / inf = 0}, what they
10724really mean is that @expr{1 / x}, as @expr{x} becomes larger and
10725larger, becomes arbitrarily close to zero. So you can imagine
10726that if @expr{x} got ``all the way to infinity,'' then @expr{1 / x}
10727would go all the way to zero. Similarly, when they say that
40ba43b4 10728@samp{exp(inf) = inf}, they mean that
4009494e 10729@texline @math{e^x}
40ba43b4 10730@infoline @expr{exp(x)}
4009494e
GM
10731grows without bound as @expr{x} grows. The symbol @samp{-inf} likewise
10732stands for an infinitely negative real value; for example, we say that
10733@samp{exp(-inf) = 0}. You can have an infinity pointing in any
10734direction on the complex plane: @samp{sqrt(-inf) = i inf}.
10735
10736The same concept of limits can be used to define @expr{1 / 0}. We
10737really want the value that @expr{1 / x} approaches as @expr{x}
10738approaches zero. But if all we have is @expr{1 / 0}, we can't
10739tell which direction @expr{x} was coming from. If @expr{x} was
10740positive and decreasing toward zero, then we should say that
10741@samp{1 / 0 = inf}. But if @expr{x} was negative and increasing
10742toward zero, the answer is @samp{1 / 0 = -inf}. In fact, @expr{x}
10743could be an imaginary number, giving the answer @samp{i inf} or
10744@samp{-i inf}. Calc uses the special symbol @samp{uinf} to mean
10745@dfn{undirected infinity}, i.e., a value which is infinitely
10746large but with an unknown sign (or direction on the complex plane).
10747
10748Calc actually has three modes that say how infinities are handled.
10749Normally, infinities never arise from calculations that didn't
10750already have them. Thus, @expr{1 / 0} is treated simply as an
10751error and left unevaluated. The @kbd{m i} (@code{calc-infinite-mode})
10752command (@pxref{Infinite Mode}) enables a mode in which
10753@expr{1 / 0} evaluates to @code{uinf} instead. There is also
10754an alternative type of infinite mode which says to treat zeros
10755as if they were positive, so that @samp{1 / 0 = inf}. While this
10756is less mathematically correct, it may be the answer you want in
10757some cases.
10758
10759Since all infinities are ``as large'' as all others, Calc simplifies,
10760e.g., @samp{5 inf} to @samp{inf}. Another example is
10761@samp{5 - inf = -inf}, where the @samp{-inf} is so large that
10762adding a finite number like five to it does not affect it.
10763Note that @samp{a - inf} also results in @samp{-inf}; Calc assumes
10764that variables like @code{a} always stand for finite quantities.
10765Just to show that infinities really are all the same size,
10766note that @samp{sqrt(inf) = inf^2 = exp(inf) = inf} in Calc's
10767notation.
10768
10769It's not so easy to define certain formulas like @samp{0 * inf} and
10770@samp{inf / inf}. Depending on where these zeros and infinities
10771came from, the answer could be literally anything. The latter
10772formula could be the limit of @expr{x / x} (giving a result of one),
10773or @expr{2 x / x} (giving two), or @expr{x^2 / x} (giving @code{inf}),
10774or @expr{x / x^2} (giving zero). Calc uses the symbol @code{nan}
10775to represent such an @dfn{indeterminate} value. (The name ``nan''
10776comes from analogy with the ``NAN'' concept of IEEE standard
10777arithmetic; it stands for ``Not A Number.'' This is somewhat of a
10778misnomer, since @code{nan} @emph{does} stand for some number or
10779infinity, it's just that @emph{which} number it stands for
10780cannot be determined.) In Calc's notation, @samp{0 * inf = nan}
10781and @samp{inf / inf = nan}. A few other common indeterminate
10782expressions are @samp{inf - inf} and @samp{inf ^ 0}. Also,
10783@samp{0 / 0 = nan} if you have turned on Infinite mode
10784(as described above).
10785
10786Infinities are especially useful as parts of @dfn{intervals}.
10787@xref{Interval Forms}.
10788
10789@node Vectors and Matrices, Strings, Infinities, Data Types
10790@section Vectors and Matrices
10791
10792@noindent
10793@cindex Vectors
10794@cindex Plain vectors
10795@cindex Matrices
10796The @dfn{vector} data type is flexible and general. A vector is simply a
10797list of zero or more data objects. When these objects are numbers, the
10798whole is a vector in the mathematical sense. When these objects are
10799themselves vectors of equal (nonzero) length, the whole is a @dfn{matrix}.
10800A vector which is not a matrix is referred to here as a @dfn{plain vector}.
10801
10802A vector is displayed as a list of values separated by commas and enclosed
10803in square brackets: @samp{[1, 2, 3]}. Thus the following is a 2 row by
108043 column matrix: @samp{[[1, 2, 3], [4, 5, 6]]}. Vectors, like complex
10805numbers, are entered as incomplete objects. @xref{Incomplete Objects}.
10806During algebraic entry, vectors are entered all at once in the usual
10807brackets-and-commas form. Matrices may be entered algebraically as nested
10808vectors, or using the shortcut notation @w{@samp{[1, 2, 3; 4, 5, 6]}},
10809with rows separated by semicolons. The commas may usually be omitted
10810when entering vectors: @samp{[1 2 3]}. Curly braces may be used in
10811place of brackets: @samp{@{1, 2, 3@}}, but the commas are required in
10812this case.
10813
10814Traditional vector and matrix arithmetic is also supported;
10815@pxref{Basic Arithmetic} and @pxref{Matrix Functions}.
10816Many other operations are applied to vectors element-wise. For example,
10817the complex conjugate of a vector is a vector of the complex conjugates
10818of its elements.
10819
10820@ignore
10821@starindex
10822@end ignore
10823@tindex vec
10824Algebraic functions for building vectors include @samp{vec(a, b, c)}
40ba43b4 10825to build @samp{[a, b, c]}, @samp{cvec(a, n, m)} to build an
4009494e
GM
10826@texline @math{n\times m}
10827@infoline @var{n}x@var{m}
10828matrix of @samp{a}s, and @samp{index(n)} to build a vector of integers
10829from 1 to @samp{n}.
10830
10831@node Strings, HMS Forms, Vectors and Matrices, Data Types
10832@section Strings
10833
10834@noindent
10835@kindex "
10836@cindex Strings
10837@cindex Character strings
10838Character strings are not a special data type in the Calculator.
10839Rather, a string is represented simply as a vector all of whose
10840elements are integers in the range 0 to 255 (ASCII codes). You can
10841enter a string at any time by pressing the @kbd{"} key. Quotation
10842marks and backslashes are written @samp{\"} and @samp{\\}, respectively,
10843inside strings. Other notations introduced by backslashes are:
10844
10845@example
10846@group
10847\a 7 \^@@ 0
10848\b 8 \^a-z 1-26
10849\e 27 \^[ 27
10850\f 12 \^\\ 28
10851\n 10 \^] 29
10852\r 13 \^^ 30
10853\t 9 \^_ 31
10854 \^? 127
10855@end group
10856@end example
10857
10858@noindent
10859Finally, a backslash followed by three octal digits produces any
10860character from its ASCII code.
10861
10862@kindex d "
10863@pindex calc-display-strings
10864Strings are normally displayed in vector-of-integers form. The
10865@w{@kbd{d "}} (@code{calc-display-strings}) command toggles a mode in
10866which any vectors of small integers are displayed as quoted strings
10867instead.
10868
10869The backslash notations shown above are also used for displaying
10870strings. Characters 128 and above are not translated by Calc; unless
10871you have an Emacs modified for 8-bit fonts, these will show up in
10872backslash-octal-digits notation. For characters below 32, and
10873for character 127, Calc uses the backslash-letter combination if
10874there is one, or otherwise uses a @samp{\^} sequence.
10875
10876The only Calc feature that uses strings is @dfn{compositions};
10877@pxref{Compositions}. Strings also provide a convenient
10878way to do conversions between ASCII characters and integers.
10879
10880@ignore
10881@starindex
10882@end ignore
10883@tindex string
10884There is a @code{string} function which provides a different display
10885format for strings. Basically, @samp{string(@var{s})}, where @var{s}
10886is a vector of integers in the proper range, is displayed as the
10887corresponding string of characters with no surrounding quotation
10888marks or other modifications. Thus @samp{string("ABC")} (or
10889@samp{string([65 66 67])}) will look like @samp{ABC} on the stack.
10890This happens regardless of whether @w{@kbd{d "}} has been used. The
10891only way to turn it off is to use @kbd{d U} (unformatted language
10892mode) which will display @samp{string("ABC")} instead.
10893
10894Control characters are displayed somewhat differently by @code{string}.
10895Characters below 32, and character 127, are shown using @samp{^} notation
10896(same as shown above, but without the backslash). The quote and
10897backslash characters are left alone, as are characters 128 and above.
10898
10899@ignore
10900@starindex
10901@end ignore
10902@tindex bstring
10903The @code{bstring} function is just like @code{string} except that
10904the resulting string is breakable across multiple lines if it doesn't
10905fit all on one line. Potential break points occur at every space
10906character in the string.
10907
10908@node HMS Forms, Date Forms, Strings, Data Types
10909@section HMS Forms
10910
10911@noindent
10912@cindex Hours-minutes-seconds forms
10913@cindex Degrees-minutes-seconds forms
10914@dfn{HMS} stands for Hours-Minutes-Seconds; when used as an angular
10915argument, the interpretation is Degrees-Minutes-Seconds. All functions
10916that operate on angles accept HMS forms. These are interpreted as
10917degrees regardless of the current angular mode. It is also possible to
10918use HMS as the angular mode so that calculated angles are expressed in
10919degrees, minutes, and seconds.
10920
10921@kindex @@
10922@ignore
10923@mindex @null
10924@end ignore
10925@kindex ' (HMS forms)
10926@ignore
10927@mindex @null
10928@end ignore
10929@kindex " (HMS forms)
10930@ignore
10931@mindex @null
10932@end ignore
10933@kindex h (HMS forms)
10934@ignore
10935@mindex @null
10936@end ignore
10937@kindex o (HMS forms)
10938@ignore
10939@mindex @null
10940@end ignore
10941@kindex m (HMS forms)
10942@ignore
10943@mindex @null
10944@end ignore
10945@kindex s (HMS forms)
10946The default format for HMS values is
10947@samp{@var{hours}@@ @var{mins}' @var{secs}"}. During entry, the letters
10948@samp{h} (for ``hours'') or
10949@samp{o} (approximating the ``degrees'' symbol) are accepted as well as
10950@samp{@@}, @samp{m} is accepted in place of @samp{'}, and @samp{s} is
10951accepted in place of @samp{"}.
10952The @var{hours} value is an integer (or integer-valued float).
10953The @var{mins} value is an integer or integer-valued float between 0 and 59.
10954The @var{secs} value is a real number between 0 (inclusive) and 60
10955(exclusive). A positive HMS form is interpreted as @var{hours} +
10956@var{mins}/60 + @var{secs}/3600. A negative HMS form is interpreted
10957as @mathit{- @var{hours}} @mathit{-} @var{mins}/60 @mathit{-} @var{secs}/3600.
10958Display format for HMS forms is quite flexible. @xref{HMS Formats}.
10959
10960HMS forms can be added and subtracted. When they are added to numbers,
10961the numbers are interpreted according to the current angular mode. HMS
10962forms can also be multiplied and divided by real numbers. Dividing
10963two HMS forms produces a real-valued ratio of the two angles.
10964
10965@pindex calc-time
10966@cindex Time of day
10967Just for kicks, @kbd{M-x calc-time} pushes the current time of day on
10968the stack as an HMS form.
10969
10970@node Date Forms, Modulo Forms, HMS Forms, Data Types
10971@section Date Forms
10972
10973@noindent
10974@cindex Date forms
10975A @dfn{date form} represents a date and possibly an associated time.
10976Simple date arithmetic is supported: Adding a number to a date
10977produces a new date shifted by that many days; adding an HMS form to
10978a date shifts it by that many hours. Subtracting two date forms
10979computes the number of days between them (represented as a simple
10980number). Many other operations, such as multiplying two date forms,
10981are nonsensical and are not allowed by Calc.
10982
10983Date forms are entered and displayed enclosed in @samp{< >} brackets.
10984The default format is, e.g., @samp{<Wed Jan 9, 1991>} for dates,
10985or @samp{<3:32:20pm Wed Jan 9, 1991>} for dates with times.
10986Input is flexible; date forms can be entered in any of the usual
10987notations for dates and times. @xref{Date Formats}.
10988
10989Date forms are stored internally as numbers, specifically the number
723da6aa 10990of days since midnight on the morning of December 31 of the year 1 BC.
4009494e
GM
10991If the internal number is an integer, the form represents a date only;
10992if the internal number is a fraction or float, the form represents
723da6aa 10993a date and time. For example, @samp{<6:00am Thu Jan 10, 1991>}
4009494e
GM
10994is represented by the number 726842.25. The standard precision of
1099512 decimal digits is enough to ensure that a (reasonable) date and
10996time can be stored without roundoff error.
10997
10998If the current precision is greater than 12, date forms will keep
10999additional digits in the seconds position. For example, if the
11000precision is 15, the seconds will keep three digits after the
11001decimal point. Decreasing the precision below 12 may cause the
11002time part of a date form to become inaccurate. This can also happen
11003if astronomically high years are used, though this will not be an
11004issue in everyday (or even everymillennium) use. Note that date
11005forms without times are stored as exact integers, so roundoff is
11006never an issue for them.
11007
11008You can use the @kbd{v p} (@code{calc-pack}) and @kbd{v u}
11009(@code{calc-unpack}) commands to get at the numerical representation
11010of a date form. @xref{Packing and Unpacking}.
11011
11012Date forms can go arbitrarily far into the future or past. Negative
310e60d9
PE
11013year numbers represent years BC. There is no ``year 0''; the day
11014before @samp{<Mon Jan 1, +1>} is @samp{<Sun Dec 31, -1>}. These are
11015days 1 and 0 respectively in Calc's internal numbering scheme. The
11016Gregorian calendar is used for all dates, including dates before the
723da6aa
JB
11017Gregorian calendar was invented (although that can be configured; see
11018below). Thus Calc's use of the day number @mathit{-10000} to
11019represent August 15, 28 BC should be taken with a grain of salt.
4009494e
GM
11020
11021@cindex Julian calendar
11022@cindex Gregorian calendar
11023Some historical background: The Julian calendar was created by
310e60d9
PE
11024Julius Caesar in the year 46 BC as an attempt to fix the confusion
11025caused by the irregular Roman calendar that was used before that time.
723da6aa
JB
11026The Julian calendar introduced an extra day in all years divisible by
11027four. After some initial confusion, the calendar was adopted around
11028the year we call 8 AD. Some centuries later it became
11029apparent that the Julian year of 365.25 days was itself not quite
11030right. In 1582 Pope Gregory XIII introduced the Gregorian calendar,
11031which added the new rule that years divisible by 100, but not by 400,
11032were not to be considered leap years despite being divisible by four.
11033Many countries delayed adoption of the Gregorian calendar
11034because of religious differences. For example, Great Britain and the
11035British colonies switched to the Gregorian calendar in September
110361752, when the Julian calendar was eleven days behind the
11037Gregorian calendar. That year in Britain, the day after September 2
11038was September 14. To take another example, Russia did not adopt the
11039Gregorian calendar until 1918, and that year in Russia the day after
11040January 31 was February 14. Calc's reckoning therefore matches English
11041practice starting in 1752 and Russian practice starting in 1918, but
11042disagrees with earlier dates in both countries.
11043
11044When the Julian calendar was introduced, it had January 1 as the first
11045day of the year. By the Middle Ages, many European countries
11046had changed the beginning of a new year to a different date, often to
11047a religious festival. Almost all countries reverted to using January 1
11048as the beginning of the year by the time they adopted the Gregorian
11049calendar.
11050
11051Some calendars attempt to mimic the historical situation by using the
11052Gregorian calendar for recent dates and the Julian calendar for older
11053dates. The @code{cal} program in most Unix implementations does this,
11054for example. While January 1 wasn't always the beginning of a calendar
11055year, these hybrid calendars still use January 1 as the beginning of
11056the year even for older dates. The customizable variable
11057@code{calc-gregorian-switch} (@pxref{Customizing Calc}) can be set to
11058have Calc's date forms switch from the Julian to Gregorian calendar at
11059any specified date.
11060
11061Today's timekeepers introduce an occasional ``leap second''.
11062These do not occur regularly and Calc does not take these minor
11063effects into account. (If it did, it would have to report a
11064non-integer number of days between, say,
11065@samp{<12:00am Mon Jan 1, 1900>} and
4009494e
GM
11066@samp{<12:00am Sat Jan 1, 2000>}.)
11067
4009494e 11068@cindex Julian day counting
7c1a0036 11069Another day counting system in common use is, confusingly, also called
4c39f404
CY
11070``Julian.'' The Julian day number is the numbers of days since
1107112:00 noon (GMT) on Jan 1, 4713 BC, which in Calc's scheme (in GMT)
db78a8cb 11072is @mathit{-1721423.5} (recall that Calc starts at midnight instead
7c1a0036
GM
11073of noon). Thus to convert a Calc date code obtained by unpacking a
11074date form into a Julian day number, simply add 1721423.5 after
11075compensating for the time zone difference. The built-in @kbd{t J}
11076command performs this conversion for you.
11077
4c39f404 11078The Julian day number is based on the Julian cycle, which was invented
7c1a0036 11079in 1583 by Joseph Justus Scaliger. Scaliger named it the Julian cycle
4c39f404 11080since it involves the Julian calendar, but some have suggested that
7c1a0036 11081Scaliger named it in honor of his father, Julius Caesar Scaliger. The
4c39f404
CY
11082Julian cycle is based on three other cycles: the indiction cycle, the
11083Metonic cycle, and the solar cycle. The indiction cycle is a 15 year
11084cycle originally used by the Romans for tax purposes but later used to
11085date medieval documents. The Metonic cycle is a 19 year cycle; 19
11086years is close to being a common multiple of a solar year and a lunar
11087month, and so every 19 years the phases of the moon will occur on the
11088same days of the year. The solar cycle is a 28 year cycle; the Julian
11089calendar repeats itself every 28 years. The smallest time period
11090which contains multiples of all three cycles is the least common
11091multiple of 15 years, 19 years and 28 years, which (since they're
11092pairwise relatively prime) is
7c1a0036
GM
11093@texline @math{15\times 19\times 28 = 7980} years.
11094@infoline 15*19*28 = 7980 years.
11095This is the length of a Julian cycle. Working backwards, the previous
9858f6c3 11096year in which all three cycles began was 4713 BC, and so Scaliger
7c1a0036
GM
11097chose that year as the beginning of a Julian cycle. Since at the time
11098there were no historical records from before 4713 BC, using this year
11099as a starting point had the advantage of avoiding negative year
11100numbers. In 1849, the astronomer John Herschel (son of William
11101Herschel) suggested using the number of days since the beginning of
11102the Julian cycle as an astronomical dating system; this idea was taken
11103up by other astronomers. (At the time, noon was the start of the
11104astronomical day. Herschel originally suggested counting the days
11105since Jan 1, 4713 BC at noon Alexandria time; this was later amended to
11106noon GMT.) Julian day numbering is largely used in astronomy.
4009494e
GM
11107
11108@cindex Unix time format
11109The Unix operating system measures time as an integer number of
11110seconds since midnight, Jan 1, 1970. To convert a Calc date
11111value into a Unix time stamp, first subtract 719164 (the code
11112for @samp{<Jan 1, 1970>}), then multiply by 86400 (the number of
11113seconds in a day) and press @kbd{R} to round to the nearest
11114integer. If you have a date form, you can simply subtract the
11115day @samp{<Jan 1, 1970>} instead of unpacking and subtracting
11116719164. Likewise, divide by 86400 and add @samp{<Jan 1, 1970>}
11117to convert from Unix time to a Calc date form. (Note that
11118Unix normally maintains the time in the GMT time zone; you may
11119need to subtract five hours to get New York time, or eight hours
11120for California time. The same is usually true of Julian day
11121counts.) The built-in @kbd{t U} command performs these
11122conversions.
11123
11124@node Modulo Forms, Error Forms, Date Forms, Data Types
11125@section Modulo Forms
11126
11127@noindent
11128@cindex Modulo forms
11129A @dfn{modulo form} is a real number which is taken modulo (i.e., within
11130an integer multiple of) some value @var{M}. Arithmetic modulo @var{M}
11131often arises in number theory. Modulo forms are written
11132`@var{a} @tfn{mod} @var{M}',
11133where @var{a} and @var{M} are real numbers or HMS forms, and
11134@texline @math{0 \le a < M}.
11135@infoline @expr{0 <= a < @var{M}}.
11136In many applications @expr{a} and @expr{M} will be
11137integers but this is not required.
11138
11139@ignore
11140@mindex M
11141@end ignore
11142@kindex M (modulo forms)
11143@ignore
11144@mindex mod
11145@end ignore
11146@tindex mod (operator)
11147To create a modulo form during numeric entry, press the shift-@kbd{M}
11148key to enter the word @samp{mod}. As a special convenience, pressing
11149shift-@kbd{M} a second time automatically enters the value of @expr{M}
11150that was most recently used before. During algebraic entry, either
11151type @samp{mod} by hand or press @kbd{M-m} (that's @kbd{@key{META}-m}).
11152Once again, pressing this a second time enters the current modulo.
11153
11154Modulo forms are not to be confused with the modulo operator @samp{%}.
11155The expression @samp{27 % 10} means to compute 27 modulo 10 to produce
11156the result 7. Further computations treat this 7 as just a regular integer.
11157The expression @samp{27 mod 10} produces the result @samp{7 mod 10};
11158further computations with this value are again reduced modulo 10 so that
11159the result always lies in the desired range.
11160
11161When two modulo forms with identical @expr{M}'s are added or multiplied,
11162the Calculator simply adds or multiplies the values, then reduces modulo
11163@expr{M}. If one argument is a modulo form and the other a plain number,
11164the plain number is treated like a compatible modulo form. It is also
11165possible to raise modulo forms to powers; the result is the value raised
11166to the power, then reduced modulo @expr{M}. (When all values involved
11167are integers, this calculation is done much more efficiently than
11168actually computing the power and then reducing.)
11169
11170@cindex Modulo division
11171Two modulo forms `@var{a} @tfn{mod} @var{M}' and `@var{b} @tfn{mod} @var{M}'
11172can be divided if @expr{a}, @expr{b}, and @expr{M} are all
11173integers. The result is the modulo form which, when multiplied by
11174`@var{b} @tfn{mod} @var{M}', produces `@var{a} @tfn{mod} @var{M}'. If
11175there is no solution to this equation (which can happen only when
11176@expr{M} is non-prime), or if any of the arguments are non-integers, the
11177division is left in symbolic form. Other operations, such as square
11178roots, are not yet supported for modulo forms. (Note that, although
11179@w{`@tfn{(}@var{a} @tfn{mod} @var{M}@tfn{)^.5}'} will compute a ``modulo square root''
40ba43b4 11180in the sense of reducing
4009494e 11181@texline @math{\sqrt a}
40ba43b4 11182@infoline @expr{sqrt(a)}
4009494e
GM
11183modulo @expr{M}, this is not a useful definition from the
11184number-theoretical point of view.)
11185
11186It is possible to mix HMS forms and modulo forms. For example, an
11187HMS form modulo 24 could be used to manipulate clock times; an HMS
11188form modulo 360 would be suitable for angles. Making the modulo @expr{M}
11189also be an HMS form eliminates troubles that would arise if the angular
11190mode were inadvertently set to Radians, in which case
11191@w{@samp{2@@ 0' 0" mod 24}} would be interpreted as two degrees modulo
1119224 radians!
11193
11194Modulo forms cannot have variables or formulas for components. If you
11195enter the formula @samp{(x + 2) mod 5}, Calc propagates the modulus
11196to each of the coefficients: @samp{(1 mod 5) x + (2 mod 5)}.
11197
11198You can use @kbd{v p} and @kbd{%} to modify modulo forms.
11199@xref{Packing and Unpacking}. @xref{Basic Arithmetic}.
11200
11201@ignore
11202@starindex
11203@end ignore
11204@tindex makemod
11205The algebraic function @samp{makemod(a, m)} builds the modulo form
11206@w{@samp{a mod m}}.
11207
11208@node Error Forms, Interval Forms, Modulo Forms, Data Types
11209@section Error Forms
11210
11211@noindent
11212@cindex Error forms
11213@cindex Standard deviations
11214An @dfn{error form} is a number with an associated standard
11215deviation, as in @samp{2.3 +/- 0.12}. The notation
40ba43b4
PE
11216@texline `@var{x} @tfn{+/-} @math{\sigma}'
11217@infoline `@var{x} @tfn{+/-} sigma'
4009494e
GM
11218stands for an uncertain value which follows
11219a normal or Gaussian distribution of mean @expr{x} and standard
40ba43b4 11220deviation or ``error''
4009494e
GM
11221@texline @math{\sigma}.
11222@infoline @expr{sigma}.
11223Both the mean and the error can be either numbers or
11224formulas. Generally these are real numbers but the mean may also be
11225complex. If the error is negative or complex, it is changed to its
11226absolute value. An error form with zero error is converted to a
11227regular number by the Calculator.
11228
11229All arithmetic and transcendental functions accept error forms as input.
11230Operations on the mean-value part work just like operations on regular
40ba43b4 11231numbers. The error part for any function @expr{f(x)} (such as
4009494e
GM
11232@texline @math{\sin x}
11233@infoline @expr{sin(x)})
11234is defined by the error of @expr{x} times the derivative of @expr{f}
11235evaluated at the mean value of @expr{x}. For a two-argument function
11236@expr{f(x,y)} (such as addition) the error is the square root of the sum
11237of the squares of the errors due to @expr{x} and @expr{y}.
11238@tex
11239$$ \eqalign{
11240 f(x \hbox{\code{ +/- }} \sigma)
11241 &= f(x) \hbox{\code{ +/- }} \sigma \left| {df(x) \over dx} \right| \cr
11242 f(x \hbox{\code{ +/- }} \sigma_x, y \hbox{\code{ +/- }} \sigma_y)
11243 &= f(x,y) \hbox{\code{ +/- }}
11244 \sqrt{\left(\sigma_x \left| {\partial f(x,y) \over \partial x}
11245 \right| \right)^2
11246 +\left(\sigma_y \left| {\partial f(x,y) \over \partial y}
11247 \right| \right)^2 } \cr
11248} $$
11249@end tex
11250Note that this
11251definition assumes the errors in @expr{x} and @expr{y} are uncorrelated.
11252A side effect of this definition is that @samp{(2 +/- 1) * (2 +/- 1)}
11253is not the same as @samp{(2 +/- 1)^2}; the former represents the product
11254of two independent values which happen to have the same probability
11255distributions, and the latter is the product of one random value with itself.
11256The former will produce an answer with less error, since on the average
11257the two independent errors can be expected to cancel out.
11258
11259Consult a good text on error analysis for a discussion of the proper use
11260of standard deviations. Actual errors often are neither Gaussian-distributed
11261nor uncorrelated, and the above formulas are valid only when errors
11262are small. As an example, the error arising from
40ba43b4
PE
11263@texline `@tfn{sin(}@var{x} @tfn{+/-} @math{\sigma}@tfn{)}'
11264@infoline `@tfn{sin(}@var{x} @tfn{+/-} @var{sigma}@tfn{)}'
11265is
11266@texline `@math{\sigma} @tfn{abs(cos(}@var{x}@tfn{))}'.
11267@infoline `@var{sigma} @tfn{abs(cos(}@var{x}@tfn{))}'.
4009494e
GM
11268When @expr{x} is close to zero,
11269@texline @math{\cos x}
40ba43b4
PE
11270@infoline @expr{cos(x)}
11271is close to one so the error in the sine is close to
4009494e
GM
11272@texline @math{\sigma};
11273@infoline @expr{sigma};
40ba43b4 11274this makes sense, since
4009494e 11275@texline @math{\sin x}
40ba43b4 11276@infoline @expr{sin(x)}
4009494e
GM
11277is approximately @expr{x} near zero, so a given error in @expr{x} will
11278produce about the same error in the sine. Likewise, near 90 degrees
11279@texline @math{\cos x}
40ba43b4 11280@infoline @expr{cos(x)}
4009494e
GM
11281is nearly zero and so the computed error is
11282small: The sine curve is nearly flat in that region, so an error in @expr{x}
40ba43b4 11283has relatively little effect on the value of
4009494e 11284@texline @math{\sin x}.
40ba43b4 11285@infoline @expr{sin(x)}.
4009494e
GM
11286However, consider @samp{sin(90 +/- 1000)}. The cosine of 90 is zero, so
11287Calc will report zero error! We get an obviously wrong result because
11288we have violated the small-error approximation underlying the error
11289analysis. If the error in @expr{x} had been small, the error in
11290@texline @math{\sin x}
40ba43b4 11291@infoline @expr{sin(x)}
4009494e
GM
11292would indeed have been negligible.
11293
11294@ignore
11295@mindex p
11296@end ignore
11297@kindex p (error forms)
11298@tindex +/-
11299To enter an error form during regular numeric entry, use the @kbd{p}
11300(``plus-or-minus'') key to type the @samp{+/-} symbol. (If you try actually
11301typing @samp{+/-} the @kbd{+} key will be interpreted as the Calculator's
11302@kbd{+} command!) Within an algebraic formula, you can press @kbd{M-+} to
11303type the @samp{+/-} symbol, or type it out by hand.
11304
11305Error forms and complex numbers can be mixed; the formulas shown above
11306are used for complex numbers, too; note that if the error part evaluates
11307to a complex number its absolute value (or the square root of the sum of
11308the squares of the absolute values of the two error contributions) is
11309used. Mathematically, this corresponds to a radially symmetric Gaussian
11310distribution of numbers on the complex plane. However, note that Calc
11311considers an error form with real components to represent a real number,
11312not a complex distribution around a real mean.
11313
11314Error forms may also be composed of HMS forms. For best results, both
11315the mean and the error should be HMS forms if either one is.
11316
11317@ignore
11318@starindex
11319@end ignore
11320@tindex sdev
11321The algebraic function @samp{sdev(a, b)} builds the error form @samp{a +/- b}.
11322
11323@node Interval Forms, Incomplete Objects, Error Forms, Data Types
11324@section Interval Forms
11325
11326@noindent
11327@cindex Interval forms
11328An @dfn{interval} is a subset of consecutive real numbers. For example,
11329the interval @samp{[2 ..@: 4]} represents all the numbers from 2 to 4,
11330inclusive. If you multiply it by the interval @samp{[0.5 ..@: 2]} you
11331obtain @samp{[1 ..@: 8]}. This calculation represents the fact that if
11332you multiply some number in the range @samp{[2 ..@: 4]} by some other
11333number in the range @samp{[0.5 ..@: 2]}, your result will lie in the range
11334from 1 to 8. Interval arithmetic is used to get a worst-case estimate
11335of the possible range of values a computation will produce, given the
11336set of possible values of the input.
11337
11338@ifnottex
11339Calc supports several varieties of intervals, including @dfn{closed}
11340intervals of the type shown above, @dfn{open} intervals such as
11341@samp{(2 ..@: 4)}, which represents the range of numbers from 2 to 4
11342@emph{exclusive}, and @dfn{semi-open} intervals in which one end
11343uses a round parenthesis and the other a square bracket. In mathematical
11344terms,
11345@samp{[2 ..@: 4]} means @expr{2 <= x <= 4}, whereas
11346@samp{[2 ..@: 4)} represents @expr{2 <= x < 4},
11347@samp{(2 ..@: 4]} represents @expr{2 < x <= 4}, and
11348@samp{(2 ..@: 4)} represents @expr{2 < x < 4}.
11349@end ifnottex
11350@tex
11351Calc supports several varieties of intervals, including \dfn{closed}
11352intervals of the type shown above, \dfn{open} intervals such as
11353\samp{(2 ..\: 4)}, which represents the range of numbers from 2 to 4
11354\emph{exclusive}, and \dfn{semi-open} intervals in which one end
11355uses a round parenthesis and the other a square bracket. In mathematical
11356terms,
11357$$ \eqalign{
11358 [2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 \le x \le 4 \cr
11359 [2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 \le x < 4 \cr
11360 (2 \hbox{\cite{..}} 4] &\quad\hbox{means}\quad 2 < x \le 4 \cr
11361 (2 \hbox{\cite{..}} 4) &\quad\hbox{means}\quad 2 < x < 4 \cr
11362} $$
11363@end tex
11364
11365The lower and upper limits of an interval must be either real numbers
11366(or HMS or date forms), or symbolic expressions which are assumed to be
11367real-valued, or @samp{-inf} and @samp{inf}. In general the lower limit
11368must be less than the upper limit. A closed interval containing only
11369one value, @samp{[3 ..@: 3]}, is converted to a plain number (3)
11370automatically. An interval containing no values at all (such as
11371@samp{[3 ..@: 2]} or @samp{[2 ..@: 2)}) can be represented but is not
11372guaranteed to behave well when used in arithmetic. Note that the
11373interval @samp{[3 .. inf)} represents all real numbers greater than
11374or equal to 3, and @samp{(-inf .. inf)} represents all real numbers.
11375In fact, @samp{[-inf .. inf]} represents all real numbers including
11376the real infinities.
11377
11378Intervals are entered in the notation shown here, either as algebraic
11379formulas, or using incomplete forms. (@xref{Incomplete Objects}.)
11380In algebraic formulas, multiple periods in a row are collected from
11381left to right, so that @samp{1...1e2} is interpreted as @samp{1.0 ..@: 1e2}
11382rather than @samp{1 ..@: 0.1e2}. Add spaces or zeros if you want to
11383get the other interpretation. If you omit the lower or upper limit,
11384a default of @samp{-inf} or @samp{inf} (respectively) is furnished.
11385
11386Infinite mode also affects operations on intervals
11387(@pxref{Infinities}). Calc will always introduce an open infinity,
11388as in @samp{1 / (0 .. 2] = [0.5 .. inf)}. But closed infinities,
11389@w{@samp{1 / [0 .. 2] = [0.5 .. inf]}}, arise only in Infinite mode;
11390otherwise they are left unevaluated. Note that the ``direction'' of
11391a zero is not an issue in this case since the zero is always assumed
11392to be continuous with the rest of the interval. For intervals that
11393contain zero inside them Calc is forced to give the result,
11394@samp{1 / (-2 .. 2) = [-inf .. inf]}.
11395
11396While it may seem that intervals and error forms are similar, they are
11397based on entirely different concepts of inexact quantities. An error
40ba43b4
PE
11398form
11399@texline `@var{x} @tfn{+/-} @math{\sigma}'
11400@infoline `@var{x} @tfn{+/-} @var{sigma}'
4009494e 11401means a variable is random, and its value could
40ba43b4
PE
11402be anything but is ``probably'' within one
11403@texline @math{\sigma}
11404@infoline @var{sigma}
11405of the mean value @expr{x}. An interval
4009494e
GM
11406`@tfn{[}@var{a} @tfn{..@:} @var{b}@tfn{]}' means a
11407variable's value is unknown, but guaranteed to lie in the specified
11408range. Error forms are statistical or ``average case'' approximations;
11409interval arithmetic tends to produce ``worst case'' bounds on an
11410answer.
11411
11412Intervals may not contain complex numbers, but they may contain
11413HMS forms or date forms.
11414
11415@xref{Set Operations}, for commands that interpret interval forms
11416as subsets of the set of real numbers.
11417
11418@ignore
11419@starindex
11420@end ignore
11421@tindex intv
11422The algebraic function @samp{intv(n, a, b)} builds an interval form
11423from @samp{a} to @samp{b}; @samp{n} is an integer code which must
11424be 0 for @samp{(..)}, 1 for @samp{(..]}, 2 for @samp{[..)}, or
114253 for @samp{[..]}.
11426
11427Please note that in fully rigorous interval arithmetic, care would be
11428taken to make sure that the computation of the lower bound rounds toward
11429minus infinity, while upper bound computations round toward plus
11430infinity. Calc's arithmetic always uses a round-to-nearest mode,
11431which means that roundoff errors could creep into an interval
11432calculation to produce intervals slightly smaller than they ought to
11433be. For example, entering @samp{[1..2]} and pressing @kbd{Q 2 ^}
11434should yield the interval @samp{[1..2]} again, but in fact it yields the
11435(slightly too small) interval @samp{[1..1.9999999]} due to roundoff
11436error.
11437
11438@node Incomplete Objects, Variables, Interval Forms, Data Types
11439@section Incomplete Objects
11440
11441@noindent
11442@ignore
11443@mindex [ ]
11444@end ignore
11445@kindex [
11446@ignore
11447@mindex ( )
11448@end ignore
11449@kindex (
11450@kindex ,
11451@ignore
11452@mindex @null
11453@end ignore
11454@kindex ]
11455@ignore
11456@mindex @null
11457@end ignore
11458@kindex )
11459@cindex Incomplete vectors
11460@cindex Incomplete complex numbers
11461@cindex Incomplete interval forms
11462When @kbd{(} or @kbd{[} is typed to begin entering a complex number or
11463vector, respectively, the effect is to push an @dfn{incomplete} complex
11464number or vector onto the stack. The @kbd{,} key adds the value(s) at
11465the top of the stack onto the current incomplete object. The @kbd{)}
11466and @kbd{]} keys ``close'' the incomplete object after adding any values
11467on the top of the stack in front of the incomplete object.
11468
11469As a result, the sequence of keystrokes @kbd{[ 2 , 3 @key{RET} 2 * , 9 ]}
11470pushes the vector @samp{[2, 6, 9]} onto the stack. Likewise, @kbd{( 1 , 2 Q )}
11471pushes the complex number @samp{(1, 1.414)} (approximately).
11472
11473If several values lie on the stack in front of the incomplete object,
11474all are collected and appended to the object. Thus the @kbd{,} key
11475is redundant: @kbd{[ 2 @key{RET} 3 @key{RET} 2 * 9 ]}. Some people
11476prefer the equivalent @key{SPC} key to @key{RET}.
11477
11478As a special case, typing @kbd{,} immediately after @kbd{(}, @kbd{[}, or
11479@kbd{,} adds a zero or duplicates the preceding value in the list being
11480formed. Typing @key{DEL} during incomplete entry removes the last item
11481from the list.
11482
11483@kindex ;
11484The @kbd{;} key is used in the same way as @kbd{,} to create polar complex
11485numbers: @kbd{( 1 ; 2 )}. When entering a vector, @kbd{;} is useful for
11486creating a matrix. In particular, @kbd{[ [ 1 , 2 ; 3 , 4 ; 5 , 6 ] ]} is
11487equivalent to @kbd{[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]}.
11488
11489@kindex ..
11490@pindex calc-dots
11491Incomplete entry is also used to enter intervals. For example,
11492@kbd{[ 2 ..@: 4 )} enters a semi-open interval. Note that when you type
11493the first period, it will be interpreted as a decimal point, but when
11494you type a second period immediately afterward, it is re-interpreted as
11495part of the interval symbol. Typing @kbd{..} corresponds to executing
11496the @code{calc-dots} command.
11497
11498If you find incomplete entry distracting, you may wish to enter vectors
11499and complex numbers as algebraic formulas by pressing the apostrophe key.
11500
11501@node Variables, Formulas, Incomplete Objects, Data Types
11502@section Variables
11503
11504@noindent
11505@cindex Variables, in formulas
11506A @dfn{variable} is somewhere between a storage register on a conventional
11507calculator, and a variable in a programming language. (In fact, a Calc
11508variable is really just an Emacs Lisp variable that contains a Calc number
11509or formula.) A variable's name is normally composed of letters and digits.
11510Calc also allows apostrophes and @code{#} signs in variable names.
11511(The Calc variable @code{foo} corresponds to the Emacs Lisp variable
11512@code{var-foo}, but unless you access the variable from within Emacs
11513Lisp, you don't need to worry about it. Variable names in algebraic
11514formulas implicitly have @samp{var-} prefixed to their names. The
11515@samp{#} character in variable names used in algebraic formulas
11516corresponds to a dash @samp{-} in the Lisp variable name. If the name
11517contains any dashes, the prefix @samp{var-} is @emph{not} automatically
11518added. Thus the two formulas @samp{foo + 1} and @samp{var#foo + 1} both
11519refer to the same variable.)
11520
11521In a command that takes a variable name, you can either type the full
11522name of a variable, or type a single digit to use one of the special
11523convenience variables @code{q0} through @code{q9}. For example,
11524@kbd{3 s s 2} stores the number 3 in variable @code{q2}, and
11525@w{@kbd{3 s s foo @key{RET}}} stores that number in variable
11526@code{foo}.
11527
11528To push a variable itself (as opposed to the variable's value) on the
11529stack, enter its name as an algebraic expression using the apostrophe
11530(@key{'}) key.
11531
11532@kindex =
11533@pindex calc-evaluate
11534@cindex Evaluation of variables in a formula
11535@cindex Variables, evaluation
11536@cindex Formulas, evaluation
11537The @kbd{=} (@code{calc-evaluate}) key ``evaluates'' a formula by
11538replacing all variables in the formula which have been given values by a
11539@code{calc-store} or @code{calc-let} command by their stored values.
11540Other variables are left alone. Thus a variable that has not been
11541stored acts like an abstract variable in algebra; a variable that has
11542been stored acts more like a register in a traditional calculator.
11543With a positive numeric prefix argument, @kbd{=} evaluates the top
11544@var{n} stack entries; with a negative argument, @kbd{=} evaluates
11545the @var{n}th stack entry.
11546
11547@cindex @code{e} variable
11548@cindex @code{pi} variable
11549@cindex @code{i} variable
11550@cindex @code{phi} variable
11551@cindex @code{gamma} variable
11552@vindex e
11553@vindex pi
11554@vindex i
11555@vindex phi
11556@vindex gamma
11557A few variables are called @dfn{special constants}. Their names are
11558@samp{e}, @samp{pi}, @samp{i}, @samp{phi}, and @samp{gamma}.
11559(@xref{Scientific Functions}.) When they are evaluated with @kbd{=},
11560their values are calculated if necessary according to the current precision
11561or complex polar mode. If you wish to use these symbols for other purposes,
11562simply undefine or redefine them using @code{calc-store}.
11563
11564The variables @samp{inf}, @samp{uinf}, and @samp{nan} stand for
11565infinite or indeterminate values. It's best not to use them as
11566regular variables, since Calc uses special algebraic rules when
11567it manipulates them. Calc displays a warning message if you store
11568a value into any of these special variables.
11569
11570@xref{Store and Recall}, for a discussion of commands dealing with variables.
11571
11572@node Formulas, , Variables, Data Types
11573@section Formulas
11574
11575@noindent
11576@cindex Formulas
11577@cindex Expressions
11578@cindex Operators in formulas
11579@cindex Precedence of operators
11580When you press the apostrophe key you may enter any expression or formula
11581in algebraic form. (Calc uses the terms ``expression'' and ``formula''
11582interchangeably.) An expression is built up of numbers, variable names,
11583and function calls, combined with various arithmetic operators.
11584Parentheses may
11585be used to indicate grouping. Spaces are ignored within formulas, except
11586that spaces are not permitted within variable names or numbers.
11587Arithmetic operators, in order from highest to lowest precedence, and
11588with their equivalent function names, are:
11589
11590@samp{_} [@code{subscr}] (subscripts);
11591
11592postfix @samp{%} [@code{percent}] (as in @samp{25% = 0.25});
11593
0edd2970 11594prefix @samp{!} [@code{lnot}] (logical ``not,'' as in @samp{!x});
4009494e
GM
11595
11596@samp{+/-} [@code{sdev}] (the standard deviation symbol) and
11597@samp{mod} [@code{makemod}] (the symbol for modulo forms);
11598
11599postfix @samp{!} [@code{fact}] (factorial, as in @samp{n!})
11600and postfix @samp{!!} [@code{dfact}] (double factorial);
11601
11602@samp{^} [@code{pow}] (raised-to-the-power-of);
11603
0edd2970
JB
11604prefix @samp{+} and @samp{-} [@code{neg}] (as in @samp{-x});
11605
4009494e
GM
11606@samp{*} [@code{mul}];
11607
11608@samp{/} [@code{div}], @samp{%} [@code{mod}] (modulo), and
11609@samp{\} [@code{idiv}] (integer division);
11610
11611infix @samp{+} [@code{add}] and @samp{-} [@code{sub}] (as in @samp{x-y});
11612
11613@samp{|} [@code{vconcat}] (vector concatenation);
11614
11615relations @samp{=} [@code{eq}], @samp{!=} [@code{neq}], @samp{<} [@code{lt}],
11616@samp{>} [@code{gt}], @samp{<=} [@code{leq}], and @samp{>=} [@code{geq}];
11617
11618@samp{&&} [@code{land}] (logical ``and'');
11619
11620@samp{||} [@code{lor}] (logical ``or'');
11621
11622the C-style ``if'' operator @samp{a?b:c} [@code{if}];
11623
11624@samp{!!!} [@code{pnot}] (rewrite pattern ``not'');
11625
11626@samp{&&&} [@code{pand}] (rewrite pattern ``and'');
11627
11628@samp{|||} [@code{por}] (rewrite pattern ``or'');
11629
11630@samp{:=} [@code{assign}] (for assignments and rewrite rules);
11631
11632@samp{::} [@code{condition}] (rewrite pattern condition);
11633
11634@samp{=>} [@code{evalto}].
11635
11636Note that, unlike in usual computer notation, multiplication binds more
40ba43b4 11637strongly than division: @samp{a*b/c*d} is equivalent to
4009494e
GM
11638@texline @math{a b \over c d}.
11639@infoline @expr{(a*b)/(c*d)}.
11640
11641@cindex Multiplication, implicit
11642@cindex Implicit multiplication
11643The multiplication sign @samp{*} may be omitted in many cases. In particular,
11644if the righthand side is a number, variable name, or parenthesized
11645expression, the @samp{*} may be omitted. Implicit multiplication has the
11646same precedence as the explicit @samp{*} operator. The one exception to
11647the rule is that a variable name followed by a parenthesized expression,
11648as in @samp{f(x)},
11649is interpreted as a function call, not an implicit @samp{*}. In many
11650cases you must use a space if you omit the @samp{*}: @samp{2a} is the
11651same as @samp{2*a}, and @samp{a b} is the same as @samp{a*b}, but @samp{ab}
11652is a variable called @code{ab}, @emph{not} the product of @samp{a} and
11653@samp{b}! Also note that @samp{f (x)} is still a function call.
11654
11655@cindex Implicit comma in vectors
11656The rules are slightly different for vectors written with square brackets.
11657In vectors, the space character is interpreted (like the comma) as a
11658separator of elements of the vector. Thus @w{@samp{[ 2a b+c d ]}} is
11659equivalent to @samp{[2*a, b+c, d]}, whereas @samp{2a b+c d} is equivalent
11660to @samp{2*a*b + c*d}.
11661Note that spaces around the brackets, and around explicit commas, are
11662ignored. To force spaces to be interpreted as multiplication you can
11663enclose a formula in parentheses as in @samp{[(a b) 2(c d)]}, which is
11664interpreted as @samp{[a*b, 2*c*d]}. An implicit comma is also inserted
11665between @samp{][}, as in the matrix @samp{[[1 2][3 4]]}.
11666
11667Vectors that contain commas (not embedded within nested parentheses or
11668brackets) do not treat spaces specially: @samp{[a b, 2 c d]} is a vector
11669of two elements. Also, if it would be an error to treat spaces as
11670separators, but not otherwise, then Calc will ignore spaces:
11671@w{@samp{[a - b]}} is a vector of one element, but @w{@samp{[a -b]}} is
11672a vector of two elements. Finally, vectors entered with curly braces
11673instead of square brackets do not give spaces any special treatment.
11674When Calc displays a vector that does not contain any commas, it will
11675insert parentheses if necessary to make the meaning clear:
11676@w{@samp{[(a b)]}}.
11677
11678The expression @samp{5%-2} is ambiguous; is this five-percent minus two,
11679or five modulo minus-two? Calc always interprets the leftmost symbol as
11680an infix operator preferentially (modulo, in this case), so you would
11681need to write @samp{(5%)-2} to get the former interpretation.
11682
11683@cindex Function call notation
11684A function call is, e.g., @samp{sin(1+x)}. (The Calc algebraic function
11685@code{foo} corresponds to the Emacs Lisp function @code{calcFunc-foo},
11686but unless you access the function from within Emacs Lisp, you don't
11687need to worry about it.) Most mathematical Calculator commands like
11688@code{calc-sin} have function equivalents like @code{sin}.
11689If no Lisp function is defined for a function called by a formula, the
11690call is left as it is during algebraic manipulation: @samp{f(x+y)} is
11691left alone. Beware that many innocent-looking short names like @code{in}
11692and @code{re} have predefined meanings which could surprise you; however,
11693single letters or single letters followed by digits are always safe to
11694use for your own function names. @xref{Function Index}.
11695
11696In the documentation for particular commands, the notation @kbd{H S}
11697(@code{calc-sinh}) [@code{sinh}] means that the key sequence @kbd{H S}, the
11698command @kbd{M-x calc-sinh}, and the algebraic function @code{sinh(x)} all
11699represent the same operation.
11700
11701Commands that interpret (``parse'') text as algebraic formulas include
11702algebraic entry (@kbd{'}), editing commands like @kbd{`} which parse
11703the contents of the editing buffer when you finish, the @kbd{C-x * g}
11704and @w{@kbd{C-x * r}} commands, the @kbd{C-y} command, the X window system
11705``paste'' mouse operation, and Embedded mode. All of these operations
11706use the same rules for parsing formulas; in particular, language modes
11707(@pxref{Language Modes}) affect them all in the same way.
11708
11709When you read a large amount of text into the Calculator (say a vector
11710which represents a big set of rewrite rules; @pxref{Rewrite Rules}),
11711you may wish to include comments in the text. Calc's formula parser
11712ignores the symbol @samp{%%} and anything following it on a line:
11713
11714@example
11715[ a + b, %% the sum of "a" and "b"
11716 c + d,
11717 %% last line is coming up:
11718 e + f ]
11719@end example
11720
11721@noindent
11722This is parsed exactly the same as @samp{[ a + b, c + d, e + f ]}.
11723
11724@xref{Syntax Tables}, for a way to create your own operators and other
11725input notations. @xref{Compositions}, for a way to create new display
11726formats.
11727
11728@xref{Algebra}, for commands for manipulating formulas symbolically.
11729
11730@node Stack and Trail, Mode Settings, Data Types, Top
11731@chapter Stack and Trail Commands
11732
11733@noindent
11734This chapter describes the Calc commands for manipulating objects on the
11735stack and in the trail buffer. (These commands operate on objects of any
11736type, such as numbers, vectors, formulas, and incomplete objects.)
11737
11738@menu
11739* Stack Manipulation::
11740* Editing Stack Entries::
11741* Trail Commands::
11742* Keep Arguments::
11743@end menu
11744
11745@node Stack Manipulation, Editing Stack Entries, Stack and Trail, Stack and Trail
11746@section Stack Manipulation Commands
11747
11748@noindent
11749@kindex @key{RET}
11750@kindex @key{SPC}
11751@pindex calc-enter
11752@cindex Duplicating stack entries
11753To duplicate the top object on the stack, press @key{RET} or @key{SPC}
11754(two equivalent keys for the @code{calc-enter} command).
11755Given a positive numeric prefix argument, these commands duplicate
11756several elements at the top of the stack.
11757Given a negative argument,
11758these commands duplicate the specified element of the stack.
11759Given an argument of zero, they duplicate the entire stack.
11760For example, with @samp{10 20 30} on the stack,
11761@key{RET} creates @samp{10 20 30 30},
11762@kbd{C-u 2 @key{RET}} creates @samp{10 20 30 20 30},
11763@kbd{C-u - 2 @key{RET}} creates @samp{10 20 30 20}, and
11764@kbd{C-u 0 @key{RET}} creates @samp{10 20 30 10 20 30}.
11765
11766@kindex @key{LFD}
11767@pindex calc-over
11768The @key{LFD} (@code{calc-over}) command (on a key marked Line-Feed if you
11769have it, else on @kbd{C-j}) is like @code{calc-enter}
11770except that the sign of the numeric prefix argument is interpreted
11771oppositely. Also, with no prefix argument the default argument is 2.
11772Thus with @samp{10 20 30} on the stack, @key{LFD} and @kbd{C-u 2 @key{LFD}}
11773are both equivalent to @kbd{C-u - 2 @key{RET}}, producing
11774@samp{10 20 30 20}.
11775
11776@kindex @key{DEL}
11777@kindex C-d
11778@pindex calc-pop
11779@cindex Removing stack entries
11780@cindex Deleting stack entries
11781To remove the top element from the stack, press @key{DEL} (@code{calc-pop}).
11782The @kbd{C-d} key is a synonym for @key{DEL}.
11783(If the top element is an incomplete object with at least one element, the
11784last element is removed from it.) Given a positive numeric prefix argument,
11785several elements are removed. Given a negative argument, the specified
11786element of the stack is deleted. Given an argument of zero, the entire
11787stack is emptied.
11788For example, with @samp{10 20 30} on the stack,
11789@key{DEL} leaves @samp{10 20},
11790@kbd{C-u 2 @key{DEL}} leaves @samp{10},
11791@kbd{C-u - 2 @key{DEL}} leaves @samp{10 30}, and
11792@kbd{C-u 0 @key{DEL}} leaves an empty stack.
11793
11794@kindex M-@key{DEL}
11795@pindex calc-pop-above
11796The @kbd{M-@key{DEL}} (@code{calc-pop-above}) command is to @key{DEL} what
11797@key{LFD} is to @key{RET}: It interprets the sign of the numeric
11798prefix argument in the opposite way, and the default argument is 2.
11799Thus @kbd{M-@key{DEL}} by itself removes the second-from-top stack element,
11800leaving the first, third, fourth, and so on; @kbd{M-3 M-@key{DEL}} deletes
11801the third stack element.
11802
11803@kindex @key{TAB}
11804@pindex calc-roll-down
11805To exchange the top two elements of the stack, press @key{TAB}
11806(@code{calc-roll-down}). Given a positive numeric prefix argument, the
11807specified number of elements at the top of the stack are rotated downward.
11808Given a negative argument, the entire stack is rotated downward the specified
11809number of times. Given an argument of zero, the entire stack is reversed
11810top-for-bottom.
11811For example, with @samp{10 20 30 40 50} on the stack,
11812@key{TAB} creates @samp{10 20 30 50 40},
11813@kbd{C-u 3 @key{TAB}} creates @samp{10 20 50 30 40},
11814@kbd{C-u - 2 @key{TAB}} creates @samp{40 50 10 20 30}, and
11815@kbd{C-u 0 @key{TAB}} creates @samp{50 40 30 20 10}.
11816
11817@kindex M-@key{TAB}
11818@pindex calc-roll-up
11819The command @kbd{M-@key{TAB}} (@code{calc-roll-up}) is analogous to @key{TAB}
11820except that it rotates upward instead of downward. Also, the default
11821with no prefix argument is to rotate the top 3 elements.
11822For example, with @samp{10 20 30 40 50} on the stack,
11823@kbd{M-@key{TAB}} creates @samp{10 20 40 50 30},
11824@kbd{C-u 4 M-@key{TAB}} creates @samp{10 30 40 50 20},
11825@kbd{C-u - 2 M-@key{TAB}} creates @samp{30 40 50 10 20}, and
11826@kbd{C-u 0 M-@key{TAB}} creates @samp{50 40 30 20 10}.
11827
11828A good way to view the operation of @key{TAB} and @kbd{M-@key{TAB}} is in
11829terms of moving a particular element to a new position in the stack.
11830With a positive argument @var{n}, @key{TAB} moves the top stack
11831element down to level @var{n}, making room for it by pulling all the
11832intervening stack elements toward the top. @kbd{M-@key{TAB}} moves the
11833element at level @var{n} up to the top. (Compare with @key{LFD},
11834which copies instead of moving the element in level @var{n}.)
11835
11836With a negative argument @mathit{-@var{n}}, @key{TAB} rotates the stack
11837to move the object in level @var{n} to the deepest place in the
11838stack, and the object in level @mathit{@var{n}+1} to the top. @kbd{M-@key{TAB}}
5a9e3ab7 11839rotates the deepest stack element to be in level @var{n}, also
4009494e
GM
11840putting the top stack element in level @mathit{@var{n}+1}.
11841
11842@xref{Selecting Subformulas}, for a way to apply these commands to
11843any portion of a vector or formula on the stack.
11844
5a9e3ab7
JB
11845@kindex C-xC-t
11846@pindex calc-transpose-lines
11847@cindex Moving stack entries
11848The command @kbd{C-x C-t} (@code{calc-transpose-lines}) will transpose
11849the stack object determined by the point with the stack object at the
11850next higher level. For example, with @samp{10 20 30 40 50} on the
11851stack and the point on the line containing @samp{30}, @kbd{C-x C-t}
11852creates @samp{10 20 40 30 50}. More generally, @kbd{C-x C-t} acts on
11853the stack objects determined by the current point (and mark) similar
40ba43b4 11854to how the text-mode command @code{transpose-lines} acts on
5a9e3ab7
JB
11855lines. With argument @var{n}, @kbd{C-x C-t} will move the stack object
11856at the level above the current point and move it past N other objects;
11857for example, with @samp{10 20 30 40 50} on the stack and the point on
40ba43b4 11858the line containing @samp{30}, @kbd{C-u 2 C-x C-t} creates
5a9e3ab7 11859@samp{10 40 20 30 50}. With an argument of 0, @kbd{C-x C-t} will switch
40ba43b4 11860the stack objects at the levels determined by the point and the mark.
5a9e3ab7 11861
4009494e
GM
11862@node Editing Stack Entries, Trail Commands, Stack Manipulation, Stack and Trail
11863@section Editing Stack Entries
11864
11865@noindent
11866@kindex `
11867@pindex calc-edit
11868@pindex calc-edit-finish
11869@cindex Editing the stack with Emacs
8dc6104d
JB
11870The @kbd{`} (@code{calc-edit}) command creates a temporary buffer
11871(@samp{*Calc Edit*}) for editing the top-of-stack value using regular
11872Emacs commands. Note that @kbd{`} is a backquote, not a quote. With a
11873numeric prefix argument, it edits the specified number of stack entries
11874at once. (An argument of zero edits the entire stack; a negative
11875argument edits one specific stack entry.)
4009494e
GM
11876
11877When you are done editing, press @kbd{C-c C-c} to finish and return
11878to Calc. The @key{RET} and @key{LFD} keys also work to finish most
11879sorts of editing, though in some cases Calc leaves @key{RET} with its
11880usual meaning (``insert a newline'') if it's a situation where you
11881might want to insert new lines into the editing buffer.
11882
11883When you finish editing, the Calculator parses the lines of text in
11884the @samp{*Calc Edit*} buffer as numbers or formulas, replaces the
11885original stack elements in the original buffer with these new values,
11886then kills the @samp{*Calc Edit*} buffer. The original Calculator buffer
11887continues to exist during editing, but for best results you should be
11888careful not to change it until you have finished the edit. You can
11889also cancel the edit by killing the buffer with @kbd{C-x k}.
11890
11891The formula is normally reevaluated as it is put onto the stack.
11892For example, editing @samp{a + 2} to @samp{3 + 2} and pressing
11893@kbd{C-c C-c} will push 5 on the stack. If you use @key{LFD} to
11894finish, Calc will put the result on the stack without evaluating it.
11895
11896If you give a prefix argument to @kbd{C-c C-c},
11897Calc will not kill the @samp{*Calc Edit*} buffer. You can switch
11898back to that buffer and continue editing if you wish. However, you
11899should understand that if you initiated the edit with @kbd{`}, the
11900@kbd{C-c C-c} operation will be programmed to replace the top of the
11901stack with the new edited value, and it will do this even if you have
11902rearranged the stack in the meanwhile. This is not so much of a problem
11903with other editing commands, though, such as @kbd{s e}
11904(@code{calc-edit-variable}; @pxref{Operations on Variables}).
11905
11906If the @code{calc-edit} command involves more than one stack entry,
11907each line of the @samp{*Calc Edit*} buffer is interpreted as a
11908separate formula. Otherwise, the entire buffer is interpreted as
11909one formula, with line breaks ignored. (You can use @kbd{C-o} or
11910@kbd{C-q C-j} to insert a newline in the buffer without pressing @key{RET}.)
11911
11912The @kbd{`} key also works during numeric or algebraic entry. The
11913text entered so far is moved to the @code{*Calc Edit*} buffer for
11914more extensive editing than is convenient in the minibuffer.
11915
11916@node Trail Commands, Keep Arguments, Editing Stack Entries, Stack and Trail
11917@section Trail Commands
11918
11919@noindent
11920@cindex Trail buffer
11921The commands for manipulating the Calc Trail buffer are two-key sequences
11922beginning with the @kbd{t} prefix.
11923
11924@kindex t d
11925@pindex calc-trail-display
11926The @kbd{t d} (@code{calc-trail-display}) command turns display of the
11927trail on and off. Normally the trail display is toggled on if it was off,
11928off if it was on. With a numeric prefix of zero, this command always
11929turns the trail off; with a prefix of one, it always turns the trail on.
11930The other trail-manipulation commands described here automatically turn
11931the trail on. Note that when the trail is off values are still recorded
11932there; they are simply not displayed. To set Emacs to turn the trail
11933off by default, type @kbd{t d} and then save the mode settings with
11934@kbd{m m} (@code{calc-save-modes}).
11935
11936@kindex t i
11937@pindex calc-trail-in
11938@kindex t o
11939@pindex calc-trail-out
11940The @kbd{t i} (@code{calc-trail-in}) and @kbd{t o}
11941(@code{calc-trail-out}) commands switch the cursor into and out of the
11942Calc Trail window. In practice they are rarely used, since the commands
11943shown below are a more convenient way to move around in the
11944trail, and they work ``by remote control'' when the cursor is still
11945in the Calculator window.
11946
11947@cindex Trail pointer
11948There is a @dfn{trail pointer} which selects some entry of the trail at
11949any given time. The trail pointer looks like a @samp{>} symbol right
11950before the selected number. The following commands operate on the
11951trail pointer in various ways.
11952
11953@kindex t y
11954@pindex calc-trail-yank
11955@cindex Retrieving previous results
11956The @kbd{t y} (@code{calc-trail-yank}) command reads the selected value in
11957the trail and pushes it onto the Calculator stack. It allows you to
11958re-use any previously computed value without retyping. With a numeric
11959prefix argument @var{n}, it yanks the value @var{n} lines above the current
11960trail pointer.
11961
11962@kindex t <
11963@pindex calc-trail-scroll-left
11964@kindex t >
11965@pindex calc-trail-scroll-right
11966The @kbd{t <} (@code{calc-trail-scroll-left}) and @kbd{t >}
11967(@code{calc-trail-scroll-right}) commands horizontally scroll the trail
11968window left or right by one half of its width.
11969
11970@kindex t n
11971@pindex calc-trail-next
11972@kindex t p
11973@pindex calc-trail-previous
11974@kindex t f
11975@pindex calc-trail-forward
11976@kindex t b
11977@pindex calc-trail-backward
11978The @kbd{t n} (@code{calc-trail-next}) and @kbd{t p}
11979(@code{calc-trail-previous)} commands move the trail pointer down or up
11980one line. The @kbd{t f} (@code{calc-trail-forward}) and @kbd{t b}
11981(@code{calc-trail-backward}) commands move the trail pointer down or up
11982one screenful at a time. All of these commands accept numeric prefix
11983arguments to move several lines or screenfuls at a time.
11984
11985@kindex t [
11986@pindex calc-trail-first
11987@kindex t ]
11988@pindex calc-trail-last
11989@kindex t h
11990@pindex calc-trail-here
11991The @kbd{t [} (@code{calc-trail-first}) and @kbd{t ]}
11992(@code{calc-trail-last}) commands move the trail pointer to the first or
11993last line of the trail. The @kbd{t h} (@code{calc-trail-here}) command
11994moves the trail pointer to the cursor position; unlike the other trail
11995commands, @kbd{t h} works only when Calc Trail is the selected window.
11996
11997@kindex t s
11998@pindex calc-trail-isearch-forward
11999@kindex t r
12000@pindex calc-trail-isearch-backward
12001@ifnottex
12002The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12003(@code{calc-trail-isearch-backward}) commands perform an incremental
12004search forward or backward through the trail. You can press @key{RET}
12005to terminate the search; the trail pointer moves to the current line.
12006If you cancel the search with @kbd{C-g}, the trail pointer stays where
12007it was when the search began.
12008@end ifnottex
12009@tex
12010The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12011(@code{calc-trail-isearch-backward}) com\-mands perform an incremental
12012search forward or backward through the trail. You can press @key{RET}
12013to terminate the search; the trail pointer moves to the current line.
12014If you cancel the search with @kbd{C-g}, the trail pointer stays where
12015it was when the search began.
12016@end tex
12017
12018@kindex t m
12019@pindex calc-trail-marker
12020The @kbd{t m} (@code{calc-trail-marker}) command allows you to enter a
12021line of text of your own choosing into the trail. The text is inserted
12022after the line containing the trail pointer; this usually means it is
12023added to the end of the trail. Trail markers are useful mainly as the
12024targets for later incremental searches in the trail.
12025
12026@kindex t k
12027@pindex calc-trail-kill
12028The @kbd{t k} (@code{calc-trail-kill}) command removes the selected line
12029from the trail. The line is saved in the Emacs kill ring suitable for
12030yanking into another buffer, but it is not easy to yank the text back
12031into the trail buffer. With a numeric prefix argument, this command
12032kills the @var{n} lines below or above the selected one.
12033
12034The @kbd{t .} (@code{calc-full-trail-vectors}) command is described
12035elsewhere; @pxref{Vector and Matrix Formats}.
12036
12037@node Keep Arguments, , Trail Commands, Stack and Trail
12038@section Keep Arguments
12039
12040@noindent
12041@kindex K
12042@pindex calc-keep-args
12043The @kbd{K} (@code{calc-keep-args}) command acts like a prefix for
12044the following command. It prevents that command from removing its
12045arguments from the stack. For example, after @kbd{2 @key{RET} 3 +},
12046the stack contains the sole number 5, but after @kbd{2 @key{RET} 3 K +},
12047the stack contains the arguments and the result: @samp{2 3 5}.
12048
12049With the exception of keyboard macros, this works for all commands that
12050take arguments off the stack. (To avoid potentially unpleasant behavior,
12051a @kbd{K} prefix before a keyboard macro will be ignored. A @kbd{K}
40ba43b4 12052prefix called @emph{within} the keyboard macro will still take effect.)
4009494e
GM
12053As another example, @kbd{K a s} simplifies a formula, pushing the
12054simplified version of the formula onto the stack after the original
12055formula (rather than replacing the original formula). Note that you
12056could get the same effect by typing @kbd{@key{RET} a s}, copying the
12057formula and then simplifying the copy. One difference is that for a very
12058large formula the time taken to format the intermediate copy in
12059@kbd{@key{RET} a s} could be noticeable; @kbd{K a s} would avoid this
40ba43b4 12060extra work.
4009494e
GM
12061
12062Even stack manipulation commands are affected. @key{TAB} works by
12063popping two values and pushing them back in the opposite order,
12064so @kbd{2 @key{RET} 3 K @key{TAB}} produces @samp{2 3 3 2}.
12065
12066A few Calc commands provide other ways of doing the same thing.
12067For example, @kbd{' sin($)} replaces the number on the stack with
12068its sine using algebraic entry; to push the sine and keep the
12069original argument you could use either @kbd{' sin($1)} or
12070@kbd{K ' sin($)}. @xref{Algebraic Entry}. Also, the @kbd{s s}
12071command is effectively the same as @kbd{K s t}. @xref{Storing Variables}.
12072
12073If you execute a command and then decide you really wanted to keep
12074the argument, you can press @kbd{M-@key{RET}} (@code{calc-last-args}).
12075This command pushes the last arguments that were popped by any command
12076onto the stack. Note that the order of things on the stack will be
12077different than with @kbd{K}: @kbd{2 @key{RET} 3 + M-@key{RET}} leaves
12078@samp{5 2 3} on the stack instead of @samp{2 3 5}. @xref{Undo}.
12079
12080@node Mode Settings, Arithmetic, Stack and Trail, Top
12081@chapter Mode Settings
12082
12083@noindent
12084This chapter describes commands that set modes in the Calculator.
12085They do not affect the contents of the stack, although they may change
12086the @emph{appearance} or @emph{interpretation} of the stack's contents.
12087
12088@menu
12089* General Mode Commands::
12090* Precision::
12091* Inverse and Hyperbolic::
12092* Calculation Modes::
12093* Simplification Modes::
12094* Declarations::
12095* Display Modes::
12096* Language Modes::
12097* Modes Variable::
12098* Calc Mode Line::
12099@end menu
12100
12101@node General Mode Commands, Precision, Mode Settings, Mode Settings
12102@section General Mode Commands
12103
12104@noindent
12105@kindex m m
12106@pindex calc-save-modes
12107@cindex Continuous memory
12108@cindex Saving mode settings
12109@cindex Permanent mode settings
12110@cindex Calc init file, mode settings
4970fbfe 12111You can save all of the current mode settings in your Calc init file
4009494e 12112(the file given by the variable @code{calc-settings-file}, typically
4970fbfe
CY
12113@file{~/.emacs.d/calc.el}) with the @kbd{m m} (@code{calc-save-modes})
12114command. This will cause Emacs to reestablish these modes each time
12115it starts up. The modes saved in the file include everything
12116controlled by the @kbd{m} and @kbd{d} prefix keys, the current
12117precision and binary word size, whether or not the trail is displayed,
12118the current height of the Calc window, and more. The current
12119interface (used when you type @kbd{C-x * *}) is also saved. If there
12120were already saved mode settings in the file, they are replaced.
12121Otherwise, the new mode information is appended to the end of the
12122file.
4009494e
GM
12123
12124@kindex m R
12125@pindex calc-mode-record-mode
12126The @kbd{m R} (@code{calc-mode-record-mode}) command tells Calc to
12127record all the mode settings (as if by pressing @kbd{m m}) every
12128time a mode setting changes. If the modes are saved this way, then this
12129``automatic mode recording'' mode is also saved.
12130Type @kbd{m R} again to disable this method of recording the mode
12131settings. To turn it off permanently, the @kbd{m m} command will also be
12132necessary. (If Embedded mode is enabled, other options for recording
12133the modes are available; @pxref{Mode Settings in Embedded Mode}.)
12134
12135@kindex m F
12136@pindex calc-settings-file-name
12137The @kbd{m F} (@code{calc-settings-file-name}) command allows you to
12138choose a different file than the current value of @code{calc-settings-file}
12139for @kbd{m m}, @kbd{Z P}, and similar commands to save permanent information.
12140You are prompted for a file name. All Calc modes are then reset to
12141their default values, then settings from the file you named are loaded
12142if this file exists, and this file becomes the one that Calc will
12143use in the future for commands like @kbd{m m}. The default settings
dcf7843e 12144file name is @file{~/.emacs.d/calc.el}. You can see the current file name by
4009494e
GM
12145giving a blank response to the @kbd{m F} prompt. See also the
12146discussion of the @code{calc-settings-file} variable; @pxref{Customizing Calc}.
12147
12148If the file name you give is your user init file (typically
12149@file{~/.emacs}), @kbd{m F} will not automatically load the new file. This
12150is because your user init file may contain other things you don't want
40ba43b4 12151to reread. You can give
4009494e
GM
12152a numeric prefix argument of 1 to @kbd{m F} to force it to read the
12153file no matter what. Conversely, an argument of @mathit{-1} tells
12154@kbd{m F} @emph{not} to read the new file. An argument of 2 or @mathit{-2}
12155tells @kbd{m F} not to reset the modes to their defaults beforehand,
12156which is useful if you intend your new file to have a variant of the
12157modes present in the file you were using before.
12158
12159@kindex m x
12160@pindex calc-always-load-extensions
12161The @kbd{m x} (@code{calc-always-load-extensions}) command enables a mode
12162in which the first use of Calc loads the entire program, including all
12163extensions modules. Otherwise, the extensions modules will not be loaded
12164until the various advanced Calc features are used. Since this mode only
12165has effect when Calc is first loaded, @kbd{m x} is usually followed by
12166@kbd{m m} to make the mode-setting permanent. To load all of Calc just
12167once, rather than always in the future, you can press @kbd{C-x * L}.
12168
12169@kindex m S
12170@pindex calc-shift-prefix
12171The @kbd{m S} (@code{calc-shift-prefix}) command enables a mode in which
12172all of Calc's letter prefix keys may be typed shifted as well as unshifted.
12173If you are typing, say, @kbd{a S} (@code{calc-solve-for}) quite often
12174you might find it easier to turn this mode on so that you can type
12175@kbd{A S} instead. When this mode is enabled, the commands that used to
12176be on those single shifted letters (e.g., @kbd{A} (@code{calc-abs})) can
12177now be invoked by pressing the shifted letter twice: @kbd{A A}. Note
12178that the @kbd{v} prefix key always works both shifted and unshifted, and
12179the @kbd{z} and @kbd{Z} prefix keys are always distinct. Also, the @kbd{h}
12180prefix is not affected by this mode. Press @kbd{m S} again to disable
12181shifted-prefix mode.
12182
12183@node Precision, Inverse and Hyperbolic, General Mode Commands, Mode Settings
12184@section Precision
12185
12186@noindent
12187@kindex p
12188@pindex calc-precision
12189@cindex Precision of calculations
12190The @kbd{p} (@code{calc-precision}) command controls the precision to
12191which floating-point calculations are carried. The precision must be
12192at least 3 digits and may be arbitrarily high, within the limits of
12193memory and time. This affects only floats: Integer and rational
12194calculations are always carried out with as many digits as necessary.
12195
12196The @kbd{p} key prompts for the current precision. If you wish you
12197can instead give the precision as a numeric prefix argument.
12198
12199Many internal calculations are carried to one or two digits higher
12200precision than normal. Results are rounded down afterward to the
12201current precision. Unless a special display mode has been selected,
12202floats are always displayed with their full stored precision, i.e.,
12203what you see is what you get. Reducing the current precision does not
12204round values already on the stack, but those values will be rounded
12205down before being used in any calculation. The @kbd{c 0} through
12206@kbd{c 9} commands (@pxref{Conversions}) can be used to round an
12207existing value to a new precision.
12208
12209@cindex Accuracy of calculations
12210It is important to distinguish the concepts of @dfn{precision} and
12211@dfn{accuracy}. In the normal usage of these words, the number
12212123.4567 has a precision of 7 digits but an accuracy of 4 digits.
12213The precision is the total number of digits not counting leading
12214or trailing zeros (regardless of the position of the decimal point).
12215The accuracy is simply the number of digits after the decimal point
12216(again not counting trailing zeros). In Calc you control the precision,
12217not the accuracy of computations. If you were to set the accuracy
12218instead, then calculations like @samp{exp(100)} would generate many
12219more digits than you would typically need, while @samp{exp(-100)} would
12220probably round to zero! In Calc, both these computations give you
12221exactly 12 (or the requested number of) significant digits.
12222
12223The only Calc features that deal with accuracy instead of precision
12224are fixed-point display mode for floats (@kbd{d f}; @pxref{Float Formats}),
12225and the rounding functions like @code{floor} and @code{round}
12226(@pxref{Integer Truncation}). Also, @kbd{c 0} through @kbd{c 9}
12227deal with both precision and accuracy depending on the magnitudes
12228of the numbers involved.
12229
12230If you need to work with a particular fixed accuracy (say, dollars and
12231cents with two digits after the decimal point), one solution is to work
12232with integers and an ``implied'' decimal point. For example, $8.99
12233divided by 6 would be entered @kbd{899 @key{RET} 6 /}, yielding 149.833
12234(actually $1.49833 with our implied decimal point); pressing @kbd{R}
12235would round this to 150 cents, i.e., $1.50.
12236
12237@xref{Floats}, for still more on floating-point precision and related
12238issues.
12239
12240@node Inverse and Hyperbolic, Calculation Modes, Precision, Mode Settings
12241@section Inverse and Hyperbolic Flags
12242
12243@noindent
12244@kindex I
12245@pindex calc-inverse
12246There is no single-key equivalent to the @code{calc-arcsin} function.
12247Instead, you must first press @kbd{I} (@code{calc-inverse}) to set
12248the @dfn{Inverse Flag}, then press @kbd{S} (@code{calc-sin}).
12249The @kbd{I} key actually toggles the Inverse Flag. When this flag
12250is set, the word @samp{Inv} appears in the mode line.
12251
12252@kindex H
12253@pindex calc-hyperbolic
12254Likewise, the @kbd{H} key (@code{calc-hyperbolic}) sets or clears the
12255Hyperbolic Flag, which transforms @code{calc-sin} into @code{calc-sinh}.
12256If both of these flags are set at once, the effect will be
12257@code{calc-arcsinh}. (The Hyperbolic flag is also used by some
12258non-trigonometric commands; for example @kbd{H L} computes a base-10,
12259instead of base-@mathit{e}, logarithm.)
12260
12261Command names like @code{calc-arcsin} are provided for completeness, and
12262may be executed with @kbd{x} or @kbd{M-x}. Their effect is simply to
12263toggle the Inverse and/or Hyperbolic flags and then execute the
12264corresponding base command (@code{calc-sin} in this case).
12265
f8b91752
JB
12266@kindex O
12267@pindex calc-option
12268The @kbd{O} key (@code{calc-option}) sets another flag, the
12269@dfn{Option Flag}, which also can alter the subsequent Calc command in
40ba43b4 12270various ways.
f8b91752
JB
12271
12272The Inverse, Hyperbolic and Option flags apply only to the next
12273Calculator command, after which they are automatically cleared. (They
12274are also cleared if the next keystroke is not a Calc command.) Digits
12275you type after @kbd{I}, @kbd{H} or @kbd{O} (or @kbd{K}) are treated as
12276prefix arguments for the next command, not as numeric entries. The
12277same is true of @kbd{C-u}, but not of the minus sign (@kbd{K -} means
12278to subtract and keep arguments).
12279
12280Another Calc prefix flag, @kbd{K} (keep-arguments), is discussed
4009494e
GM
12281elsewhere. @xref{Keep Arguments}.
12282
12283@node Calculation Modes, Simplification Modes, Inverse and Hyperbolic, Mode Settings
12284@section Calculation Modes
12285
12286@noindent
12287The commands in this section are two-key sequences beginning with
12288the @kbd{m} prefix. (That's the letter @kbd{m}, not the @key{META} key.)
12289The @samp{m a} (@code{calc-algebraic-mode}) command is described elsewhere
12290(@pxref{Algebraic Entry}).
12291
12292@menu
12293* Angular Modes::
12294* Polar Mode::
12295* Fraction Mode::
12296* Infinite Mode::
12297* Symbolic Mode::
12298* Matrix Mode::
12299* Automatic Recomputation::
12300* Working Message::
12301@end menu
12302
12303@node Angular Modes, Polar Mode, Calculation Modes, Calculation Modes
12304@subsection Angular Modes
12305
12306@noindent
12307@cindex Angular mode
12308The Calculator supports three notations for angles: radians, degrees,
12309and degrees-minutes-seconds. When a number is presented to a function
12310like @code{sin} that requires an angle, the current angular mode is
12311used to interpret the number as either radians or degrees. If an HMS
12312form is presented to @code{sin}, it is always interpreted as
12313degrees-minutes-seconds.
12314
12315Functions that compute angles produce a number in radians, a number in
12316degrees, or an HMS form depending on the current angular mode. If the
12317result is a complex number and the current mode is HMS, the number is
12318instead expressed in degrees. (Complex-number calculations would
12319normally be done in Radians mode, though. Complex numbers are converted
12320to degrees by calculating the complex result in radians and then
12321multiplying by 180 over @cpi{}.)
12322
12323@kindex m r
12324@pindex calc-radians-mode
12325@kindex m d
12326@pindex calc-degrees-mode
12327@kindex m h
12328@pindex calc-hms-mode
12329The @kbd{m r} (@code{calc-radians-mode}), @kbd{m d} (@code{calc-degrees-mode}),
12330and @kbd{m h} (@code{calc-hms-mode}) commands control the angular mode.
12331The current angular mode is displayed on the Emacs mode line.
12332The default angular mode is Degrees.
12333
12334@node Polar Mode, Fraction Mode, Angular Modes, Calculation Modes
12335@subsection Polar Mode
12336
12337@noindent
12338@cindex Polar mode
12339The Calculator normally ``prefers'' rectangular complex numbers in the
12340sense that rectangular form is used when the proper form can not be
12341decided from the input. This might happen by multiplying a rectangular
12342number by a polar one, by taking the square root of a negative real
12343number, or by entering @kbd{( 2 @key{SPC} 3 )}.
12344
12345@kindex m p
12346@pindex calc-polar-mode
12347The @kbd{m p} (@code{calc-polar-mode}) command toggles complex-number
12348preference between rectangular and polar forms. In Polar mode, all
12349of the above example situations would produce polar complex numbers.
12350
12351@node Fraction Mode, Infinite Mode, Polar Mode, Calculation Modes
12352@subsection Fraction Mode
12353
12354@noindent
12355@cindex Fraction mode
12356@cindex Division of integers
12357Division of two integers normally yields a floating-point number if the
12358result cannot be expressed as an integer. In some cases you would
12359rather get an exact fractional answer. One way to accomplish this is
12360to use the @kbd{:} (@code{calc-fdiv}) [@code{fdiv}] command, which
12361divides the two integers on the top of the stack to produce a fraction:
40ba43b4 12362@kbd{6 @key{RET} 4 :} produces @expr{3:2} even though
4009494e
GM
12363@kbd{6 @key{RET} 4 /} produces @expr{1.5}.
12364
12365@kindex m f
12366@pindex calc-frac-mode
12367To set the Calculator to produce fractional results for normal integer
12368divisions, use the @kbd{m f} (@code{calc-frac-mode}) command.
12369For example, @expr{8/4} produces @expr{2} in either mode,
12370but @expr{6/4} produces @expr{3:2} in Fraction mode, @expr{1.5} in
12371Float mode.
12372
12373At any time you can use @kbd{c f} (@code{calc-float}) to convert a
12374fraction to a float, or @kbd{c F} (@code{calc-fraction}) to convert a
12375float to a fraction. @xref{Conversions}.
12376
12377@node Infinite Mode, Symbolic Mode, Fraction Mode, Calculation Modes
12378@subsection Infinite Mode
12379
12380@noindent
12381@cindex Infinite mode
12382The Calculator normally treats results like @expr{1 / 0} as errors;
12383formulas like this are left in unsimplified form. But Calc can be
12384put into a mode where such calculations instead produce ``infinite''
12385results.
12386
12387@kindex m i
12388@pindex calc-infinite-mode
12389The @kbd{m i} (@code{calc-infinite-mode}) command turns this mode
12390on and off. When the mode is off, infinities do not arise except
12391in calculations that already had infinities as inputs. (One exception
12392is that infinite open intervals like @samp{[0 .. inf)} can be
12393generated; however, intervals closed at infinity (@samp{[0 .. inf]})
12394will not be generated when Infinite mode is off.)
12395
12396With Infinite mode turned on, @samp{1 / 0} will generate @code{uinf},
12397an undirected infinity. @xref{Infinities}, for a discussion of the
12398difference between @code{inf} and @code{uinf}. Also, @expr{0 / 0}
12399evaluates to @code{nan}, the ``indeterminate'' symbol. Various other
12400functions can also return infinities in this mode; for example,
12401@samp{ln(0) = -inf}, and @samp{gamma(-7) = uinf}. Once again,
12402note that @samp{exp(inf) = inf} regardless of Infinite mode because
12403this calculation has infinity as an input.
12404
12405@cindex Positive Infinite mode
12406The @kbd{m i} command with a numeric prefix argument of zero,
12407i.e., @kbd{C-u 0 m i}, turns on a Positive Infinite mode in
12408which zero is treated as positive instead of being directionless.
12409Thus, @samp{1 / 0 = inf} and @samp{-1 / 0 = -inf} in this mode.
12410Note that zero never actually has a sign in Calc; there are no
12411separate representations for @mathit{+0} and @mathit{-0}. Positive
12412Infinite mode merely changes the interpretation given to the
12413single symbol, @samp{0}. One consequence of this is that, while
12414you might expect @samp{1 / -0 = -inf}, actually @samp{1 / -0}
12415is equivalent to @samp{1 / 0}, which is equal to positive @code{inf}.
12416
12417@node Symbolic Mode, Matrix Mode, Infinite Mode, Calculation Modes
12418@subsection Symbolic Mode
12419
12420@noindent
12421@cindex Symbolic mode
12422@cindex Inexact results
12423Calculations are normally performed numerically wherever possible.
12424For example, the @code{calc-sqrt} command, or @code{sqrt} function in an
12425algebraic expression, produces a numeric answer if the argument is a
12426number or a symbolic expression if the argument is an expression:
12427@kbd{2 Q} pushes 1.4142 but @kbd{@key{'} x+1 @key{RET} Q} pushes @samp{sqrt(x+1)}.
12428
12429@kindex m s
12430@pindex calc-symbolic-mode
12431In @dfn{Symbolic mode}, controlled by the @kbd{m s} (@code{calc-symbolic-mode})
12432command, functions which would produce inexact, irrational results are
12433left in symbolic form. Thus @kbd{16 Q} pushes 4, but @kbd{2 Q} pushes
12434@samp{sqrt(2)}.
12435
12436@kindex N
12437@pindex calc-eval-num
12438The shift-@kbd{N} (@code{calc-eval-num}) command evaluates numerically
12439the expression at the top of the stack, by temporarily disabling
12440@code{calc-symbolic-mode} and executing @kbd{=} (@code{calc-evaluate}).
12441Given a numeric prefix argument, it also
12442sets the floating-point precision to the specified value for the duration
12443of the command.
12444
12445To evaluate a formula numerically without expanding the variables it
12446contains, you can use the key sequence @kbd{m s a v m s} (this uses
12447@code{calc-alg-evaluate}, which resimplifies but doesn't evaluate
12448variables.)
12449
12450@node Matrix Mode, Automatic Recomputation, Symbolic Mode, Calculation Modes
12451@subsection Matrix and Scalar Modes
12452
12453@noindent
12454@cindex Matrix mode
12455@cindex Scalar mode
12456Calc sometimes makes assumptions during algebraic manipulation that
12457are awkward or incorrect when vectors and matrices are involved.
12458Calc has two modes, @dfn{Matrix mode} and @dfn{Scalar mode}, which
12459modify its behavior around vectors in useful ways.
12460
12461@kindex m v
12462@pindex calc-matrix-mode
12463Press @kbd{m v} (@code{calc-matrix-mode}) once to enter Matrix mode.
12464In this mode, all objects are assumed to be matrices unless provably
12465otherwise. One major effect is that Calc will no longer consider
12466multiplication to be commutative. (Recall that in matrix arithmetic,
12467@samp{A*B} is not the same as @samp{B*A}.) This assumption affects
12468rewrite rules and algebraic simplification. Another effect of this
12469mode is that calculations that would normally produce constants like
124700 and 1 (e.g., @expr{a - a} and @expr{a / a}, respectively) will now
12471produce function calls that represent ``generic'' zero or identity
12472matrices: @samp{idn(0)}, @samp{idn(1)}. The @code{idn} function
12473@samp{idn(@var{a},@var{n})} returns @var{a} times an @var{n}x@var{n}
12474identity matrix; if @var{n} is omitted, it doesn't know what
12475dimension to use and so the @code{idn} call remains in symbolic
12476form. However, if this generic identity matrix is later combined
12477with a matrix whose size is known, it will be converted into
12478a true identity matrix of the appropriate size. On the other hand,
12479if it is combined with a scalar (as in @samp{idn(1) + 2}), Calc
12480will assume it really was a scalar after all and produce, e.g., 3.
12481
12482Press @kbd{m v} a second time to get Scalar mode. Here, objects are
12483assumed @emph{not} to be vectors or matrices unless provably so.
12484For example, normally adding a variable to a vector, as in
12485@samp{[x, y, z] + a}, will leave the sum in symbolic form because
12486as far as Calc knows, @samp{a} could represent either a number or
12487another 3-vector. In Scalar mode, @samp{a} is assumed to be a
12488non-vector, and the addition is evaluated to @samp{[x+a, y+a, z+a]}.
12489
12490Press @kbd{m v} a third time to return to the normal mode of operation.
12491
12492If you press @kbd{m v} with a numeric prefix argument @var{n}, you
12493get a special ``dimensioned'' Matrix mode in which matrices of
12494unknown size are assumed to be @var{n}x@var{n} square matrices.
12495Then, the function call @samp{idn(1)} will expand into an actual
12496matrix rather than representing a ``generic'' matrix. Simply typing
12497@kbd{C-u m v} will get you a square Matrix mode, in which matrices of
12498unknown size are assumed to be square matrices of unspecified size.
12499
12500@cindex Declaring scalar variables
12501Of course these modes are approximations to the true state of
12502affairs, which is probably that some quantities will be matrices
12503and others will be scalars. One solution is to ``declare''
12504certain variables or functions to be scalar-valued.
12505@xref{Declarations}, to see how to make declarations in Calc.
12506
12507There is nothing stopping you from declaring a variable to be
12508scalar and then storing a matrix in it; however, if you do, the
12509results you get from Calc may not be valid. Suppose you let Calc
12510get the result @samp{[x+a, y+a, z+a]} shown above, and then stored
12511@samp{[1, 2, 3]} in @samp{a}. The result would not be the same as
12512for @samp{[x, y, z] + [1, 2, 3]}, but that's because you have broken
12513your earlier promise to Calc that @samp{a} would be scalar.
12514
12515Another way to mix scalars and matrices is to use selections
12516(@pxref{Selecting Subformulas}). Use Matrix mode when operating on
12517your formula normally; then, to apply Scalar mode to a certain part
12518of the formula without affecting the rest just select that part,
12519change into Scalar mode and press @kbd{=} to resimplify the part
12520under this mode, then change back to Matrix mode before deselecting.
12521
12522@node Automatic Recomputation, Working Message, Matrix Mode, Calculation Modes
12523@subsection Automatic Recomputation
12524
12525@noindent
12526The @dfn{evaluates-to} operator, @samp{=>}, has the special
12527property that any @samp{=>} formulas on the stack are recomputed
12528whenever variable values or mode settings that might affect them
12529are changed. @xref{Evaluates-To Operator}.
12530
12531@kindex m C
12532@pindex calc-auto-recompute
12533The @kbd{m C} (@code{calc-auto-recompute}) command turns this
12534automatic recomputation on and off. If you turn it off, Calc will
12535not update @samp{=>} operators on the stack (nor those in the
12536attached Embedded mode buffer, if there is one). They will not
12537be updated unless you explicitly do so by pressing @kbd{=} or until
12538you press @kbd{m C} to turn recomputation back on. (While automatic
12539recomputation is off, you can think of @kbd{m C m C} as a command
12540to update all @samp{=>} operators while leaving recomputation off.)
12541
12542To update @samp{=>} operators in an Embedded buffer while
12543automatic recomputation is off, use @w{@kbd{C-x * u}}.
12544@xref{Embedded Mode}.
12545
12546@node Working Message, , Automatic Recomputation, Calculation Modes
12547@subsection Working Messages
12548
12549@noindent
12550@cindex Performance
12551@cindex Working messages
12552Since the Calculator is written entirely in Emacs Lisp, which is not
12553designed for heavy numerical work, many operations are quite slow.
12554The Calculator normally displays the message @samp{Working...} in the
12555echo area during any command that may be slow. In addition, iterative
12556operations such as square roots and trigonometric functions display the
12557intermediate result at each step. Both of these types of messages can
12558be disabled if you find them distracting.
12559
12560@kindex m w
12561@pindex calc-working
12562Type @kbd{m w} (@code{calc-working}) with a numeric prefix of 0 to
12563disable all ``working'' messages. Use a numeric prefix of 1 to enable
12564only the plain @samp{Working...} message. Use a numeric prefix of 2 to
12565see intermediate results as well. With no numeric prefix this displays
12566the current mode.
12567
12568While it may seem that the ``working'' messages will slow Calc down
12569considerably, experiments have shown that their impact is actually
12570quite small. But if your terminal is slow you may find that it helps
12571to turn the messages off.
12572
12573@node Simplification Modes, Declarations, Calculation Modes, Mode Settings
12574@section Simplification Modes
12575
12576@noindent
12577The current @dfn{simplification mode} controls how numbers and formulas
12578are ``normalized'' when being taken from or pushed onto the stack.
12579Some normalizations are unavoidable, such as rounding floating-point
12580results to the current precision, and reducing fractions to simplest
12581form. Others, such as simplifying a formula like @expr{a+a} (or @expr{2+3}),
8e7046c3 12582are done automatically but can be turned off when necessary.
4009494e
GM
12583
12584When you press a key like @kbd{+} when @expr{2} and @expr{3} are on the
12585stack, Calc pops these numbers, normalizes them, creates the formula
12586@expr{2+3}, normalizes it, and pushes the result. Of course the standard
12587rules for normalizing @expr{2+3} will produce the result @expr{5}.
12588
12589Simplification mode commands consist of the lower-case @kbd{m} prefix key
12590followed by a shifted letter.
12591
12592@kindex m O
12593@pindex calc-no-simplify-mode
12594The @kbd{m O} (@code{calc-no-simplify-mode}) command turns off all optional
12595simplifications. These would leave a formula like @expr{2+3} alone. In
12596fact, nothing except simple numbers are ever affected by normalization
d2bd74ff
JB
12597in this mode. Explicit simplification commands, such as @kbd{=} or
12598@kbd{a s}, can still be given to simplify any formulas.
12599@xref{Algebraic Definitions}, for a sample use of
12600No-Simplification mode.
12601
4009494e
GM
12602
12603@kindex m N
12604@pindex calc-num-simplify-mode
12605The @kbd{m N} (@code{calc-num-simplify-mode}) command turns off simplification
12606of any formulas except those for which all arguments are constants. For
12607example, @expr{1+2} is simplified to @expr{3}, and @expr{a+(2-2)} is
12608simplified to @expr{a+0} but no further, since one argument of the sum
12609is not a constant. Unfortunately, @expr{(a+2)-2} is @emph{not} simplified
12610because the top-level @samp{-} operator's arguments are not both
12611constant numbers (one of them is the formula @expr{a+2}).
12612A constant is a number or other numeric object (such as a constant
12613error form or modulo form), or a vector all of whose
12614elements are constant.
12615
8e7046c3
JB
12616@kindex m I
12617@pindex calc-basic-simplify-mode
12618The @kbd{m I} (@code{calc-basic-simplify-mode}) command does some basic
d2bd74ff 12619simplifications for all formulas. This includes many easy and
4009494e
GM
12620fast algebraic simplifications such as @expr{a+0} to @expr{a}, and
12621@expr{a + 2 a} to @expr{3 a}, as well as evaluating functions like
12622@expr{@tfn{deriv}(x^2, x)} to @expr{2 x}.
12623
12624@kindex m B
12625@pindex calc-bin-simplify-mode
1dcac243 12626The @kbd{m B} (@code{calc-bin-simplify-mode}) mode applies the basic
4009494e
GM
12627simplifications to a result and then, if the result is an integer,
12628uses the @kbd{b c} (@code{calc-clip}) command to clip the integer according
12629to the current binary word size. @xref{Binary Functions}. Real numbers
12630are rounded to the nearest integer and then clipped; other kinds of
1dcac243 12631results (after the basic simplifications) are left alone.
4009494e 12632
8e7046c3
JB
12633@kindex m A
12634@pindex calc-alg-simplify-mode
12635The @kbd{m A} (@code{calc-alg-simplify-mode}) mode does standard
d2bd74ff 12636algebraic simplifications. @xref{Algebraic Simplifications}.
4009494e
GM
12637
12638@kindex m E
12639@pindex calc-ext-simplify-mode
8e7046c3
JB
12640The @kbd{m E} (@code{calc-ext-simplify-mode}) mode does ``extended'', or
12641``unsafe'', algebraic simplification. @xref{Unsafe Simplifications}.
4009494e
GM
12642
12643@kindex m U
12644@pindex calc-units-simplify-mode
12645The @kbd{m U} (@code{calc-units-simplify-mode}) mode does units
8e7046c3
JB
12646simplification. @xref{Simplification of Units}. These include the
12647algebraic simplifications, plus variable names which
4009494e
GM
12648are identifiable as unit names (like @samp{mm} for ``millimeters'')
12649are simplified with their unit definitions in mind.
12650
12651A common technique is to set the simplification mode down to the lowest
12652amount of simplification you will allow to be applied automatically, then
12653use manual commands like @kbd{a s} and @kbd{c c} (@code{calc-clean}) to
d2bd74ff 12654perform higher types of simplifications on demand.
4009494e
GM
12655@node Declarations, Display Modes, Simplification Modes, Mode Settings
12656@section Declarations
12657
12658@noindent
12659A @dfn{declaration} is a statement you make that promises you will
12660use a certain variable or function in a restricted way. This may
12661give Calc the freedom to do things that it couldn't do if it had to
12662take the fully general situation into account.
12663
12664@menu
12665* Declaration Basics::
12666* Kinds of Declarations::
12667* Functions for Declarations::
12668@end menu
12669
12670@node Declaration Basics, Kinds of Declarations, Declarations, Declarations
12671@subsection Declaration Basics
12672
12673@noindent
12674@kindex s d
12675@pindex calc-declare-variable
12676The @kbd{s d} (@code{calc-declare-variable}) command is the easiest
12677way to make a declaration for a variable. This command prompts for
12678the variable name, then prompts for the declaration. The default
12679at the declaration prompt is the previous declaration, if any.
12680You can edit this declaration, or press @kbd{C-k} to erase it and
12681type a new declaration. (Or, erase it and press @key{RET} to clear
12682the declaration, effectively ``undeclaring'' the variable.)
12683
12684A declaration is in general a vector of @dfn{type symbols} and
12685@dfn{range} values. If there is only one type symbol or range value,
12686you can write it directly rather than enclosing it in a vector.
12687For example, @kbd{s d foo @key{RET} real @key{RET}} declares @code{foo} to
12688be a real number, and @kbd{s d bar @key{RET} [int, const, [1..6]] @key{RET}}
12689declares @code{bar} to be a constant integer between 1 and 6.
12690(Actually, you can omit the outermost brackets and Calc will
12691provide them for you: @kbd{s d bar @key{RET} int, const, [1..6] @key{RET}}.)
12692
12693@cindex @code{Decls} variable
12694@vindex Decls
12695Declarations in Calc are kept in a special variable called @code{Decls}.
12696This variable encodes the set of all outstanding declarations in
12697the form of a matrix. Each row has two elements: A variable or
12698vector of variables declared by that row, and the declaration
12699specifier as described above. You can use the @kbd{s D} command to
12700edit this variable if you wish to see all the declarations at once.
12701@xref{Operations on Variables}, for a description of this command
12702and the @kbd{s p} command that allows you to save your declarations
12703permanently if you wish.
12704
12705Items being declared can also be function calls. The arguments in
12706the call are ignored; the effect is to say that this function returns
12707values of the declared type for any valid arguments. The @kbd{s d}
12708command declares only variables, so if you wish to make a function
12709declaration you will have to edit the @code{Decls} matrix yourself.
12710
12711For example, the declaration matrix
12712
12713@smallexample
12714@group
12715[ [ foo, real ]
12716 [ [j, k, n], int ]
12717 [ f(1,2,3), [0 .. inf) ] ]
12718@end group
12719@end smallexample
12720
12721@noindent
12722declares that @code{foo} represents a real number, @code{j}, @code{k}
12723and @code{n} represent integers, and the function @code{f} always
12724returns a real number in the interval shown.
12725
12726@vindex All
12727If there is a declaration for the variable @code{All}, then that
12728declaration applies to all variables that are not otherwise declared.
12729It does not apply to function names. For example, using the row
12730@samp{[All, real]} says that all your variables are real unless they
12731are explicitly declared without @code{real} in some other row.
12732The @kbd{s d} command declares @code{All} if you give a blank
12733response to the variable-name prompt.
12734
12735@node Kinds of Declarations, Functions for Declarations, Declaration Basics, Declarations
12736@subsection Kinds of Declarations
12737
12738@noindent
12739The type-specifier part of a declaration (that is, the second prompt
12740in the @kbd{s d} command) can be a type symbol, an interval, or a
12741vector consisting of zero or more type symbols followed by zero or
12742more intervals or numbers that represent the set of possible values
12743for the variable.
12744
12745@smallexample
12746@group
12747[ [ a, [1, 2, 3, 4, 5] ]
12748 [ b, [1 .. 5] ]
12749 [ c, [int, 1 .. 5] ] ]
12750@end group
12751@end smallexample
12752
12753Here @code{a} is declared to contain one of the five integers shown;
12754@code{b} is any number in the interval from 1 to 5 (any real number
12755since we haven't specified), and @code{c} is any integer in that
12756interval. Thus the declarations for @code{a} and @code{c} are
12757nearly equivalent (see below).
12758
12759The type-specifier can be the empty vector @samp{[]} to say that
12760nothing is known about a given variable's value. This is the same
12761as not declaring the variable at all except that it overrides any
12762@code{All} declaration which would otherwise apply.
12763
12764The initial value of @code{Decls} is the empty vector @samp{[]}.
12765If @code{Decls} has no stored value or if the value stored in it
12766is not valid, it is ignored and there are no declarations as far
12767as Calc is concerned. (The @kbd{s d} command will replace such a
12768malformed value with a fresh empty matrix, @samp{[]}, before recording
12769the new declaration.) Unrecognized type symbols are ignored.
12770
12771The following type symbols describe what sorts of numbers will be
12772stored in a variable:
12773
12774@table @code
12775@item int
12776Integers.
12777@item numint
12778Numerical integers. (Integers or integer-valued floats.)
12779@item frac
12780Fractions. (Rational numbers which are not integers.)
12781@item rat
12782Rational numbers. (Either integers or fractions.)
12783@item float
12784Floating-point numbers.
12785@item real
12786Real numbers. (Integers, fractions, or floats. Actually,
12787intervals and error forms with real components also count as
12788reals here.)
12789@item pos
12790Positive real numbers. (Strictly greater than zero.)
12791@item nonneg
12792Nonnegative real numbers. (Greater than or equal to zero.)
12793@item number
12794Numbers. (Real or complex.)
12795@end table
12796
12797Calc uses this information to determine when certain simplifications
12798of formulas are safe. For example, @samp{(x^y)^z} cannot be
12799simplified to @samp{x^(y z)} in general; for example,
12800@samp{((-3)^2)^1:2} is 3, but @samp{(-3)^(2*1:2) = (-3)^1} is @mathit{-3}.
12801However, this simplification @emph{is} safe if @code{z} is known
12802to be an integer, or if @code{x} is known to be a nonnegative
12803real number. If you have given declarations that allow Calc to
12804deduce either of these facts, Calc will perform this simplification
12805of the formula.
12806
12807Calc can apply a certain amount of logic when using declarations.
12808For example, @samp{(x^y)^(2n+1)} will be simplified if @code{n}
12809has been declared @code{int}; Calc knows that an integer times an
12810integer, plus an integer, must always be an integer. (In fact,
12811Calc would simplify @samp{(-x)^(2n+1)} to @samp{-(x^(2n+1))} since
12812it is able to determine that @samp{2n+1} must be an odd integer.)
12813
12814Similarly, @samp{(abs(x)^y)^z} will be simplified to @samp{abs(x)^(y z)}
12815because Calc knows that the @code{abs} function always returns a
12816nonnegative real. If you had a @code{myabs} function that also had
12817this property, you could get Calc to recognize it by adding the row
12818@samp{[myabs(), nonneg]} to the @code{Decls} matrix.
12819
12820One instance of this simplification is @samp{sqrt(x^2)} (since the
12821@code{sqrt} function is effectively a one-half power). Normally
12822Calc leaves this formula alone. After the command
12823@kbd{s d x @key{RET} real @key{RET}}, however, it can simplify the formula to
12824@samp{abs(x)}. And after @kbd{s d x @key{RET} nonneg @key{RET}}, Calc can
12825simplify this formula all the way to @samp{x}.
12826
12827If there are any intervals or real numbers in the type specifier,
12828they comprise the set of possible values that the variable or
12829function being declared can have. In particular, the type symbol
12830@code{real} is effectively the same as the range @samp{[-inf .. inf]}
12831(note that infinity is included in the range of possible values);
12832@code{pos} is the same as @samp{(0 .. inf]}, and @code{nonneg} is
12833the same as @samp{[0 .. inf]}. Saying @samp{[real, [-5 .. 5]]} is
12834redundant because the fact that the variable is real can be
12835deduced just from the interval, but @samp{[int, [-5 .. 5]]} and
12836@samp{[rat, [-5 .. 5]]} are useful combinations.
12837
12838Note that the vector of intervals or numbers is in the same format
12839used by Calc's set-manipulation commands. @xref{Set Operations}.
12840
12841The type specifier @samp{[1, 2, 3]} is equivalent to
12842@samp{[numint, 1, 2, 3]}, @emph{not} to @samp{[int, 1, 2, 3]}.
12843In other words, the range of possible values means only that
12844the variable's value must be numerically equal to a number in
12845that range, but not that it must be equal in type as well.
12846Calc's set operations act the same way; @samp{in(2, [1., 2., 3.])}
12847and @samp{in(1.5, [1:2, 3:2, 5:2])} both report ``true.''
12848
12849If you use a conflicting combination of type specifiers, the
12850results are unpredictable. An example is @samp{[pos, [0 .. 5]]},
12851where the interval does not lie in the range described by the
12852type symbol.
12853
12854``Real'' declarations mostly affect simplifications involving powers
12855like the one described above. Another case where they are used
12856is in the @kbd{a P} command which returns a list of all roots of a
12857polynomial; if the variable has been declared real, only the real
12858roots (if any) will be included in the list.
12859
12860``Integer'' declarations are used for simplifications which are valid
12861only when certain values are integers (such as @samp{(x^y)^z}
12862shown above).
12863
8e7046c3
JB
12864Calc's algebraic simplifications also make use of declarations when
12865simplifying equations and inequalities. They will cancel @code{x}
4009494e
GM
12866from both sides of @samp{a x = b x} only if it is sure @code{x}
12867is non-zero, say, because it has a @code{pos} declaration.
12868To declare specifically that @code{x} is real and non-zero,
12869use @samp{[[-inf .. 0), (0 .. inf]]}. (There is no way in the
12870current notation to say that @code{x} is nonzero but not necessarily
12871real.) The @kbd{a e} command does ``unsafe'' simplifications,
c80e3b4a 12872including canceling @samp{x} from the equation when @samp{x} is
4009494e
GM
12873not known to be nonzero.
12874
12875Another set of type symbols distinguish between scalars and vectors.
12876
12877@table @code
12878@item scalar
12879The value is not a vector.
12880@item vector
12881The value is a vector.
12882@item matrix
12883The value is a matrix (a rectangular vector of vectors).
12884@item sqmatrix
12885The value is a square matrix.
12886@end table
12887
12888These type symbols can be combined with the other type symbols
12889described above; @samp{[int, matrix]} describes an object which
12890is a matrix of integers.
12891
12892Scalar/vector declarations are used to determine whether certain
12893algebraic operations are safe. For example, @samp{[a, b, c] + x}
12894is normally not simplified to @samp{[a + x, b + x, c + x]}, but
12895it will be if @code{x} has been declared @code{scalar}. On the
12896other hand, multiplication is usually assumed to be commutative,
12897but the terms in @samp{x y} will never be exchanged if both @code{x}
12898and @code{y} are known to be vectors or matrices. (Calc currently
12899never distinguishes between @code{vector} and @code{matrix}
12900declarations.)
12901
12902@xref{Matrix Mode}, for a discussion of Matrix mode and
12903Scalar mode, which are similar to declaring @samp{[All, matrix]}
12904or @samp{[All, scalar]} but much more convenient.
12905
12906One more type symbol that is recognized is used with the @kbd{H a d}
12907command for taking total derivatives of a formula. @xref{Calculus}.
12908
12909@table @code
12910@item const
12911The value is a constant with respect to other variables.
12912@end table
12913
12914Calc does not check the declarations for a variable when you store
12915a value in it. However, storing @mathit{-3.5} in a variable that has
12916been declared @code{pos}, @code{int}, or @code{matrix} may have
12917unexpected effects; Calc may evaluate @samp{sqrt(x^2)} to @expr{3.5}
12918if it substitutes the value first, or to @expr{-3.5} if @code{x}
12919was declared @code{pos} and the formula @samp{sqrt(x^2)} is
12920simplified to @samp{x} before the value is substituted. Before
12921using a variable for a new purpose, it is best to use @kbd{s d}
12922or @kbd{s D} to check to make sure you don't still have an old
12923declaration for the variable that will conflict with its new meaning.
12924
12925@node Functions for Declarations, , Kinds of Declarations, Declarations
12926@subsection Functions for Declarations
12927
12928@noindent
12929Calc has a set of functions for accessing the current declarations
12930in a convenient manner. These functions return 1 if the argument
12931can be shown to have the specified property, or 0 if the argument
12932can be shown @emph{not} to have that property; otherwise they are
12933left unevaluated. These functions are suitable for use with rewrite
12934rules (@pxref{Conditional Rewrite Rules}) or programming constructs
12935(@pxref{Conditionals in Macros}). They can be entered only using
12936algebraic notation. @xref{Logical Operations}, for functions
12937that perform other tests not related to declarations.
12938
12939For example, @samp{dint(17)} returns 1 because 17 is an integer, as
12940do @samp{dint(n)} and @samp{dint(2 n - 3)} if @code{n} has been declared
12941@code{int}, but @samp{dint(2.5)} and @samp{dint(n + 0.5)} return 0.
12942Calc consults knowledge of its own built-in functions as well as your
12943own declarations: @samp{dint(floor(x))} returns 1.
12944
12945@ignore
12946@starindex
12947@end ignore
12948@tindex dint
12949@ignore
12950@starindex
12951@end ignore
12952@tindex dnumint
12953@ignore
12954@starindex
12955@end ignore
12956@tindex dnatnum
12957The @code{dint} function checks if its argument is an integer.
12958The @code{dnatnum} function checks if its argument is a natural
12959number, i.e., a nonnegative integer. The @code{dnumint} function
12960checks if its argument is numerically an integer, i.e., either an
12961integer or an integer-valued float. Note that these and the other
12962data type functions also accept vectors or matrices composed of
12963suitable elements, and that real infinities @samp{inf} and @samp{-inf}
12964are considered to be integers for the purposes of these functions.
12965
12966@ignore
12967@starindex
12968@end ignore
12969@tindex drat
12970The @code{drat} function checks if its argument is rational, i.e.,
12971an integer or fraction. Infinities count as rational, but intervals
12972and error forms do not.
12973
12974@ignore
12975@starindex
12976@end ignore
12977@tindex dreal
12978The @code{dreal} function checks if its argument is real. This
12979includes integers, fractions, floats, real error forms, and intervals.
12980
12981@ignore
12982@starindex
12983@end ignore
12984@tindex dimag
12985The @code{dimag} function checks if its argument is imaginary,
12986i.e., is mathematically equal to a real number times @expr{i}.
12987
12988@ignore
12989@starindex
12990@end ignore
12991@tindex dpos
12992@ignore
12993@starindex
12994@end ignore
12995@tindex dneg
12996@ignore
12997@starindex
12998@end ignore
12999@tindex dnonneg
13000The @code{dpos} function checks for positive (but nonzero) reals.
13001The @code{dneg} function checks for negative reals. The @code{dnonneg}
13002function checks for nonnegative reals, i.e., reals greater than or
8e7046c3
JB
13003equal to zero. Note that Calc's algebraic simplifications, which are
13004effectively applied to all conditions in rewrite rules, can simplify
13005an expression like @expr{x > 0} to 1 or 0 using @code{dpos}.
13006So the actual functions @code{dpos}, @code{dneg}, and @code{dnonneg}
4009494e
GM
13007are rarely necessary.
13008
13009@ignore
13010@starindex
13011@end ignore
13012@tindex dnonzero
13013The @code{dnonzero} function checks that its argument is nonzero.
13014This includes all nonzero real or complex numbers, all intervals that
13015do not include zero, all nonzero modulo forms, vectors all of whose
13016elements are nonzero, and variables or formulas whose values can be
13017deduced to be nonzero. It does not include error forms, since they
13018represent values which could be anything including zero. (This is
13019also the set of objects considered ``true'' in conditional contexts.)
13020
13021@ignore
13022@starindex
13023@end ignore
13024@tindex deven
13025@ignore
13026@starindex
13027@end ignore
13028@tindex dodd
13029The @code{deven} function returns 1 if its argument is known to be
13030an even integer (or integer-valued float); it returns 0 if its argument
13031is known not to be even (because it is known to be odd or a non-integer).
8e7046c3 13032Calc's algebraic simplifications use this to simplify a test of the form
4009494e
GM
13033@samp{x % 2 = 0}. There is also an analogous @code{dodd} function.
13034
13035@ignore
13036@starindex
13037@end ignore
13038@tindex drange
13039The @code{drange} function returns a set (an interval or a vector
13040of intervals and/or numbers; @pxref{Set Operations}) that describes
13041the set of possible values of its argument. If the argument is
13042a variable or a function with a declaration, the range is copied
13043from the declaration. Otherwise, the possible signs of the
13044expression are determined using a method similar to @code{dpos},
13045etc., and a suitable set like @samp{[0 .. inf]} is returned. If
13046the expression is not provably real, the @code{drange} function
13047remains unevaluated.
13048
13049@ignore
13050@starindex
13051@end ignore
13052@tindex dscalar
13053The @code{dscalar} function returns 1 if its argument is provably
13054scalar, or 0 if its argument is provably non-scalar. It is left
13055unevaluated if this cannot be determined. (If Matrix mode or Scalar
13056mode is in effect, this function returns 1 or 0, respectively,
13057if it has no other information.) When Calc interprets a condition
13058(say, in a rewrite rule) it considers an unevaluated formula to be
13059``false.'' Thus, @samp{dscalar(a)} is ``true'' only if @code{a} is
13060provably scalar, and @samp{!dscalar(a)} is ``true'' only if @code{a}
13061is provably non-scalar; both are ``false'' if there is insufficient
13062information to tell.
13063
13064@node Display Modes, Language Modes, Declarations, Mode Settings
13065@section Display Modes
13066
13067@noindent
13068The commands in this section are two-key sequences beginning with the
13069@kbd{d} prefix. The @kbd{d l} (@code{calc-line-numbering}) and @kbd{d b}
13070(@code{calc-line-breaking}) commands are described elsewhere;
13071@pxref{Stack Basics} and @pxref{Normal Language Modes}, respectively.
13072Display formats for vectors and matrices are also covered elsewhere;
13073@pxref{Vector and Matrix Formats}.
13074
13075One thing all display modes have in common is their treatment of the
13076@kbd{H} prefix. This prefix causes any mode command that would normally
13077refresh the stack to leave the stack display alone. The word ``Dirty''
13078will appear in the mode line when Calc thinks the stack display may not
13079reflect the latest mode settings.
13080
13081@kindex d @key{RET}
13082@pindex calc-refresh-top
13083The @kbd{d @key{RET}} (@code{calc-refresh-top}) command reformats the
13084top stack entry according to all the current modes. Positive prefix
13085arguments reformat the top @var{n} entries; negative prefix arguments
13086reformat the specified entry, and a prefix of zero is equivalent to
13087@kbd{d @key{SPC}} (@code{calc-refresh}), which reformats the entire stack.
13088For example, @kbd{H d s M-2 d @key{RET}} changes to scientific notation
13089but reformats only the top two stack entries in the new mode.
13090
13091The @kbd{I} prefix has another effect on the display modes. The mode
13092is set only temporarily; the top stack entry is reformatted according
13093to that mode, then the original mode setting is restored. In other
13094words, @kbd{I d s} is equivalent to @kbd{H d s d @key{RET} H d (@var{old mode})}.
13095
13096@menu
13097* Radix Modes::
13098* Grouping Digits::
13099* Float Formats::
13100* Complex Formats::
13101* Fraction Formats::
13102* HMS Formats::
13103* Date Formats::
13104* Truncating the Stack::
13105* Justification::
13106* Labels::
13107@end menu
13108
13109@node Radix Modes, Grouping Digits, Display Modes, Display Modes
13110@subsection Radix Modes
13111
13112@noindent
13113@cindex Radix display
13114@cindex Non-decimal numbers
13115@cindex Decimal and non-decimal numbers
13116Calc normally displays numbers in decimal (@dfn{base-10} or @dfn{radix-10})
13117notation. Calc can actually display in any radix from two (binary) to 36.
13118When the radix is above 10, the letters @code{A} to @code{Z} are used as
13119digits. When entering such a number, letter keys are interpreted as
13120potential digits rather than terminating numeric entry mode.
13121
13122@kindex d 2
13123@kindex d 8
13124@kindex d 6
13125@kindex d 0
13126@cindex Hexadecimal integers
13127@cindex Octal integers
13128The key sequences @kbd{d 2}, @kbd{d 8}, @kbd{d 6}, and @kbd{d 0} select
13129binary, octal, hexadecimal, and decimal as the current display radix,
13130respectively. Numbers can always be entered in any radix, though the
13131current radix is used as a default if you press @kbd{#} without any initial
13132digits. A number entered without a @kbd{#} is @emph{always} interpreted
13133as decimal.
13134
13135@kindex d r
13136@pindex calc-radix
13137To set the radix generally, use @kbd{d r} (@code{calc-radix}) and enter
13138an integer from 2 to 36. You can specify the radix as a numeric prefix
13139argument; otherwise you will be prompted for it.
13140
13141@kindex d z
13142@pindex calc-leading-zeros
13143@cindex Leading zeros
13144Integers normally are displayed with however many digits are necessary to
13145represent the integer and no more. The @kbd{d z} (@code{calc-leading-zeros})
13146command causes integers to be padded out with leading zeros according to the
13147current binary word size. (@xref{Binary Functions}, for a discussion of
13148word size.) If the absolute value of the word size is @expr{w}, all integers
40ba43b4 13149are displayed with at least enough digits to represent
4009494e 13150@texline @math{2^w-1}
40ba43b4 13151@infoline @expr{(2^w)-1}
4009494e 13152in the current radix. (Larger integers will still be displayed in their
40ba43b4 13153entirety.)
4009494e 13154
0e983327 13155@cindex Two's complements
f8b91752
JB
13156Calc can display @expr{w}-bit integers using two's complement
13157notation, although this is most useful with the binary, octal and
13158hexadecimal display modes. This option is selected by using the
13159@kbd{O} option prefix before setting the display radix, and a negative word
13160size might be appropriate (@pxref{Binary Functions}). In two's
13161complement notation, the integers in the (nearly) symmetric interval
13162from
17291a1f
JB
13163@texline @math{-2^{w-1}}
13164@infoline @expr{-2^(w-1)}
13165to
13166@texline @math{2^{w-1}-1}
13167@infoline @expr{2^(w-1)-1}
0e983327 13168are represented by the integers from @expr{0} to @expr{2^w-1}:
5ea5dbc9 13169the integers from @expr{0} to
17291a1f
JB
13170@texline @math{2^{w-1}-1}
13171@infoline @expr{2^(w-1)-1}
0e983327 13172are represented by themselves and the integers from
17291a1f
JB
13173@texline @math{-2^{w-1}}
13174@infoline @expr{-2^(w-1)}
40ba43b4 13175to @expr{-1} are represented by the integers from
17291a1f
JB
13176@texline @math{2^{w-1}}
13177@infoline @expr{2^(w-1)}
0e983327
JB
13178to @expr{2^w-1} (the integer @expr{k} is represented by @expr{k+2^w}).
13179Calc will display a two's complement integer by the radix (either
13180@expr{2}, @expr{8} or @expr{16}), two @kbd{#} symbols, and then its
13181representation (including any leading zeros necessary to include all
13182@expr{w} bits). In a two's complement display mode, numbers that
13183are not displayed in two's complement notation (i.e., that aren't
40ba43b4 13184integers from
17291a1f
JB
13185@texline @math{-2^{w-1}}
13186@infoline @expr{-2^(w-1)}
5ea5dbc9 13187to
17291a1f
JB
13188@c (
13189@texline @math{2^{w-1}-1})
13190@infoline @expr{2^(w-1)-1})
5ea5dbc9
JB
13191will be represented using Calc's usual notation (in the appropriate
13192radix).
17291a1f 13193
4009494e
GM
13194@node Grouping Digits, Float Formats, Radix Modes, Display Modes
13195@subsection Grouping Digits
13196
13197@noindent
13198@kindex d g
13199@pindex calc-group-digits
13200@cindex Grouping digits
13201@cindex Digit grouping
13202Long numbers can be hard to read if they have too many digits. For
13203example, the factorial of 30 is 33 digits long! Press @kbd{d g}
13204(@code{calc-group-digits}) to enable @dfn{Grouping} mode, in which digits
13205are displayed in clumps of 3 or 4 (depending on the current radix)
13206separated by commas.
13207
13208The @kbd{d g} command toggles grouping on and off.
13209With a numeric prefix of 0, this command displays the current state of
13210the grouping flag; with an argument of minus one it disables grouping;
13211with a positive argument @expr{N} it enables grouping on every @expr{N}
13212digits. For floating-point numbers, grouping normally occurs only
13213before the decimal point. A negative prefix argument @expr{-N} enables
13214grouping every @expr{N} digits both before and after the decimal point.
13215
13216@kindex d ,
13217@pindex calc-group-char
13218The @kbd{d ,} (@code{calc-group-char}) command allows you to choose any
13219character as the grouping separator. The default is the comma character.
13220If you find it difficult to read vectors of large integers grouped with
13221commas, you may wish to use spaces or some other character instead.
13222This command takes the next character you type, whatever it is, and
13223uses it as the digit separator. As a special case, @kbd{d , \} selects
13224@samp{\,} (@TeX{}'s thin-space symbol) as the digit separator.
13225
13226Please note that grouped numbers will not generally be parsed correctly
13227if re-read in textual form, say by the use of @kbd{C-x * y} and @kbd{C-x * g}.
13228(@xref{Kill and Yank}, for details on these commands.) One exception is
13229the @samp{\,} separator, which doesn't interfere with parsing because it
13230is ignored by @TeX{} language mode.
13231
13232@node Float Formats, Complex Formats, Grouping Digits, Display Modes
13233@subsection Float Formats
13234
13235@noindent
13236Floating-point quantities are normally displayed in standard decimal
13237form, with scientific notation used if the exponent is especially high
13238or low. All significant digits are normally displayed. The commands
13239in this section allow you to choose among several alternative display
13240formats for floats.
13241
13242@kindex d n
13243@pindex calc-normal-notation
13244The @kbd{d n} (@code{calc-normal-notation}) command selects the normal
13245display format. All significant figures in a number are displayed.
13246With a positive numeric prefix, numbers are rounded if necessary to
13247that number of significant digits. With a negative numerix prefix,
13248the specified number of significant digits less than the current
13249precision is used. (Thus @kbd{C-u -2 d n} displays 10 digits if the
13250current precision is 12.)
13251
13252@kindex d f
13253@pindex calc-fix-notation
13254The @kbd{d f} (@code{calc-fix-notation}) command selects fixed-point
13255notation. The numeric argument is the number of digits after the
13256decimal point, zero or more. This format will relax into scientific
13257notation if a nonzero number would otherwise have been rounded all the
13258way to zero. Specifying a negative number of digits is the same as
13259for a positive number, except that small nonzero numbers will be rounded
13260to zero rather than switching to scientific notation.
13261
13262@kindex d s
13263@pindex calc-sci-notation
13264@cindex Scientific notation, display of
13265The @kbd{d s} (@code{calc-sci-notation}) command selects scientific
13266notation. A positive argument sets the number of significant figures
13267displayed, of which one will be before and the rest after the decimal
13268point. A negative argument works the same as for @kbd{d n} format.
13269The default is to display all significant digits.
13270
13271@kindex d e
13272@pindex calc-eng-notation
13273@cindex Engineering notation, display of
13274The @kbd{d e} (@code{calc-eng-notation}) command selects engineering
13275notation. This is similar to scientific notation except that the
13276exponent is rounded down to a multiple of three, with from one to three
13277digits before the decimal point. An optional numeric prefix sets the
13278number of significant digits to display, as for @kbd{d s}.
13279
13280It is important to distinguish between the current @emph{precision} and
13281the current @emph{display format}. After the commands @kbd{C-u 10 p}
13282and @kbd{C-u 6 d n} the Calculator computes all results to ten
13283significant figures but displays only six. (In fact, intermediate
13284calculations are often carried to one or two more significant figures,
13285but values placed on the stack will be rounded down to ten figures.)
13286Numbers are never actually rounded to the display precision for storage,
13287except by commands like @kbd{C-k} and @kbd{C-x * y} which operate on the
13288actual displayed text in the Calculator buffer.
13289
13290@kindex d .
13291@pindex calc-point-char
13292The @kbd{d .} (@code{calc-point-char}) command selects the character used
13293as a decimal point. Normally this is a period; users in some countries
13294may wish to change this to a comma. Note that this is only a display
13295style; on entry, periods must always be used to denote floating-point
13296numbers, and commas to separate elements in a list.
13297
13298@node Complex Formats, Fraction Formats, Float Formats, Display Modes
13299@subsection Complex Formats
13300
13301@noindent
13302@kindex d c
13303@pindex calc-complex-notation
13304There are three supported notations for complex numbers in rectangular
13305form. The default is as a pair of real numbers enclosed in parentheses
13306and separated by a comma: @samp{(a,b)}. The @kbd{d c}
13307(@code{calc-complex-notation}) command selects this style.
13308
13309@kindex d i
13310@pindex calc-i-notation
13311@kindex d j
13312@pindex calc-j-notation
13313The other notations are @kbd{d i} (@code{calc-i-notation}), in which
13314numbers are displayed in @samp{a+bi} form, and @kbd{d j}
13315(@code{calc-j-notation}) which displays the form @samp{a+bj} preferred
13316in some disciplines.
13317
13318@cindex @code{i} variable
13319@vindex i
13320Complex numbers are normally entered in @samp{(a,b)} format.
13321If you enter @samp{2+3i} as an algebraic formula, it will be stored as
13322the formula @samp{2 + 3 * i}. However, if you use @kbd{=} to evaluate
13323this formula and you have not changed the variable @samp{i}, the @samp{i}
13324will be interpreted as @samp{(0,1)} and the formula will be simplified
13325to @samp{(2,3)}. Other commands (like @code{calc-sin}) will @emph{not}
13326interpret the formula @samp{2 + 3 * i} as a complex number.
13327@xref{Variables}, under ``special constants.''
13328
13329@node Fraction Formats, HMS Formats, Complex Formats, Display Modes
13330@subsection Fraction Formats
13331
13332@noindent
13333@kindex d o
13334@pindex calc-over-notation
13335Display of fractional numbers is controlled by the @kbd{d o}
13336(@code{calc-over-notation}) command. By default, a number like
13337eight thirds is displayed in the form @samp{8:3}. The @kbd{d o} command
13338prompts for a one- or two-character format. If you give one character,
13339that character is used as the fraction separator. Common separators are
13340@samp{:} and @samp{/}. (During input of numbers, the @kbd{:} key must be
13341used regardless of the display format; in particular, the @kbd{/} is used
13342for RPN-style division, @emph{not} for entering fractions.)
13343
13344If you give two characters, fractions use ``integer-plus-fractional-part''
13345notation. For example, the format @samp{+/} would display eight thirds
13346as @samp{2+2/3}. If two colons are present in a number being entered,
13347the number is interpreted in this form (so that the entries @kbd{2:2:3}
13348and @kbd{8:3} are equivalent).
13349
13350It is also possible to follow the one- or two-character format with
13351a number. For example: @samp{:10} or @samp{+/3}. In this case,
13352Calc adjusts all fractions that are displayed to have the specified
13353denominator, if possible. Otherwise it adjusts the denominator to
13354be a multiple of the specified value. For example, in @samp{:6} mode
13355the fraction @expr{1:6} will be unaffected, but @expr{2:3} will be
13356displayed as @expr{4:6}, @expr{1:2} will be displayed as @expr{3:6},
13357and @expr{1:8} will be displayed as @expr{3:24}. Integers are also
13358affected by this mode: 3 is displayed as @expr{18:6}. Note that the
13359format @samp{:1} writes fractions the same as @samp{:}, but it writes
13360integers as @expr{n:1}.
13361
13362The fraction format does not affect the way fractions or integers are
13363stored, only the way they appear on the screen. The fraction format
13364never affects floats.
13365
13366@node HMS Formats, Date Formats, Fraction Formats, Display Modes
13367@subsection HMS Formats
13368
13369@noindent
13370@kindex d h
13371@pindex calc-hms-notation
13372The @kbd{d h} (@code{calc-hms-notation}) command controls the display of
13373HMS (hours-minutes-seconds) forms. It prompts for a string which
13374consists basically of an ``hours'' marker, optional punctuation, a
13375``minutes'' marker, more optional punctuation, and a ``seconds'' marker.
13376Punctuation is zero or more spaces, commas, or semicolons. The hours
13377marker is one or more non-punctuation characters. The minutes and
13378seconds markers must be single non-punctuation characters.
13379
13380The default HMS format is @samp{@@ ' "}, producing HMS values of the form
13381@samp{23@@ 30' 15.75"}. The format @samp{deg, ms} would display this same
13382value as @samp{23deg, 30m15.75s}. During numeric entry, the @kbd{h} or @kbd{o}
13383keys are recognized as synonyms for @kbd{@@} regardless of display format.
13384The @kbd{m} and @kbd{s} keys are recognized as synonyms for @kbd{'} and
13385@kbd{"}, respectively, but only if an @kbd{@@} (or @kbd{h} or @kbd{o}) has
13386already been typed; otherwise, they have their usual meanings
13387(@kbd{m-} prefix and @kbd{s-} prefix). Thus, @kbd{5 "}, @kbd{0 @@ 5 "}, and
13388@kbd{0 h 5 s} are some of the ways to enter the quantity ``five seconds.''
13389The @kbd{'} key is recognized as ``minutes'' only if @kbd{@@} (or @kbd{h} or
13390@kbd{o}) has already been pressed; otherwise it means to switch to algebraic
13391entry.
13392
13393@node Date Formats, Truncating the Stack, HMS Formats, Display Modes
13394@subsection Date Formats
13395
13396@noindent
13397@kindex d d
13398@pindex calc-date-notation
13399The @kbd{d d} (@code{calc-date-notation}) command controls the display
13400of date forms (@pxref{Date Forms}). It prompts for a string which
13401contains letters that represent the various parts of a date and time.
13402To show which parts should be omitted when the form represents a pure
13403date with no time, parts of the string can be enclosed in @samp{< >}
13404marks. If you don't include @samp{< >} markers in the format, Calc
13405guesses at which parts, if any, should be omitted when formatting
13406pure dates.
13407
13408The default format is: @samp{<H:mm:SSpp >Www Mmm D, YYYY}.
13409An example string in this format is @samp{3:32pm Wed Jan 9, 1991}.
13410If you enter a blank format string, this default format is
13411reestablished.
13412
13413Calc uses @samp{< >} notation for nameless functions as well as for
13414dates. @xref{Specifying Operators}. To avoid confusion with nameless
13415functions, your date formats should avoid using the @samp{#} character.
13416
13417@menu
13418* Date Formatting Codes::
13419* Free-Form Dates::
13420* Standard Date Formats::
13421@end menu
13422
13423@node Date Formatting Codes, Free-Form Dates, Date Formats, Date Formats
13424@subsubsection Date Formatting Codes
13425
13426@noindent
13427When displaying a date, the current date format is used. All
13428characters except for letters and @samp{<} and @samp{>} are
13429copied literally when dates are formatted. The portion between
13430@samp{< >} markers is omitted for pure dates, or included for
13431date/time forms. Letters are interpreted according to the table
13432below.
13433
13434When dates are read in during algebraic entry, Calc first tries to
13435match the input string to the current format either with or without
13436the time part. The punctuation characters (including spaces) must
13437match exactly; letter fields must correspond to suitable text in
13438the input. If this doesn't work, Calc checks if the input is a
13439simple number; if so, the number is interpreted as a number of days
13440since Jan 1, 1 AD. Otherwise, Calc tries a much more relaxed and
13441flexible algorithm which is described in the next section.
13442
13443Weekday names are ignored during reading.
13444
13445Two-digit year numbers are interpreted as lying in the range
13446from 1941 to 2039. Years outside that range are always
13447entered and displayed in full. Year numbers with a leading
13448@samp{+} sign are always interpreted exactly, allowing the
13449entry and display of the years 1 through 99 AD.
13450
13451Here is a complete list of the formatting codes for dates:
13452
13453@table @asis
13454@item Y
13455Year: ``91'' for 1991, ``7'' for 2007, ``+23'' for 23 AD.
13456@item YY
13457Year: ``91'' for 1991, ``07'' for 2007, ``+23'' for 23 AD.
13458@item BY
13459Year: ``91'' for 1991, `` 7'' for 2007, ``+23'' for 23 AD.
13460@item YYY
13461Year: ``1991'' for 1991, ``23'' for 23 AD.
13462@item YYYY
13463Year: ``1991'' for 1991, ``+23'' for 23 AD.
13464@item aa
13465Year: ``ad'' or blank.
13466@item AA
13467Year: ``AD'' or blank.
13468@item aaa
13469Year: ``ad '' or blank. (Note trailing space.)
13470@item AAA
13471Year: ``AD '' or blank.
13472@item aaaa
13473Year: ``a.d.'' or blank.
13474@item AAAA
13475Year: ``A.D.'' or blank.
13476@item bb
13477Year: ``bc'' or blank.
13478@item BB
13479Year: ``BC'' or blank.
13480@item bbb
13481Year: `` bc'' or blank. (Note leading space.)
13482@item BBB
13483Year: `` BC'' or blank.
13484@item bbbb
13485Year: ``b.c.'' or blank.
13486@item BBBB
13487Year: ``B.C.'' or blank.
13488@item M
13489Month: ``8'' for August.
13490@item MM
13491Month: ``08'' for August.
13492@item BM
13493Month: `` 8'' for August.
13494@item MMM
13495Month: ``AUG'' for August.
13496@item Mmm
13497Month: ``Aug'' for August.
13498@item mmm
13499Month: ``aug'' for August.
13500@item MMMM
13501Month: ``AUGUST'' for August.
13502@item Mmmm
13503Month: ``August'' for August.
13504@item D
13505Day: ``7'' for 7th day of month.
13506@item DD
13507Day: ``07'' for 7th day of month.
13508@item BD
13509Day: `` 7'' for 7th day of month.
13510@item W
13511Weekday: ``0'' for Sunday, ``6'' for Saturday.
13512@item WWW
13513Weekday: ``SUN'' for Sunday.
13514@item Www
13515Weekday: ``Sun'' for Sunday.
13516@item www
13517Weekday: ``sun'' for Sunday.
13518@item WWWW
13519Weekday: ``SUNDAY'' for Sunday.
13520@item Wwww
13521Weekday: ``Sunday'' for Sunday.
13522@item d
13523Day of year: ``34'' for Feb. 3.
13524@item ddd
13525Day of year: ``034'' for Feb. 3.
13526@item bdd
13527Day of year: `` 34'' for Feb. 3.
13528@item h
13529Hour: ``5'' for 5 AM; ``17'' for 5 PM.
13530@item hh
13531Hour: ``05'' for 5 AM; ``17'' for 5 PM.
13532@item bh
13533Hour: `` 5'' for 5 AM; ``17'' for 5 PM.
13534@item H
13535Hour: ``5'' for 5 AM and 5 PM.
13536@item HH
13537Hour: ``05'' for 5 AM and 5 PM.
13538@item BH
13539Hour: `` 5'' for 5 AM and 5 PM.
13540@item p
13541AM/PM: ``a'' or ``p''.
13542@item P
13543AM/PM: ``A'' or ``P''.
13544@item pp
13545AM/PM: ``am'' or ``pm''.
13546@item PP
13547AM/PM: ``AM'' or ``PM''.
13548@item pppp
13549AM/PM: ``a.m.'' or ``p.m.''.
13550@item PPPP
13551AM/PM: ``A.M.'' or ``P.M.''.
13552@item m
13553Minutes: ``7'' for 7.
13554@item mm
13555Minutes: ``07'' for 7.
13556@item bm
13557Minutes: `` 7'' for 7.
13558@item s
13559Seconds: ``7'' for 7; ``7.23'' for 7.23.
13560@item ss
13561Seconds: ``07'' for 7; ``07.23'' for 7.23.
13562@item bs
13563Seconds: `` 7'' for 7; `` 7.23'' for 7.23.
13564@item SS
13565Optional seconds: ``07'' for 7; blank for 0.
13566@item BS
13567Optional seconds: `` 7'' for 7; blank for 0.
13568@item N
13569Numeric date/time: ``726842.25'' for 6:00am Wed Jan 9, 1991.
13570@item n
13571Numeric date: ``726842'' for any time on Wed Jan 9, 1991.
13572@item J
13573Julian date/time: ``2448265.75'' for 6:00am Wed Jan 9, 1991.
13574@item j
13575Julian date: ``2448266'' for any time on Wed Jan 9, 1991.
13576@item U
13577Unix time: ``663400800'' for 6:00am Wed Jan 9, 1991.
13578@item X
13579Brackets suppression. An ``X'' at the front of the format
13580causes the surrounding @w{@samp{< >}} delimiters to be omitted
13581when formatting dates. Note that the brackets are still
13582required for algebraic entry.
13583@end table
13584
13585If ``SS'' or ``BS'' (optional seconds) is preceded by a colon, the
13586colon is also omitted if the seconds part is zero.
13587
13588If ``bb,'' ``bbb'' or ``bbbb'' or their upper-case equivalents
13589appear in the format, then negative year numbers are displayed
13590without a minus sign. Note that ``aa'' and ``bb'' are mutually
13591exclusive. Some typical usages would be @samp{YYYY AABB};
13592@samp{AAAYYYYBBB}; @samp{YYYYBBB}.
13593
13594The formats ``YY,'' ``YYYY,'' ``MM,'' ``DD,'' ``ddd,'' ``hh,'' ``HH,''
13595``mm,'' ``ss,'' and ``SS'' actually match any number of digits during
13596reading unless several of these codes are strung together with no
13597punctuation in between, in which case the input must have exactly as
13598many digits as there are letters in the format.
13599
13600The ``j,'' ``J,'' and ``U'' formats do not make any time zone
13601adjustment. They effectively use @samp{julian(x,0)} and
13602@samp{unixtime(x,0)} to make the conversion; @pxref{Date Arithmetic}.
13603
13604@node Free-Form Dates, Standard Date Formats, Date Formatting Codes, Date Formats
13605@subsubsection Free-Form Dates
13606
13607@noindent
13608When reading a date form during algebraic entry, Calc falls back
13609on the algorithm described here if the input does not exactly
13610match the current date format. This algorithm generally
13611``does the right thing'' and you don't have to worry about it,
13612but it is described here in full detail for the curious.
13613
13614Calc does not distinguish between upper- and lower-case letters
13615while interpreting dates.
13616
13617First, the time portion, if present, is located somewhere in the
13618text and then removed. The remaining text is then interpreted as
13619the date.
13620
13621A time is of the form @samp{hh:mm:ss}, possibly with the seconds
13622part omitted and possibly with an AM/PM indicator added to indicate
1362312-hour time. If the AM/PM is present, the minutes may also be
13624omitted. The AM/PM part may be any of the words @samp{am},
13625@samp{pm}, @samp{noon}, or @samp{midnight}; each of these may be
13626abbreviated to one letter, and the alternate forms @samp{a.m.},
13627@samp{p.m.}, and @samp{mid} are also understood. Obviously
13628@samp{noon} and @samp{midnight} are allowed only on 12:00:00.
13629The words @samp{noon}, @samp{mid}, and @samp{midnight} are also
13630recognized with no number attached.
13631
13632If there is no AM/PM indicator, the time is interpreted in 24-hour
13633format.
13634
13635To read the date portion, all words and numbers are isolated
13636from the string; other characters are ignored. All words must
13637be either month names or day-of-week names (the latter of which
13638are ignored). Names can be written in full or as three-letter
13639abbreviations.
13640
13641Large numbers, or numbers with @samp{+} or @samp{-} signs,
13642are interpreted as years. If one of the other numbers is
13643greater than 12, then that must be the day and the remaining
13644number in the input is therefore the month. Otherwise, Calc
13645assumes the month, day and year are in the same order that they
13646appear in the current date format. If the year is omitted, the
13647current year is taken from the system clock.
13648
13649If there are too many or too few numbers, or any unrecognizable
13650words, then the input is rejected.
13651
13652If there are any large numbers (of five digits or more) other than
13653the year, they are ignored on the assumption that they are something
13654like Julian dates that were included along with the traditional
13655date components when the date was formatted.
13656
13657One of the words @samp{ad}, @samp{a.d.}, @samp{bc}, or @samp{b.c.}
13658may optionally be used; the latter two are equivalent to a
13659minus sign on the year value.
13660
13661If you always enter a four-digit year, and use a name instead
13662of a number for the month, there is no danger of ambiguity.
13663
13664@node Standard Date Formats, , Free-Form Dates, Date Formats
13665@subsubsection Standard Date Formats
13666
13667@noindent
13668There are actually ten standard date formats, numbered 0 through 9.
13669Entering a blank line at the @kbd{d d} command's prompt gives
13670you format number 1, Calc's usual format. You can enter any digit
13671to select the other formats.
13672
13673To create your own standard date formats, give a numeric prefix
13674argument from 0 to 9 to the @w{@kbd{d d}} command. The format you
13675enter will be recorded as the new standard format of that
13676number, as well as becoming the new current date format.
13677You can save your formats permanently with the @w{@kbd{m m}}
13678command (@pxref{Mode Settings}).
13679
13680@table @asis
13681@item 0
13682@samp{N} (Numerical format)
13683@item 1
13684@samp{<H:mm:SSpp >Www Mmm D, YYYY} (American format)
13685@item 2
13686@samp{D Mmm YYYY<, h:mm:SS>} (European format)
13687@item 3
13688@samp{Www Mmm BD< hh:mm:ss> YYYY} (Unix written date format)
13689@item 4
13690@samp{M/D/Y< H:mm:SSpp>} (American slashed format)
13691@item 5
13692@samp{D.M.Y< h:mm:SS>} (European dotted format)
13693@item 6
13694@samp{M-D-Y< H:mm:SSpp>} (American dashed format)
13695@item 7
13696@samp{D-M-Y< h:mm:SS>} (European dashed format)
13697@item 8
13698@samp{j<, h:mm:ss>} (Julian day plus time)
13699@item 9
13700@samp{YYddd< hh:mm:ss>} (Year-day format)
13701@end table
13702
13703@node Truncating the Stack, Justification, Date Formats, Display Modes
13704@subsection Truncating the Stack
13705
13706@noindent
13707@kindex d t
13708@pindex calc-truncate-stack
13709@cindex Truncating the stack
13710@cindex Narrowing the stack
13711The @kbd{d t} (@code{calc-truncate-stack}) command moves the @samp{.}@:
13712line that marks the top-of-stack up or down in the Calculator buffer.
13713The number right above that line is considered to the be at the top of
13714the stack. Any numbers below that line are ``hidden'' from all stack
13715operations (although still visible to the user). This is similar to the
13716Emacs ``narrowing'' feature, except that the values below the @samp{.}
13717are @emph{visible}, just temporarily frozen. This feature allows you to
13718keep several independent calculations running at once in different parts
13719of the stack, or to apply a certain command to an element buried deep in
13720the stack.
13721
13722Pressing @kbd{d t} by itself moves the @samp{.} to the line the cursor
13723is on. Thus, this line and all those below it become hidden. To un-hide
13724these lines, move down to the end of the buffer and press @w{@kbd{d t}}.
13725With a positive numeric prefix argument @expr{n}, @kbd{d t} hides the
13726bottom @expr{n} values in the buffer. With a negative argument, it hides
13727all but the top @expr{n} values. With an argument of zero, it hides zero
13728values, i.e., moves the @samp{.} all the way down to the bottom.
13729
13730@kindex d [
13731@pindex calc-truncate-up
13732@kindex d ]
13733@pindex calc-truncate-down
13734The @kbd{d [} (@code{calc-truncate-up}) and @kbd{d ]}
13735(@code{calc-truncate-down}) commands move the @samp{.} up or down one
13736line at a time (or several lines with a prefix argument).
13737
13738@node Justification, Labels, Truncating the Stack, Display Modes
13739@subsection Justification
13740
13741@noindent
13742@kindex d <
13743@pindex calc-left-justify
13744@kindex d =
13745@pindex calc-center-justify
13746@kindex d >
13747@pindex calc-right-justify
13748Values on the stack are normally left-justified in the window. You can
13749control this arrangement by typing @kbd{d <} (@code{calc-left-justify}),
13750@kbd{d >} (@code{calc-right-justify}), or @kbd{d =}
13751(@code{calc-center-justify}). For example, in Right-Justification mode,
13752stack entries are displayed flush-right against the right edge of the
13753window.
13754
13755If you change the width of the Calculator window you may have to type
13756@kbd{d @key{SPC}} (@code{calc-refresh}) to re-align right-justified or centered
13757text.
13758
13759Right-justification is especially useful together with fixed-point
13760notation (see @code{d f}; @code{calc-fix-notation}). With these modes
13761together, the decimal points on numbers will always line up.
13762
13763With a numeric prefix argument, the justification commands give you
13764a little extra control over the display. The argument specifies the
13765horizontal ``origin'' of a display line. It is also possible to
13766specify a maximum line width using the @kbd{d b} command (@pxref{Normal
13767Language Modes}). For reference, the precise rules for formatting and
13768breaking lines are given below. Notice that the interaction between
13769origin and line width is slightly different in each justification
13770mode.
13771
13772In Left-Justified mode, the line is indented by a number of spaces
13773given by the origin (default zero). If the result is longer than the
13774maximum line width, if given, or too wide to fit in the Calc window
13775otherwise, then it is broken into lines which will fit; each broken
13776line is indented to the origin.
13777
13778In Right-Justified mode, lines are shifted right so that the rightmost
13779character is just before the origin, or just before the current
13780window width if no origin was specified. If the line is too long
13781for this, then it is broken; the current line width is used, if
13782specified, or else the origin is used as a width if that is
13783specified, or else the line is broken to fit in the window.
13784
13785In Centering mode, the origin is the column number of the center of
13786each stack entry. If a line width is specified, lines will not be
13787allowed to go past that width; Calc will either indent less or
13788break the lines if necessary. If no origin is specified, half the
13789line width or Calc window width is used.
13790
13791Note that, in each case, if line numbering is enabled the display
13792is indented an additional four spaces to make room for the line
13793number. The width of the line number is taken into account when
13794positioning according to the current Calc window width, but not
13795when positioning by explicit origins and widths. In the latter
13796case, the display is formatted as specified, and then uniformly
13797shifted over four spaces to fit the line numbers.
13798
13799@node Labels, , Justification, Display Modes
13800@subsection Labels
13801
13802@noindent
13803@kindex d @{
13804@pindex calc-left-label
13805The @kbd{d @{} (@code{calc-left-label}) command prompts for a string,
13806then displays that string to the left of every stack entry. If the
13807entries are left-justified (@pxref{Justification}), then they will
13808appear immediately after the label (unless you specified an origin
13809greater than the length of the label). If the entries are centered
13810or right-justified, the label appears on the far left and does not
13811affect the horizontal position of the stack entry.
13812
13813Give a blank string (with @kbd{d @{ @key{RET}}) to turn the label off.
13814
13815@kindex d @}
13816@pindex calc-right-label
13817The @kbd{d @}} (@code{calc-right-label}) command similarly adds a
13818label on the righthand side. It does not affect positioning of
13819the stack entries unless they are right-justified. Also, if both
13820a line width and an origin are given in Right-Justified mode, the
13821stack entry is justified to the origin and the righthand label is
13822justified to the line width.
13823
13824One application of labels would be to add equation numbers to
13825formulas you are manipulating in Calc and then copying into a
13826document (possibly using Embedded mode). The equations would
13827typically be centered, and the equation numbers would be on the
13828left or right as you prefer.
13829
13830@node Language Modes, Modes Variable, Display Modes, Mode Settings
13831@section Language Modes
13832
13833@noindent
13834The commands in this section change Calc to use a different notation for
13835entry and display of formulas, corresponding to the conventions of some
c1dabff0 13836other common language such as Pascal or @LaTeX{}. Objects displayed on the
4009494e
GM
13837stack or yanked from the Calculator to an editing buffer will be formatted
13838in the current language; objects entered in algebraic entry or yanked from
13839another buffer will be interpreted according to the current language.
13840
13841The current language has no effect on things written to or read from the
13842trail buffer, nor does it affect numeric entry. Only algebraic entry is
13843affected. You can make even algebraic entry ignore the current language
13844and use the standard notation by giving a numeric prefix, e.g., @kbd{C-u '}.
13845
13846For example, suppose the formula @samp{2*a[1] + atan(a[2])} occurs in a C
13847program; elsewhere in the program you need the derivatives of this formula
13848with respect to @samp{a[1]} and @samp{a[2]}. First, type @kbd{d C}
13849to switch to C notation. Now use @code{C-u C-x * g} to grab the formula
13850into the Calculator, @kbd{a d a[1] @key{RET}} to differentiate with respect
13851to the first variable, and @kbd{C-x * y} to yank the formula for the derivative
13852back into your C program. Press @kbd{U} to undo the differentiation and
13853repeat with @kbd{a d a[2] @key{RET}} for the other derivative.
13854
13855Without being switched into C mode first, Calc would have misinterpreted
13856the brackets in @samp{a[1]} and @samp{a[2]}, would not have known that
13857@code{atan} was equivalent to Calc's built-in @code{arctan} function,
13858and would have written the formula back with notations (like implicit
13859multiplication) which would not have been valid for a C program.
13860
c1dabff0 13861As another example, suppose you are maintaining a C program and a @LaTeX{}
4009494e 13862document, each of which needs a copy of the same formula. You can grab the
c1dabff0
GM
13863formula from the program in C mode, switch to @LaTeX{} mode, and yank the
13864formula into the document in @LaTeX{} math-mode format.
4009494e
GM
13865
13866Language modes are selected by typing the letter @kbd{d} followed by a
13867shifted letter key.
13868
13869@menu
13870* Normal Language Modes::
13871* C FORTRAN Pascal::
13872* TeX and LaTeX Language Modes::
13873* Eqn Language Mode::
4e320733
JB
13874* Yacas Language Mode::
13875* Maxima Language Mode::
13876* Giac Language Mode::
4009494e
GM
13877* Mathematica Language Mode::
13878* Maple Language Mode::
13879* Compositions::
13880* Syntax Tables::
13881@end menu
13882
13883@node Normal Language Modes, C FORTRAN Pascal, Language Modes, Language Modes
13884@subsection Normal Language Modes
13885
13886@noindent
13887@kindex d N
13888@pindex calc-normal-language
13889The @kbd{d N} (@code{calc-normal-language}) command selects the usual
13890notation for Calc formulas, as described in the rest of this manual.
13891Matrices are displayed in a multi-line tabular format, but all other
13892objects are written in linear form, as they would be typed from the
13893keyboard.
13894
13895@kindex d O
13896@pindex calc-flat-language
13897@cindex Matrix display
13898The @kbd{d O} (@code{calc-flat-language}) command selects a language
13899identical with the normal one, except that matrices are written in
13900one-line form along with everything else. In some applications this
13901form may be more suitable for yanking data into other buffers.
13902
13903@kindex d b
13904@pindex calc-line-breaking
13905@cindex Line breaking
13906@cindex Breaking up long lines
13907Even in one-line mode, long formulas or vectors will still be split
13908across multiple lines if they exceed the width of the Calculator window.
13909The @kbd{d b} (@code{calc-line-breaking}) command turns this line-breaking
13910feature on and off. (It works independently of the current language.)
13911If you give a numeric prefix argument of five or greater to the @kbd{d b}
13912command, that argument will specify the line width used when breaking
13913long lines.
13914
13915@kindex d B
13916@pindex calc-big-language
13917The @kbd{d B} (@code{calc-big-language}) command selects a language
13918which uses textual approximations to various mathematical notations,
13919such as powers, quotients, and square roots:
13920
13921@example
13922 ____________
13923 | a + 1 2
13924 | ----- + c
13925\| b
13926@end example
13927
13928@noindent
13929in place of @samp{sqrt((a+1)/b + c^2)}.
13930
13931Subscripts like @samp{a_i} are displayed as actual subscripts in Big
13932mode. Double subscripts, @samp{a_i_j} (@samp{subscr(subscr(a, i), j)})
13933are displayed as @samp{a} with subscripts separated by commas:
13934@samp{i, j}. They must still be entered in the usual underscore
13935notation.
13936
13937One slight ambiguity of Big notation is that
13938
13939@example
13940 3
13941- -
13942 4
13943@end example
13944
13945@noindent
13946can represent either the negative rational number @expr{-3:4}, or the
13947actual expression @samp{-(3/4)}; but the latter formula would normally
13948never be displayed because it would immediately be evaluated to
13949@expr{-3:4} or @expr{-0.75}, so this ambiguity is not a problem in
13950typical use.
13951
13952Non-decimal numbers are displayed with subscripts. Thus there is no
13953way to tell the difference between @samp{16#C2} and @samp{C2_16},
13954though generally you will know which interpretation is correct.
13955Logarithms @samp{log(x,b)} and @samp{log10(x)} also use subscripts
13956in Big mode.
13957
13958In Big mode, stack entries often take up several lines. To aid
13959readability, stack entries are separated by a blank line in this mode.
13960You may find it useful to expand the Calc window's height using
13961@kbd{C-x ^} (@code{enlarge-window}) or to make the Calc window the only
13962one on the screen with @kbd{C-x 1} (@code{delete-other-windows}).
13963
13964Long lines are currently not rearranged to fit the window width in
13965Big mode, so you may need to use the @kbd{<} and @kbd{>} keys
13966to scroll across a wide formula. For really big formulas, you may
13967even need to use @kbd{@{} and @kbd{@}} to scroll up and down.
13968
13969@kindex d U
13970@pindex calc-unformatted-language
13971The @kbd{d U} (@code{calc-unformatted-language}) command altogether disables
13972the use of operator notation in formulas. In this mode, the formula
13973shown above would be displayed:
13974
13975@example
13976sqrt(add(div(add(a, 1), b), pow(c, 2)))
13977@end example
13978
13979These four modes differ only in display format, not in the format
13980expected for algebraic entry. The standard Calc operators work in
13981all four modes, and unformatted notation works in any language mode
13982(except that Mathematica mode expects square brackets instead of
13983parentheses).
13984
13985@node C FORTRAN Pascal, TeX and LaTeX Language Modes, Normal Language Modes, Language Modes
13986@subsection C, FORTRAN, and Pascal Modes
13987
13988@noindent
13989@kindex d C
13990@pindex calc-c-language
13991@cindex C language
13992The @kbd{d C} (@code{calc-c-language}) command selects the conventions
13993of the C language for display and entry of formulas. This differs from
13994the normal language mode in a variety of (mostly minor) ways. In
13995particular, C language operators and operator precedences are used in
13996place of Calc's usual ones. For example, @samp{a^b} means @samp{xor(a,b)}
13997in C mode; a value raised to a power is written as a function call,
13998@samp{pow(a,b)}.
13999
14000In C mode, vectors and matrices use curly braces instead of brackets.
14001Octal and hexadecimal values are written with leading @samp{0} or @samp{0x}
14002rather than using the @samp{#} symbol. Array subscripting is
14003translated into @code{subscr} calls, so that @samp{a[i]} in C
14004mode is the same as @samp{a_i} in Normal mode. Assignments
14005turn into the @code{assign} function, which Calc normally displays
14006using the @samp{:=} symbol.
14007
14008The variables @code{pi} and @code{e} would be displayed @samp{pi}
14009and @samp{e} in Normal mode, but in C mode they are displayed as
14010@samp{M_PI} and @samp{M_E}, corresponding to the names of constants
14011typically provided in the @file{<math.h>} header. Functions whose
14012names are different in C are translated automatically for entry and
14013display purposes. For example, entering @samp{asin(x)} will push the
14014formula @samp{arcsin(x)} onto the stack; this formula will be displayed
14015as @samp{asin(x)} as long as C mode is in effect.
14016
14017@kindex d P
14018@pindex calc-pascal-language
14019@cindex Pascal language
14020The @kbd{d P} (@code{calc-pascal-language}) command selects Pascal
14021conventions. Like C mode, Pascal mode interprets array brackets and uses
14022a different table of operators. Hexadecimal numbers are entered and
14023displayed with a preceding dollar sign. (Thus the regular meaning of
14024@kbd{$2} during algebraic entry does not work in Pascal mode, though
14025@kbd{$} (and @kbd{$$}, etc.) not followed by digits works the same as
14026always.) No special provisions are made for other non-decimal numbers,
14027vectors, and so on, since there is no universally accepted standard way
14028of handling these in Pascal.
14029
14030@kindex d F
14031@pindex calc-fortran-language
14032@cindex FORTRAN language
14033The @kbd{d F} (@code{calc-fortran-language}) command selects FORTRAN
14034conventions. Various function names are transformed into FORTRAN
14035equivalents. Vectors are written as @samp{/1, 2, 3/}, and may be
14036entered this way or using square brackets. Since FORTRAN uses round
14037parentheses for both function calls and array subscripts, Calc displays
14038both in the same way; @samp{a(i)} is interpreted as a function call
14039upon reading, and subscripts must be entered as @samp{subscr(a, i)}.
702dbfd9
JB
14040If the variable @code{a} has been declared to have type
14041@code{vector} or @code{matrix}, however, then @samp{a(i)} will be
14042parsed as a subscript. (@xref{Declarations}.) Usually it doesn't
14043matter, though; if you enter the subscript expression @samp{a(i)} and
14044Calc interprets it as a function call, you'll never know the difference
14045unless you switch to another language mode or replace @code{a} with an
14046actual vector (or unless @code{a} happens to be the name of a built-in
4009494e
GM
14047function!).
14048
14049Underscores are allowed in variable and function names in all of these
14050language modes. The underscore here is equivalent to the @samp{#} in
14051Normal mode, or to hyphens in the underlying Emacs Lisp variable names.
14052
14053FORTRAN and Pascal modes normally do not adjust the case of letters in
14054formulas. Most built-in Calc names use lower-case letters. If you use a
14055positive numeric prefix argument with @kbd{d P} or @kbd{d F}, these
14056modes will use upper-case letters exclusively for display, and will
14057convert to lower-case on input. With a negative prefix, these modes
14058convert to lower-case for display and input.
14059
14060@node TeX and LaTeX Language Modes, Eqn Language Mode, C FORTRAN Pascal, Language Modes
c1dabff0 14061@subsection @TeX{} and @LaTeX{} Language Modes
4009494e
GM
14062
14063@noindent
14064@kindex d T
14065@pindex calc-tex-language
14066@cindex TeX language
14067@kindex d L
14068@pindex calc-latex-language
14069@cindex LaTeX language
14070The @kbd{d T} (@code{calc-tex-language}) command selects the conventions
14071of ``math mode'' in Donald Knuth's @TeX{} typesetting language,
14072and the @kbd{d L} (@code{calc-latex-language}) command selects the
c1dabff0
GM
14073conventions of ``math mode'' in @LaTeX{}, a typesetting language that
14074uses @TeX{} as its formatting engine. Calc's @LaTeX{} language mode can
14075read any formula that the @TeX{} language mode can, although @LaTeX{}
4009494e
GM
14076mode may display it differently.
14077
14078Formulas are entered and displayed in the appropriate notation;
14079@texline @math{\sin(a/b)}
14080@infoline @expr{sin(a/b)}
0cbe9c78 14081will appear as @samp{\sin\left( @{a \over b@} \right)} in @TeX{} mode and
c1dabff0 14082@samp{\sin\left(\frac@{a@}@{b@}\right)} in @LaTeX{} mode.
4009494e 14083Math formulas are often enclosed by @samp{$ $} signs in @TeX{} and
c1dabff0 14084@LaTeX{}; these should be omitted when interfacing with Calc. To Calc,
4009494e
GM
14085the @samp{$} sign has the same meaning it always does in algebraic
14086formulas (a reference to an existing entry on the stack).
14087
14088Complex numbers are displayed as in @samp{3 + 4i}. Fractions and
40ba43b4 14089quotients are written using @code{\over} in @TeX{} mode (as in
c1dabff0 14090@code{@{a \over b@}}) and @code{\frac} in @LaTeX{} mode (as in
4009494e
GM
14091@code{\frac@{a@}@{b@}}); binomial coefficients are written with
14092@code{\choose} in @TeX{} mode (as in @code{@{a \choose b@}}) and
c1dabff0 14093@code{\binom} in @LaTeX{} mode (as in @code{\binom@{a@}@{b@}}).
4009494e 14094Interval forms are written with @code{\ldots}, and error forms are
40ba43b4 14095written with @code{\pm}. Absolute values are written as in
4009494e
GM
14096@samp{|x + 1|}, and the floor and ceiling functions are written with
14097@code{\lfloor}, @code{\rfloor}, etc. The words @code{\left} and
c1dabff0 14098@code{\right} are ignored when reading formulas in @TeX{} and @LaTeX{}
4009494e
GM
14099modes. Both @code{inf} and @code{uinf} are written as @code{\infty};
14100when read, @code{\infty} always translates to @code{inf}.
14101
14102Function calls are written the usual way, with the function name followed
14103by the arguments in parentheses. However, functions for which @TeX{}
c1dabff0 14104and @LaTeX{} have special names (like @code{\sin}) will use curly braces
4009494e
GM
14105instead of parentheses for very simple arguments. During input, curly
14106braces and parentheses work equally well for grouping, but when the
14107document is formatted the curly braces will be invisible. Thus the
40ba43b4 14108printed result is
4009494e 14109@texline @math{\sin{2 x}}
40ba43b4
PE
14110@infoline @expr{sin 2x}
14111but
4009494e
GM
14112@texline @math{\sin(2 + x)}.
14113@infoline @expr{sin(2 + x)}.
14114
1265829e
JB
14115The @TeX{} specific unit names (@pxref{Predefined Units}) will not use
14116the @samp{tex} prefix; the unit name for a @TeX{} point will be
14117@samp{pt} instead of @samp{texpt}, for example.
14118
c1dabff0 14119Function and variable names not treated specially by @TeX{} and @LaTeX{}
4009494e
GM
14120are simply written out as-is, which will cause them to come out in
14121italic letters in the printed document. If you invoke @kbd{d T} or
14122@kbd{d L} with a positive numeric prefix argument, names of more than
14123one character will instead be enclosed in a protective commands that
14124will prevent them from being typeset in the math italics; they will be
40ba43b4 14125written @samp{\hbox@{@var{name}@}} in @TeX{} mode and
c1dabff0 14126@samp{\text@{@var{name}@}} in @LaTeX{} mode. The
4009494e
GM
14127@samp{\hbox@{ @}} and @samp{\text@{ @}} notations are ignored during
14128reading. If you use a negative prefix argument, such function names are
14129written @samp{\@var{name}}, and function names that begin with @code{\} during
14130reading have the @code{\} removed. (Note that in this mode, long
14131variable names are still written with @code{\hbox} or @code{\text}.
14132However, you can always make an actual variable name like @code{\bar} in
14133any @TeX{} mode.)
14134
14135During reading, text of the form @samp{\matrix@{ ...@: @}} is replaced
14136by @samp{[ ...@: ]}. The same also applies to @code{\pmatrix} and
c1dabff0 14137@code{\bmatrix}. In @LaTeX{} mode this also applies to
4009494e
GM
14138@samp{\begin@{matrix@} ... \end@{matrix@}},
14139@samp{\begin@{bmatrix@} ... \end@{bmatrix@}},
14140@samp{\begin@{pmatrix@} ... \end@{pmatrix@}}, as well as
14141@samp{\begin@{smallmatrix@} ... \end@{smallmatrix@}}.
14142The symbol @samp{&} is interpreted as a comma,
14143and the symbols @samp{\cr} and @samp{\\} are interpreted as semicolons.
14144During output, matrices are displayed in @samp{\matrix@{ a & b \\ c & d@}}
40ba43b4 14145format in @TeX{} mode and in
4009494e 14146@samp{\begin@{pmatrix@} a & b \\ c & d \end@{pmatrix@}} format in
c1dabff0 14147@LaTeX{} mode; you may need to edit this afterwards to change to your
4009494e
GM
14148preferred matrix form. If you invoke @kbd{d T} or @kbd{d L} with an
14149argument of 2 or -2, then matrices will be displayed in two-dimensional
40ba43b4 14150form, such as
4009494e
GM
14151
14152@example
14153\begin@{pmatrix@}
14154a & b \\
14155c & d
14156\end@{pmatrix@}
14157@end example
14158
14159@noindent
14160This may be convenient for isolated matrices, but could lead to
14161expressions being displayed like
14162
14163@example
14164\begin@{pmatrix@} \times x
14165a & b \\
14166c & d
14167\end@{pmatrix@}
14168@end example
14169
14170@noindent
c1dabff0 14171While this wouldn't bother Calc, it is incorrect @LaTeX{}.
4009494e
GM
14172(Similarly for @TeX{}.)
14173
14174Accents like @code{\tilde} and @code{\bar} translate into function
14175calls internally (@samp{tilde(x)}, @samp{bar(x)}). The @code{\underline}
14176sequence is treated as an accent. The @code{\vec} accent corresponds
14177to the function name @code{Vec}, because @code{vec} is the name of
14178a built-in Calc function. The following table shows the accents
c1dabff0 14179in Calc, @TeX{}, @LaTeX{} and @dfn{eqn} (described in the next section):
4009494e 14180
17587b1b 14181@ignore
4009494e
GM
14182@iftex
14183@begingroup
14184@let@calcindexershow=@calcindexernoshow @c Suppress marginal notes
14185@let@calcindexersh=@calcindexernoshow
14186@end iftex
4009494e
GM
14187@starindex
14188@end ignore
14189@tindex acute
14190@ignore
14191@starindex
14192@end ignore
14193@tindex Acute
14194@ignore
14195@starindex
14196@end ignore
14197@tindex bar
14198@ignore
14199@starindex
14200@end ignore
14201@tindex Bar
14202@ignore
14203@starindex
14204@end ignore
14205@tindex breve
14206@ignore
14207@starindex
14208@end ignore
14209@tindex Breve
14210@ignore
14211@starindex
14212@end ignore
14213@tindex check
14214@ignore
14215@starindex
14216@end ignore
14217@tindex Check
14218@ignore
14219@starindex
14220@end ignore
14221@tindex dddot
14222@ignore
14223@starindex
14224@end ignore
14225@tindex ddddot
14226@ignore
14227@starindex
14228@end ignore
14229@tindex dot
14230@ignore
14231@starindex
14232@end ignore
14233@tindex Dot
14234@ignore
14235@starindex
14236@end ignore
14237@tindex dotdot
14238@ignore
14239@starindex
14240@end ignore
14241@tindex DotDot
14242@ignore
14243@starindex
14244@end ignore
14245@tindex dyad
14246@ignore
14247@starindex
14248@end ignore
14249@tindex grave
14250@ignore
14251@starindex
14252@end ignore
14253@tindex Grave
14254@ignore
14255@starindex
14256@end ignore
14257@tindex hat
14258@ignore
14259@starindex
14260@end ignore
14261@tindex Hat
14262@ignore
14263@starindex
14264@end ignore
14265@tindex Prime
14266@ignore
14267@starindex
14268@end ignore
14269@tindex tilde
14270@ignore
14271@starindex
14272@end ignore
14273@tindex Tilde
14274@ignore
14275@starindex
14276@end ignore
14277@tindex under
14278@ignore
14279@starindex
14280@end ignore
14281@tindex Vec
14282@ignore
14283@starindex
14284@end ignore
14285@tindex VEC
17587b1b 14286@ignore
4009494e
GM
14287@iftex
14288@endgroup
14289@end iftex
17587b1b 14290@end ignore
4009494e
GM
14291@example
14292Calc TeX LaTeX eqn
14293---- --- ----- ---
40ba43b4
PE
14294acute \acute \acute
14295Acute \Acute
4009494e
GM
14296bar \bar \bar bar
14297Bar \Bar
40ba43b4
PE
14298breve \breve \breve
14299Breve \Breve
14300check \check \check
14301Check \Check
4009494e
GM
14302dddot \dddot
14303ddddot \ddddot
14304dot \dot \dot dot
14305Dot \Dot
14306dotdot \ddot \ddot dotdot
40ba43b4 14307DotDot \Ddot
4009494e 14308dyad dyad
40ba43b4
PE
14309grave \grave \grave
14310Grave \Grave
4009494e 14311hat \hat \hat hat
40ba43b4 14312Hat \Hat
4009494e
GM
14313Prime prime
14314tilde \tilde \tilde tilde
14315Tilde \Tilde
14316under \underline \underline under
14317Vec \vec \vec vec
14318VEC \Vec
14319@end example
14320
14321The @samp{=>} (evaluates-to) operator appears as a @code{\to} symbol:
14322@samp{@{@var{a} \to @var{b}@}}. @TeX{} defines @code{\to} as an
14323alias for @code{\rightarrow}. However, if the @samp{=>} is the
14324top-level expression being formatted, a slightly different notation
14325is used: @samp{\evalto @var{a} \to @var{b}}. The @code{\evalto}
14326word is ignored by Calc's input routines, and is undefined in @TeX{}.
14327You will typically want to include one of the following definitions
14328at the top of a @TeX{} file that uses @code{\evalto}:
14329
14330@example
14331\def\evalto@{@}
14332\def\evalto#1\to@{@}
14333@end example
14334
14335The first definition formats evaluates-to operators in the usual
14336way. The second causes only the @var{b} part to appear in the
14337printed document; the @var{a} part and the arrow are hidden.
14338Another definition you may wish to use is @samp{\let\to=\Rightarrow}
14339which causes @code{\to} to appear more like Calc's @samp{=>} symbol.
14340@xref{Evaluates-To Operator}, for a discussion of @code{evalto}.
14341
14342The complete set of @TeX{} control sequences that are ignored during
14343reading is:
14344
14345@example
14346\hbox \mbox \text \left \right
14347\, \> \: \; \! \quad \qquad \hfil \hfill
14348\displaystyle \textstyle \dsize \tsize
14349\scriptstyle \scriptscriptstyle \ssize \ssize
14350\rm \bf \it \sl \roman \bold \italic \slanted
14351\cal \mit \Cal \Bbb \frak \goth
14352\evalto
14353@end example
14354
14355Note that, because these symbols are ignored, reading a @TeX{} or
c1dabff0 14356@LaTeX{} formula into Calc and writing it back out may lose spacing and
40ba43b4 14357font information.
4009494e
GM
14358
14359Also, the ``discretionary multiplication sign'' @samp{\*} is read
14360the same as @samp{*}.
14361
14362@ifnottex
14363The @TeX{} version of this manual includes some printed examples at the
14364end of this section.
14365@end ifnottex
14366@iftex
14367Here are some examples of how various Calc formulas are formatted in @TeX{}:
14368
14369@example
14370@group
14371sin(a^2 / b_i)
14372\sin\left( {a^2 \over b_i} \right)
14373@end group
14374@end example
14375@tex
14376$$ \sin\left( a^2 \over b_i \right) $$
14377@end tex
14378@sp 1
14379
14380@example
14381@group
14382[(3, 4), 3:4, 3 +/- 4, [3 .. inf)]
14383[3 + 4i, @{3 \over 4@}, 3 \pm 4, [3 \ldots \infty)]
14384@end group
14385@end example
14386@tex
4009494e
GM
14387$$ [3 + 4i, {3 \over 4}, 3 \pm 4, [ 3 \ldots \infty)] $$
14388@end tex
14389@sp 1
14390
14391@example
14392@group
14393[abs(a), abs(a / b), floor(a), ceil(a / b)]
14394[|a|, \left| a \over b \right|,
14395 \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
14396@end group
14397@end example
14398@tex
14399$$ [|a|, \left| a \over b \right|,
14400 \lfloor a \rfloor, \left\lceil a \over b \right\rceil] $$
14401@end tex
14402@sp 1
14403
14404@example
14405@group
14406[sin(a), sin(2 a), sin(2 + a), sin(a / b)]
14407[\sin@{a@}, \sin@{2 a@}, \sin(2 + a),
14408 \sin\left( @{a \over b@} \right)]
14409@end group
14410@end example
14411@tex
4009494e
GM
14412$$ [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)] $$
14413@end tex
14414@sp 2
14415
14416First with plain @kbd{d T}, then with @kbd{C-u d T}, then finally with
14417@kbd{C-u - d T} (using the example definition
14418@samp{\def\foo#1@{\tilde F(#1)@}}:
14419
14420@example
14421@group
14422[f(a), foo(bar), sin(pi)]
14423[f(a), foo(bar), \sin{\pi}]
14424[f(a), \hbox@{foo@}(\hbox@{bar@}), \sin@{\pi@}]
14425[f(a), \foo@{\hbox@{bar@}@}, \sin@{\pi@}]
14426@end group
14427@end example
14428@tex
14429$$ [f(a), foo(bar), \sin{\pi}] $$
14430$$ [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] $$
14431$$ [f(a), \tilde F(\hbox{bar}), \sin{\pi}] $$
14432@end tex
14433@sp 2
14434
14435First with @samp{\def\evalto@{@}}, then with @samp{\def\evalto#1\to@{@}}:
14436
14437@example
14438@group
144392 + 3 => 5
14440\evalto 2 + 3 \to 5
14441@end group
14442@end example
14443@tex
4009494e
GM
14444$$ 2 + 3 \to 5 $$
14445$$ 5 $$
14446@end tex
14447@sp 2
14448
14449First with standard @code{\to}, then with @samp{\let\to\Rightarrow}:
14450
14451@example
14452@group
14453[2 + 3 => 5, a / 2 => (b + c) / 2]
14454[@{2 + 3 \to 5@}, @{@{a \over 2@} \to @{b + c \over 2@}@}]
14455@end group
14456@end example
14457@tex
4009494e
GM
14458$$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$
14459{\let\to\Rightarrow
14460$$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$}
14461@end tex
14462@sp 2
14463
14464Matrices normally, then changing @code{\matrix} to @code{\pmatrix}:
14465
14466@example
14467@group
14468[ [ a / b, 0 ], [ 0, 2^(x + 1) ] ]
14469\matrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14470\pmatrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14471@end group
14472@end example
14473@tex
4009494e
GM
14474$$ \matrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14475$$ \pmatrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14476@end tex
14477@sp 2
14478@end iftex
14479
702dbfd9 14480@node Eqn Language Mode, Yacas Language Mode, TeX and LaTeX Language Modes, Language Modes
4009494e
GM
14481@subsection Eqn Language Mode
14482
14483@noindent
14484@kindex d E
14485@pindex calc-eqn-language
14486@dfn{Eqn} is another popular formatter for math formulas. It is
14487designed for use with the TROFF text formatter, and comes standard
14488with many versions of Unix. The @kbd{d E} (@code{calc-eqn-language})
14489command selects @dfn{eqn} notation.
14490
14491The @dfn{eqn} language's main idiosyncrasy is that whitespace plays
14492a significant part in the parsing of the language. For example,
14493@samp{sqrt x+1 + y} treats @samp{x+1} as the argument of the
14494@code{sqrt} operator. @dfn{Eqn} also understands more conventional
14495grouping using curly braces: @samp{sqrt@{x+1@} + y}. Braces are
14496required only when the argument contains spaces.
14497
14498In Calc's @dfn{eqn} mode, however, curly braces are required to
14499delimit arguments of operators like @code{sqrt}. The first of the
14500above examples would treat only the @samp{x} as the argument of
14501@code{sqrt}, and in fact @samp{sin x+1} would be interpreted as
14502@samp{sin * x + 1}, because @code{sin} is not a special operator
14503in the @dfn{eqn} language. If you always surround the argument
14504with curly braces, Calc will never misunderstand.
14505
14506Calc also understands parentheses as grouping characters. Another
14507peculiarity of @dfn{eqn}'s syntax makes it advisable to separate
14508words with spaces from any surrounding characters that aren't curly
14509braces, so Calc writes @samp{sin ( x + y )} in @dfn{eqn} mode.
14510(The spaces around @code{sin} are important to make @dfn{eqn}
14511recognize that @code{sin} should be typeset in a roman font, and
14512the spaces around @code{x} and @code{y} are a good idea just in
14513case the @dfn{eqn} document has defined special meanings for these
14514names, too.)
14515
14516Powers and subscripts are written with the @code{sub} and @code{sup}
14517operators, respectively. Note that the caret symbol @samp{^} is
14518treated the same as a space in @dfn{eqn} mode, as is the @samp{~}
14519symbol (these are used to introduce spaces of various widths into
14520the typeset output of @dfn{eqn}).
14521
c1dabff0 14522As in @LaTeX{} mode, Calc's formatter omits parentheses around the
4009494e
GM
14523arguments of functions like @code{ln} and @code{sin} if they are
14524``simple-looking''; in this case Calc surrounds the argument with
14525braces, separated by a @samp{~} from the function name: @samp{sin~@{x@}}.
14526
14527Font change codes (like @samp{roman @var{x}}) and positioning codes
14528(like @samp{~} and @samp{down @var{n} @var{x}}) are ignored by the
14529@dfn{eqn} reader. Also ignored are the words @code{left}, @code{right},
14530@code{mark}, and @code{lineup}. Quotation marks in @dfn{eqn} mode input
14531are treated the same as curly braces: @samp{sqrt "1+x"} is equivalent to
14532@samp{sqrt @{1+x@}}; this is only an approximation to the true meaning
14533of quotes in @dfn{eqn}, but it is good enough for most uses.
14534
14535Accent codes (@samp{@var{x} dot}) are handled by treating them as
40ba43b4 14536function calls (@samp{dot(@var{x})}) internally.
4009494e
GM
14537@xref{TeX and LaTeX Language Modes}, for a table of these accent
14538functions. The @code{prime} accent is treated specially if it occurs on
14539a variable or function name: @samp{f prime prime @w{( x prime )}} is
14540stored internally as @samp{f'@w{'}(x')}. For example, taking the
14541derivative of @samp{f(2 x)} with @kbd{a d x} will produce @samp{2 f'(2
14542x)}, which @dfn{eqn} mode will display as @samp{2 f prime ( 2 x )}.
14543
14544Assignments are written with the @samp{<-} (left-arrow) symbol,
14545and @code{evalto} operators are written with @samp{->} or
14546@samp{evalto ... ->} (@pxref{TeX and LaTeX Language Modes}, for a discussion
14547of this). The regular Calc symbols @samp{:=} and @samp{=>} are also
14548recognized for these operators during reading.
14549
14550Vectors in @dfn{eqn} mode use regular Calc square brackets, but
14551matrices are formatted as @samp{matrix @{ ccol @{ a above b @} ... @}}.
14552The words @code{lcol} and @code{rcol} are recognized as synonyms
14553for @code{ccol} during input, and are generated instead of @code{ccol}
14554if the matrix justification mode so specifies.
14555
702dbfd9
JB
14556@node Yacas Language Mode, Maxima Language Mode, Eqn Language Mode, Language Modes
14557@subsection Yacas Language Mode
14558
14559@noindent
14560@kindex d Y
14561@pindex calc-yacas-language
14562@cindex Yacas language
14563The @kbd{d Y} (@code{calc-yacas-language}) command selects the
14564conventions of Yacas, a free computer algebra system. While the
14565operators and functions in Yacas are similar to those of Calc, the names
40ba43b4 14566of built-in functions in Yacas are capitalized. The Calc formula
702dbfd9
JB
14567@samp{sin(2 x)}, for example, is entered and displayed @samp{Sin(2 x)}
14568in Yacas mode, and `@samp{arcsin(x^2)} is @samp{ArcSin(x^2)} in Yacas
14569mode. Complex numbers are written are written @samp{3 + 4 I}.
14570The standard special constants are written @code{Pi}, @code{E},
14571@code{I}, @code{GoldenRatio} and @code{Gamma}. @code{Infinity}
14572represents both @code{inf} and @code{uinf}, and @code{Undefined}
14573represents @code{nan}.
14574
40ba43b4 14575Certain operators on functions, such as @code{D} for differentiation
702dbfd9 14576and @code{Integrate} for integration, take a prefix form in Yacas. For
40ba43b4 14577example, the derivative of @w{@samp{e^x sin(x)}} can be computed with
702dbfd9
JB
14578@w{@samp{D(x) Exp(x)*Sin(x)}}.
14579
14580Other notable differences between Yacas and standard Calc expressions
14581are that vectors and matrices use curly braces in Yacas, and subscripts
14582use square brackets. If, for example, @samp{A} represents the list
14583@samp{@{a,2,c,4@}}, then @samp{A[3]} would equal @samp{c}.
14584
14585
14586@node Maxima Language Mode, Giac Language Mode, Yacas Language Mode, Language Modes
14587@subsection Maxima Language Mode
14588
14589@noindent
14590@kindex d X
14591@pindex calc-maxima-language
14592@cindex Maxima language
14593The @kbd{d X} (@code{calc-maxima-language}) command selects the
14594conventions of Maxima, another free computer algebra system. The
14595function names in Maxima are similar, but not always identical, to Calc.
40ba43b4 14596For example, instead of @samp{arcsin(x)}, Maxima will use
702dbfd9
JB
14597@samp{asin(x)}. Complex numbers are written @samp{3 + 4 %i}. The
14598standard special constants are written @code{%pi}, @code{%e},
14599@code{%i}, @code{%phi} and @code{%gamma}. In Maxima, @code{inf} means
14600the same as in Calc, but @code{infinity} represents Calc's @code{uinf}.
14601
14602Underscores as well as percent signs are allowed in function and
14603variable names in Maxima mode. The underscore again is equivalent to
40ba43b4
PE
14604the @samp{#} in Normal mode, and the percent sign is equivalent to
14605@samp{o'o}.
702dbfd9
JB
14606
14607Maxima uses square brackets for lists and vectors, and matrices are
14608written as calls to the function @code{matrix}, given the row vectors of
14609the matrix as arguments. Square brackets are also used as subscripts.
14610
14611@node Giac Language Mode, Mathematica Language Mode, Maxima Language Mode, Language Modes
14612@subsection Giac Language Mode
14613
14614@noindent
14615@kindex d A
14616@pindex calc-giac-language
14617@cindex Giac language
14618The @kbd{d A} (@code{calc-giac-language}) command selects the
14619conventions of Giac, another free computer algebra system. The function
14620names in Giac are similar to Maxima. Complex numbers are written
14621@samp{3 + 4 i}. The standard special constants in Giac are the same as
14622in Calc, except that @code{infinity} represents both Calc's @code{inf}
40ba43b4 14623and @code{uinf}.
702dbfd9
JB
14624
14625Underscores are allowed in function and variable names in Giac mode.
14626Brackets are used for subscripts. In Giac, indexing of lists begins at
146270, instead of 1 as in Calc. So if @samp{A} represents the list
14628@samp{[a,2,c,4]}, then @samp{A[2]} would equal @samp{c}. In general,
14629@samp{A[n]} in Giac mode corresponds to @samp{A_(n+1)} in Normal mode.
14630
14631The Giac interval notation @samp{2 .. 3} has no surrounding brackets;
14632Calc reads @samp{2 .. 3} as the closed interval @samp{[2 .. 3]} and
14633writes any kind of interval as @samp{2 .. 3}. This means you cannot see
14634the difference between an open and a closed interval while in Giac mode.
14635
14636@node Mathematica Language Mode, Maple Language Mode, Giac Language Mode, Language Modes
4009494e
GM
14637@subsection Mathematica Language Mode
14638
14639@noindent
14640@kindex d M
14641@pindex calc-mathematica-language
14642@cindex Mathematica language
14643The @kbd{d M} (@code{calc-mathematica-language}) command selects the
14644conventions of Mathematica. Notable differences in Mathematica mode
14645are that the names of built-in functions are capitalized, and function
14646calls use square brackets instead of parentheses. Thus the Calc
14647formula @samp{sin(2 x)} is entered and displayed @w{@samp{Sin[2 x]}} in
14648Mathematica mode.
14649
14650Vectors and matrices use curly braces in Mathematica. Complex numbers
14651are written @samp{3 + 4 I}. The standard special constants in Calc are
14652written @code{Pi}, @code{E}, @code{I}, @code{GoldenRatio}, @code{EulerGamma},
14653@code{Infinity}, @code{ComplexInfinity}, and @code{Indeterminate} in
14654Mathematica mode.
14655Non-decimal numbers are written, e.g., @samp{16^^7fff}. Floating-point
14656numbers in scientific notation are written @samp{1.23*10.^3}.
14657Subscripts use double square brackets: @samp{a[[i]]}.
14658
14659@node Maple Language Mode, Compositions, Mathematica Language Mode, Language Modes
14660@subsection Maple Language Mode
14661
14662@noindent
14663@kindex d W
14664@pindex calc-maple-language
14665@cindex Maple language
14666The @kbd{d W} (@code{calc-maple-language}) command selects the
14667conventions of Maple.
14668
14669Maple's language is much like C. Underscores are allowed in symbol
14670names; square brackets are used for subscripts; explicit @samp{*}s for
14671multiplications are required. Use either @samp{^} or @samp{**} to
14672denote powers.
14673
14674Maple uses square brackets for lists and curly braces for sets. Calc
14675interprets both notations as vectors, and displays vectors with square
14676brackets. This means Maple sets will be converted to lists when they
14677pass through Calc. As a special case, matrices are written as calls
14678to the function @code{matrix}, given a list of lists as the argument,
14679and can be read in this form or with all-capitals @code{MATRIX}.
14680
702dbfd9
JB
14681The Maple interval notation @samp{2 .. 3} is like Giac's interval
14682notation, and is handled the same by Calc.
4009494e
GM
14683
14684Maple writes complex numbers as @samp{3 + 4*I}. Its special constants
14685are @code{Pi}, @code{E}, @code{I}, and @code{infinity} (all three of
14686@code{inf}, @code{uinf}, and @code{nan} display as @code{infinity}).
14687Floating-point numbers are written @samp{1.23*10.^3}.
14688
14689Among things not currently handled by Calc's Maple mode are the
14690various quote symbols, procedures and functional operators, and
14691inert (@samp{&}) operators.
14692
14693@node Compositions, Syntax Tables, Maple Language Mode, Language Modes
14694@subsection Compositions
14695
14696@noindent
14697@cindex Compositions
14698There are several @dfn{composition functions} which allow you to get
14699displays in a variety of formats similar to those in Big language
14700mode. Most of these functions do not evaluate to anything; they are
14701placeholders which are left in symbolic form by Calc's evaluator but
14702are recognized by Calc's display formatting routines.
14703
14704Two of these, @code{string} and @code{bstring}, are described elsewhere.
14705@xref{Strings}. For example, @samp{string("ABC")} is displayed as
14706@samp{ABC}. When viewed on the stack it will be indistinguishable from
14707the variable @code{ABC}, but internally it will be stored as
14708@samp{string([65, 66, 67])} and can still be manipulated this way; for
14709example, the selection and vector commands @kbd{j 1 v v j u} would
14710select the vector portion of this object and reverse the elements, then
14711deselect to reveal a string whose characters had been reversed.
14712
14713The composition functions do the same thing in all language modes
14714(although their components will of course be formatted in the current
14715language mode). The one exception is Unformatted mode (@kbd{d U}),
14716which does not give the composition functions any special treatment.
14717The functions are discussed here because of their relationship to
14718the language modes.
14719
14720@menu
14721* Composition Basics::
14722* Horizontal Compositions::
14723* Vertical Compositions::
14724* Other Compositions::
14725* Information about Compositions::
14726* User-Defined Compositions::
14727@end menu
14728
14729@node Composition Basics, Horizontal Compositions, Compositions, Compositions
14730@subsubsection Composition Basics
14731
14732@noindent
14733Compositions are generally formed by stacking formulas together
14734horizontally or vertically in various ways. Those formulas are
14735themselves compositions. @TeX{} users will find this analogous
14736to @TeX{}'s ``boxes.'' Each multi-line composition has a
14737@dfn{baseline}; horizontal compositions use the baselines to
14738decide how formulas should be positioned relative to one another.
14739For example, in the Big mode formula
14740
14741@example
14742@group
14743 2
14744 a + b
1474517 + ------
14746 c
14747@end group
14748@end example
14749
14750@noindent
14751the second term of the sum is four lines tall and has line three as
14752its baseline. Thus when the term is combined with 17, line three
14753is placed on the same level as the baseline of 17.
14754
14755@tex
14756\bigskip
14757@end tex
14758
14759Another important composition concept is @dfn{precedence}. This is
14760an integer that represents the binding strength of various operators.
14761For example, @samp{*} has higher precedence (195) than @samp{+} (180),
14762which means that @samp{(a * b) + c} will be formatted without the
14763parentheses, but @samp{a * (b + c)} will keep the parentheses.
14764
14765The operator table used by normal and Big language modes has the
14766following precedences:
14767
14768@example
0edd2970
JB
14769_ 1200 @r{(subscripts)}
14770% 1100 @r{(as in n}%@r{)}
14771! 1000 @r{(as in }!@r{n)}
4009494e
GM
14772mod 400
14773+/- 300
14774!! 210 @r{(as in n}!!@r{)}
14775! 210 @r{(as in n}!@r{)}
14776^ 200
0edd2970 14777- 197 @r{(as in }-@r{n)}
4009494e
GM
14778* 195 @r{(or implicit multiplication)}
14779/ % \ 190
14780+ - 180 @r{(as in a}+@r{b)}
14781| 170
14782< = 160 @r{(and other relations)}
14783&& 110
14784|| 100
14785? : 90
14786!!! 85
14787&&& 80
14788||| 75
14789:= 50
14790:: 45
14791=> 40
14792@end example
14793
14794The general rule is that if an operator with precedence @expr{n}
14795occurs as an argument to an operator with precedence @expr{m}, then
14796the argument is enclosed in parentheses if @expr{n < m}. Top-level
14797expressions and expressions which are function arguments, vector
14798components, etc., are formatted with precedence zero (so that they
14799normally never get additional parentheses).
14800
14801For binary left-associative operators like @samp{+}, the righthand
14802argument is actually formatted with one-higher precedence than shown
14803in the table. This makes sure @samp{(a + b) + c} omits the parentheses,
14804but the unnatural form @samp{a + (b + c)} keeps its parentheses.
14805Right-associative operators like @samp{^} format the lefthand argument
14806with one-higher precedence.
14807
14808@ignore
14809@starindex
14810@end ignore
14811@tindex cprec
14812The @code{cprec} function formats an expression with an arbitrary
14813precedence. For example, @samp{cprec(abc, 185)} will combine into
14814sums and products as follows: @samp{7 + abc}, @samp{7 (abc)} (because
14815this @code{cprec} form has higher precedence than addition, but lower
14816precedence than multiplication).
14817
14818@tex
14819\bigskip
14820@end tex
14821
14822A final composition issue is @dfn{line breaking}. Calc uses two
14823different strategies for ``flat'' and ``non-flat'' compositions.
14824A non-flat composition is anything that appears on multiple lines
14825(not counting line breaking). Examples would be matrices and Big
14826mode powers and quotients. Non-flat compositions are displayed
14827exactly as specified. If they come out wider than the current
14828window, you must use horizontal scrolling (@kbd{<} and @kbd{>}) to
14829view them.
14830
14831Flat compositions, on the other hand, will be broken across several
14832lines if they are too wide to fit the window. Certain points in a
14833composition are noted internally as @dfn{break points}. Calc's
14834general strategy is to fill each line as much as possible, then to
14835move down to the next line starting at the first break point that
14836didn't fit. However, the line breaker understands the hierarchical
14837structure of formulas. It will not break an ``inner'' formula if
14838it can use an earlier break point from an ``outer'' formula instead.
14839For example, a vector of sums might be formatted as:
14840
14841@example
14842@group
14843[ a + b + c, d + e + f,
14844 g + h + i, j + k + l, m ]
14845@end group
14846@end example
14847
14848@noindent
14849If the @samp{m} can fit, then so, it seems, could the @samp{g}.
14850But Calc prefers to break at the comma since the comma is part
14851of a ``more outer'' formula. Calc would break at a plus sign
14852only if it had to, say, if the very first sum in the vector had
14853itself been too large to fit.
14854
14855Of the composition functions described below, only @code{choriz}
14856generates break points. The @code{bstring} function (@pxref{Strings})
14857also generates breakable items: A break point is added after every
14858space (or group of spaces) except for spaces at the very beginning or
14859end of the string.
14860
14861Composition functions themselves count as levels in the formula
14862hierarchy, so a @code{choriz} that is a component of a larger
14863@code{choriz} will be less likely to be broken. As a special case,
14864if a @code{bstring} occurs as a component of a @code{choriz} or
14865@code{choriz}-like object (such as a vector or a list of arguments
14866in a function call), then the break points in that @code{bstring}
14867will be on the same level as the break points of the surrounding
14868object.
14869
14870@node Horizontal Compositions, Vertical Compositions, Composition Basics, Compositions
14871@subsubsection Horizontal Compositions
14872
14873@noindent
14874@ignore
14875@starindex
14876@end ignore
14877@tindex choriz
14878The @code{choriz} function takes a vector of objects and composes
14879them horizontally. For example, @samp{choriz([17, a b/c, d])} formats
14880as @w{@samp{17a b / cd}} in Normal language mode, or as
14881
14882@example
14883@group
14884 a b
1488517---d
14886 c
14887@end group
14888@end example
14889
14890@noindent
14891in Big language mode. This is actually one case of the general
14892function @samp{choriz(@var{vec}, @var{sep}, @var{prec})}, where
14893either or both of @var{sep} and @var{prec} may be omitted.
14894@var{Prec} gives the @dfn{precedence} to use when formatting
14895each of the components of @var{vec}. The default precedence is
14896the precedence from the surrounding environment.
14897
14898@var{Sep} is a string (i.e., a vector of character codes as might
14899be entered with @code{" "} notation) which should separate components
14900of the composition. Also, if @var{sep} is given, the line breaker
14901will allow lines to be broken after each occurrence of @var{sep}.
14902If @var{sep} is omitted, the composition will not be breakable
14903(unless any of its component compositions are breakable).
14904
14905For example, @samp{2 choriz([a, b c, d = e], " + ", 180)} is
14906formatted as @samp{2 a + b c + (d = e)}. To get the @code{choriz}
14907to have precedence 180 ``outwards'' as well as ``inwards,''
14908enclose it in a @code{cprec} form: @samp{2 cprec(choriz(...), 180)}
14909formats as @samp{2 (a + b c + (d = e))}.
14910
14911The baseline of a horizontal composition is the same as the
14912baselines of the component compositions, which are all aligned.
14913
14914@node Vertical Compositions, Other Compositions, Horizontal Compositions, Compositions
14915@subsubsection Vertical Compositions
14916
14917@noindent
14918@ignore
14919@starindex
14920@end ignore
14921@tindex cvert
14922The @code{cvert} function makes a vertical composition. Each
14923component of the vector is centered in a column. The baseline of
14924the result is by default the top line of the resulting composition.
14925For example, @samp{f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))}
14926formats in Big mode as
14927
14928@example
14929@group
14930f( a , 2 )
14931 bb a + 1
14932 ccc 2
14933 b
14934@end group
14935@end example
14936
14937@ignore
14938@starindex
14939@end ignore
14940@tindex cbase
14941There are several special composition functions that work only as
14942components of a vertical composition. The @code{cbase} function
14943controls the baseline of the vertical composition; the baseline
14944will be the same as the baseline of whatever component is enclosed
14945in @code{cbase}. Thus @samp{f(cvert([a, cbase(bb), ccc]),
14946cvert([a^2 + 1, cbase(b^2)]))} displays as
14947
14948@example
14949@group
14950 2
14951 a + 1
14952 a 2
14953f(bb , b )
14954 ccc
14955@end group
14956@end example
14957
14958@ignore
14959@starindex
14960@end ignore
14961@tindex ctbase
14962@ignore
14963@starindex
14964@end ignore
14965@tindex cbbase
14966There are also @code{ctbase} and @code{cbbase} functions which
14967make the baseline of the vertical composition equal to the top
14968or bottom line (rather than the baseline) of that component.
14969Thus @samp{cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
14970cvert([cbbase(a / b)])} gives
14971
14972@example
14973@group
14974 a
14975a -
14976- + a + b
14977b -
14978 b
14979@end group
14980@end example
14981
14982There should be only one @code{cbase}, @code{ctbase}, or @code{cbbase}
14983function in a given vertical composition. These functions can also
14984be written with no arguments: @samp{ctbase()} is a zero-height object
14985which means the baseline is the top line of the following item, and
14986@samp{cbbase()} means the baseline is the bottom line of the preceding
14987item.
14988
14989@ignore
14990@starindex
14991@end ignore
14992@tindex crule
14993The @code{crule} function builds a ``rule,'' or horizontal line,
14994across a vertical composition. By itself @samp{crule()} uses @samp{-}
14995characters to build the rule. You can specify any other character,
14996e.g., @samp{crule("=")}. The argument must be a character code or
14997vector of exactly one character code. It is repeated to match the
14998width of the widest item in the stack. For example, a quotient
14999with a thick line is @samp{cvert([a + 1, cbase(crule("=")), b^2])}:
15000
15001@example
15002@group
15003a + 1
15004=====
15005 2
15006 b
15007@end group
15008@end example
15009
15010@ignore
15011@starindex
15012@end ignore
15013@tindex clvert
15014@ignore
15015@starindex
15016@end ignore
15017@tindex crvert
15018Finally, the functions @code{clvert} and @code{crvert} act exactly
15019like @code{cvert} except that the items are left- or right-justified
15020in the stack. Thus @samp{clvert([a, bb, ccc]) + crvert([a, bb, ccc])}
15021gives:
15022
15023@example
15024@group
15025a + a
15026bb bb
15027ccc ccc
15028@end group
15029@end example
15030
15031Like @code{choriz}, the vertical compositions accept a second argument
15032which gives the precedence to use when formatting the components.
15033Vertical compositions do not support separator strings.
15034
15035@node Other Compositions, Information about Compositions, Vertical Compositions, Compositions
15036@subsubsection Other Compositions
15037
15038@noindent
15039@ignore
15040@starindex
15041@end ignore
15042@tindex csup
15043The @code{csup} function builds a superscripted expression. For
15044example, @samp{csup(a, b)} looks the same as @samp{a^b} does in Big
15045language mode. This is essentially a horizontal composition of
15046@samp{a} and @samp{b}, where @samp{b} is shifted up so that its
15047bottom line is one above the baseline.
15048
15049@ignore
15050@starindex
15051@end ignore
15052@tindex csub
15053Likewise, the @code{csub} function builds a subscripted expression.
15054This shifts @samp{b} down so that its top line is one below the
15055bottom line of @samp{a} (note that this is not quite analogous to
15056@code{csup}). Other arrangements can be obtained by using
15057@code{choriz} and @code{cvert} directly.
15058
15059@ignore
15060@starindex
15061@end ignore
15062@tindex cflat
15063The @code{cflat} function formats its argument in ``flat'' mode,
15064as obtained by @samp{d O}, if the current language mode is normal
15065or Big. It has no effect in other language modes. For example,
15066@samp{a^(b/c)} is formatted by Big mode like @samp{csup(a, cflat(b/c))}
15067to improve its readability.
15068
15069@ignore
15070@starindex
15071@end ignore
15072@tindex cspace
15073The @code{cspace} function creates horizontal space. For example,
15074@samp{cspace(4)} is effectively the same as @samp{string(" ")}.
15075A second string (i.e., vector of characters) argument is repeated
15076instead of the space character. For example, @samp{cspace(4, "ab")}
15077looks like @samp{abababab}. If the second argument is not a string,
15078it is formatted in the normal way and then several copies of that
15079are composed together: @samp{cspace(4, a^2)} yields
15080
15081@example
15082@group
15083 2 2 2 2
15084a a a a
15085@end group
15086@end example
15087
15088@noindent
15089If the number argument is zero, this is a zero-width object.
15090
15091@ignore
15092@starindex
15093@end ignore
15094@tindex cvspace
15095The @code{cvspace} function creates vertical space, or a vertical
15096stack of copies of a certain string or formatted object. The
15097baseline is the center line of the resulting stack. A numerical
15098argument of zero will produce an object which contributes zero
15099height if used in a vertical composition.
15100
15101@ignore
15102@starindex
15103@end ignore
15104@tindex ctspace
15105@ignore
15106@starindex
15107@end ignore
15108@tindex cbspace
15109There are also @code{ctspace} and @code{cbspace} functions which
15110create vertical space with the baseline the same as the baseline
15111of the top or bottom copy, respectively, of the second argument.
15112Thus @samp{cvspace(2, a/b) + ctspace(2, a/b) + cbspace(2, a/b)}
15113displays as:
15114
15115@example
15116@group
15117 a
15118 -
15119a b
15120- a a
15121b + - + -
15122a b b
15123- a
15124b -
15125 b
15126@end group
15127@end example
15128
15129@node Information about Compositions, User-Defined Compositions, Other Compositions, Compositions
15130@subsubsection Information about Compositions
15131
15132@noindent
15133The functions in this section are actual functions; they compose their
15134arguments according to the current language and other display modes,
15135then return a certain measurement of the composition as an integer.
15136
15137@ignore
15138@starindex
15139@end ignore
15140@tindex cwidth
15141The @code{cwidth} function measures the width, in characters, of a
15142composition. For example, @samp{cwidth(a + b)} is 5, and
15143@samp{cwidth(a / b)} is 5 in Normal mode, 1 in Big mode, and 11 in
15144@TeX{} mode (for @samp{@{a \over b@}}). The argument may involve
15145the composition functions described in this section.
15146
15147@ignore
15148@starindex
15149@end ignore
15150@tindex cheight
15151The @code{cheight} function measures the height of a composition.
15152This is the total number of lines in the argument's printed form.
15153
15154@ignore
15155@starindex
15156@end ignore
15157@tindex cascent
15158@ignore
15159@starindex
15160@end ignore
15161@tindex cdescent
15162The functions @code{cascent} and @code{cdescent} measure the amount
15163of the height that is above (and including) the baseline, or below
15164the baseline, respectively. Thus @samp{cascent(@var{x}) + cdescent(@var{x})}
15165always equals @samp{cheight(@var{x})}. For a one-line formula like
15166@samp{a + b}, @code{cascent} returns 1 and @code{cdescent} returns 0.
15167For @samp{a / b} in Big mode, @code{cascent} returns 2 and @code{cdescent}
15168returns 1. The only formula for which @code{cascent} will return zero
15169is @samp{cvspace(0)} or equivalents.
15170
15171@node User-Defined Compositions, , Information about Compositions, Compositions
15172@subsubsection User-Defined Compositions
15173
15174@noindent
15175@kindex Z C
15176@pindex calc-user-define-composition
15177The @kbd{Z C} (@code{calc-user-define-composition}) command lets you
15178define the display format for any algebraic function. You provide a
15179formula containing a certain number of argument variables on the stack.
15180Any time Calc formats a call to the specified function in the current
15181language mode and with that number of arguments, Calc effectively
15182replaces the function call with that formula with the arguments
15183replaced.
15184
15185Calc builds the default argument list by sorting all the variable names
15186that appear in the formula into alphabetical order. You can edit this
15187argument list before pressing @key{RET} if you wish. Any variables in
15188the formula that do not appear in the argument list will be displayed
15189literally; any arguments that do not appear in the formula will not
15190affect the display at all.
15191
15192You can define formats for built-in functions, for functions you have
15193defined with @kbd{Z F} (@pxref{Algebraic Definitions}), or for functions
15194which have no definitions but are being used as purely syntactic objects.
15195You can define different formats for each language mode, and for each
15196number of arguments, using a succession of @kbd{Z C} commands. When
15197Calc formats a function call, it first searches for a format defined
15198for the current language mode (and number of arguments); if there is
15199none, it uses the format defined for the Normal language mode. If
15200neither format exists, Calc uses its built-in standard format for that
15201function (usually just @samp{@var{func}(@var{args})}).
15202
15203If you execute @kbd{Z C} with the number 0 on the stack instead of a
15204formula, any defined formats for the function in the current language
15205mode will be removed. The function will revert to its standard format.
15206
15207For example, the default format for the binomial coefficient function
15208@samp{choose(n, m)} in the Big language mode is
15209
15210@example
15211@group
15212 n
15213( )
15214 m
15215@end group
15216@end example
15217
15218@noindent
15219You might prefer the notation,
15220
15221@example
15222@group
15223 C
15224n m
15225@end group
15226@end example
15227
15228@noindent
15229To define this notation, first make sure you are in Big mode,
15230then put the formula
15231
15232@smallexample
15233choriz([cvert([cvspace(1), n]), C, cvert([cvspace(1), m])])
15234@end smallexample
15235
15236@noindent
15237on the stack and type @kbd{Z C}. Answer the first prompt with
15238@code{choose}. The second prompt will be the default argument list
15239of @samp{(C m n)}. Edit this list to be @samp{(n m)} and press
15240@key{RET}. Now, try it out: For example, turn simplification
15241off with @kbd{m O} and enter @samp{choose(a,b) + choose(7,3)}
15242as an algebraic entry.
15243
15244@example
15245@group
15246 C + C
15247a b 7 3
15248@end group
15249@end example
15250
15251As another example, let's define the usual notation for Stirling
15252numbers of the first kind, @samp{stir1(n, m)}. This is just like
15253the regular format for binomial coefficients but with square brackets
15254instead of parentheses.
15255
15256@smallexample
15257choriz([string("["), cvert([n, cbase(cvspace(1)), m]), string("]")])
15258@end smallexample
15259
15260Now type @kbd{Z C stir1 @key{RET}}, edit the argument list to
15261@samp{(n m)}, and type @key{RET}.
15262
15263The formula provided to @kbd{Z C} usually will involve composition
15264functions, but it doesn't have to. Putting the formula @samp{a + b + c}
15265onto the stack and typing @kbd{Z C foo @key{RET} @key{RET}} would define
15266the function @samp{foo(x,y,z)} to display like @samp{x + y + z}.
15267This ``sum'' will act exactly like a real sum for all formatting
15268purposes (it will be parenthesized the same, and so on). However
15269it will be computationally unrelated to a sum. For example, the
15270formula @samp{2 * foo(1, 2, 3)} will display as @samp{2 (1 + 2 + 3)}.
15271Operator precedences have caused the ``sum'' to be written in
15272parentheses, but the arguments have not actually been summed.
15273(Generally a display format like this would be undesirable, since
15274it can easily be confused with a real sum.)
15275
15276The special function @code{eval} can be used inside a @kbd{Z C}
15277composition formula to cause all or part of the formula to be
15278evaluated at display time. For example, if the formula is
15279@samp{a + eval(b + c)}, then @samp{foo(1, 2, 3)} will be displayed
15280as @samp{1 + 5}. Evaluation will use the default simplifications,
15281regardless of the current simplification mode. There are also
15282@code{evalsimp} and @code{evalextsimp} which simplify as if by
15283@kbd{a s} and @kbd{a e} (respectively). Note that these ``functions''
15284operate only in the context of composition formulas (and also in
15285rewrite rules, where they serve a similar purpose; @pxref{Rewrite
15286Rules}). On the stack, a call to @code{eval} will be left in
15287symbolic form.
15288
15289It is not a good idea to use @code{eval} except as a last resort.
15290It can cause the display of formulas to be extremely slow. For
15291example, while @samp{eval(a + b)} might seem quite fast and simple,
15292there are several situations where it could be slow. For example,
15293@samp{a} and/or @samp{b} could be polar complex numbers, in which
15294case doing the sum requires trigonometry. Or, @samp{a} could be
15295the factorial @samp{fact(100)} which is unevaluated because you
15296have typed @kbd{m O}; @code{eval} will evaluate it anyway to
15297produce a large, unwieldy integer.
15298
15299You can save your display formats permanently using the @kbd{Z P}
15300command (@pxref{Creating User Keys}).
15301
15302@node Syntax Tables, , Compositions, Language Modes
15303@subsection Syntax Tables
15304
15305@noindent
15306@cindex Syntax tables
15307@cindex Parsing formulas, customized
15308Syntax tables do for input what compositions do for output: They
15309allow you to teach custom notations to Calc's formula parser.
15310Calc keeps a separate syntax table for each language mode.
15311
15312(Note that the Calc ``syntax tables'' discussed here are completely
15313unrelated to the syntax tables described in the Emacs manual.)
15314
15315@kindex Z S
15316@pindex calc-edit-user-syntax
15317The @kbd{Z S} (@code{calc-edit-user-syntax}) command edits the
15318syntax table for the current language mode. If you want your
15319syntax to work in any language, define it in the Normal language
15320mode. Type @kbd{C-c C-c} to finish editing the syntax table, or
15321@kbd{C-x k} to cancel the edit. The @kbd{m m} command saves all
15322the syntax tables along with the other mode settings;
15323@pxref{General Mode Commands}.
15324
15325@menu
15326* Syntax Table Basics::
15327* Precedence in Syntax Tables::
15328* Advanced Syntax Patterns::
15329* Conditional Syntax Rules::
15330@end menu
15331
15332@node Syntax Table Basics, Precedence in Syntax Tables, Syntax Tables, Syntax Tables
15333@subsubsection Syntax Table Basics
15334
15335@noindent
15336@dfn{Parsing} is the process of converting a raw string of characters,
15337such as you would type in during algebraic entry, into a Calc formula.
15338Calc's parser works in two stages. First, the input is broken down
15339into @dfn{tokens}, such as words, numbers, and punctuation symbols
15340like @samp{+}, @samp{:=}, and @samp{+/-}. Space between tokens is
15341ignored (except when it serves to separate adjacent words). Next,
15342the parser matches this string of tokens against various built-in
15343syntactic patterns, such as ``an expression followed by @samp{+}
15344followed by another expression'' or ``a name followed by @samp{(},
15345zero or more expressions separated by commas, and @samp{)}.''
15346
15347A @dfn{syntax table} is a list of user-defined @dfn{syntax rules},
15348which allow you to specify new patterns to define your own
15349favorite input notations. Calc's parser always checks the syntax
15350table for the current language mode, then the table for the Normal
15351language mode, before it uses its built-in rules to parse an
15352algebraic formula you have entered. Each syntax rule should go on
15353its own line; it consists of a @dfn{pattern}, a @samp{:=} symbol,
15354and a Calc formula with an optional @dfn{condition}. (Syntax rules
15355resemble algebraic rewrite rules, but the notation for patterns is
15356completely different.)
15357
15358A syntax pattern is a list of tokens, separated by spaces.
15359Except for a few special symbols, tokens in syntax patterns are
15360matched literally, from left to right. For example, the rule,
15361
15362@example
15363foo ( ) := 2+3
15364@end example
15365
15366@noindent
15367would cause Calc to parse the formula @samp{4+foo()*5} as if it
15368were @samp{4+(2+3)*5}. Notice that the parentheses were written
15369as two separate tokens in the rule. As a result, the rule works
15370for both @samp{foo()} and @w{@samp{foo ( )}}. If we had written
15371the rule as @samp{foo () := 2+3}, then Calc would treat @samp{()}
15372as a single, indivisible token, so that @w{@samp{foo( )}} would
15373not be recognized by the rule. (It would be parsed as a regular
15374zero-argument function call instead.) In fact, this rule would
15375also make trouble for the rest of Calc's parser: An unrelated
15376formula like @samp{bar()} would now be tokenized into @samp{bar ()}
15377instead of @samp{bar ( )}, so that the standard parser for function
15378calls would no longer recognize it!
15379
15380While it is possible to make a token with a mixture of letters
15381and punctuation symbols, this is not recommended. It is better to
15382break it into several tokens, as we did with @samp{foo()} above.
15383
15384The symbol @samp{#} in a syntax pattern matches any Calc expression.
15385On the righthand side, the things that matched the @samp{#}s can
15386be referred to as @samp{#1}, @samp{#2}, and so on (where @samp{#1}
15387matches the leftmost @samp{#} in the pattern). For example, these
15388rules match a user-defined function, prefix operator, infix operator,
15389and postfix operator, respectively:
15390
15391@example
15392foo ( # ) := myfunc(#1)
15393foo # := myprefix(#1)
15394# foo # := myinfix(#1,#2)
15395# foo := mypostfix(#1)
15396@end example
15397
15398Thus @samp{foo(3)} will parse as @samp{myfunc(3)}, and @samp{2+3 foo}
15399will parse as @samp{mypostfix(2+3)}.
15400
15401It is important to write the first two rules in the order shown,
15402because Calc tries rules in order from first to last. If the
15403pattern @samp{foo #} came first, it would match anything that could
15404match the @samp{foo ( # )} rule, since an expression in parentheses
15405is itself a valid expression. Thus the @w{@samp{foo ( # )}} rule would
15406never get to match anything. Likewise, the last two rules must be
15407written in the order shown or else @samp{3 foo 4} will be parsed as
15408@samp{mypostfix(3) * 4}. (Of course, the best way to avoid these
15409ambiguities is not to use the same symbol in more than one way at
15410the same time! In case you're not convinced, try the following
15411exercise: How will the above rules parse the input @samp{foo(3,4)},
15412if at all? Work it out for yourself, then try it in Calc and see.)
15413
15414Calc is quite flexible about what sorts of patterns are allowed.
15415The only rule is that every pattern must begin with a literal
15416token (like @samp{foo} in the first two patterns above), or with
15417a @samp{#} followed by a literal token (as in the last two
15418patterns). After that, any mixture is allowed, although putting
15419two @samp{#}s in a row will not be very useful since two
15420expressions with nothing between them will be parsed as one
15421expression that uses implicit multiplication.
15422
15423As a more practical example, Maple uses the notation
15424@samp{sum(a(i), i=1..10)} for sums, which Calc's Maple mode doesn't
15425recognize at present. To handle this syntax, we simply add the
15426rule,
15427
15428@example
15429sum ( # , # = # .. # ) := sum(#1,#2,#3,#4)
15430@end example
15431
15432@noindent
15433to the Maple mode syntax table. As another example, C mode can't
15434read assignment operators like @samp{++} and @samp{*=}. We can
15435define these operators quite easily:
15436
15437@example
15438# *= # := muleq(#1,#2)
15439# ++ := postinc(#1)
15440++ # := preinc(#1)
15441@end example
15442
15443@noindent
15444To complete the job, we would use corresponding composition functions
15445and @kbd{Z C} to cause these functions to display in their respective
15446Maple and C notations. (Note that the C example ignores issues of
15447operator precedence, which are discussed in the next section.)
15448
15449You can enclose any token in quotes to prevent its usual
15450interpretation in syntax patterns:
15451
15452@example
15453# ":=" # := becomes(#1,#2)
15454@end example
15455
15456Quotes also allow you to include spaces in a token, although once
15457again it is generally better to use two tokens than one token with
15458an embedded space. To include an actual quotation mark in a quoted
15459token, precede it with a backslash. (This also works to include
15460backslashes in tokens.)
15461
15462@example
15463# "bad token" # "/\"\\" # := silly(#1,#2,#3)
15464@end example
15465
15466@noindent
15467This will parse @samp{3 bad token 4 /"\ 5} to @samp{silly(3,4,5)}.
15468
15469The token @kbd{#} has a predefined meaning in Calc's formula parser;
15470it is not valid to use @samp{"#"} in a syntax rule. However, longer
15471tokens that include the @samp{#} character are allowed. Also, while
15472@samp{"$"} and @samp{"\""} are allowed as tokens, their presence in
15473the syntax table will prevent those characters from working in their
15474usual ways (referring to stack entries and quoting strings,
15475respectively).
15476
15477Finally, the notation @samp{%%} anywhere in a syntax table causes
15478the rest of the line to be ignored as a comment.
15479
15480@node Precedence in Syntax Tables, Advanced Syntax Patterns, Syntax Table Basics, Syntax Tables
15481@subsubsection Precedence
15482
15483@noindent
15484Different operators are generally assigned different @dfn{precedences}.
15485By default, an operator defined by a rule like
15486
15487@example
15488# foo # := foo(#1,#2)
15489@end example
15490
15491@noindent
15492will have an extremely low precedence, so that @samp{2*3+4 foo 5 == 6}
15493will be parsed as @samp{(2*3+4) foo (5 == 6)}. To change the
15494precedence of an operator, use the notation @samp{#/@var{p}} in
15495place of @samp{#}, where @var{p} is an integer precedence level.
15496For example, 185 lies between the precedences for @samp{+} and
15497@samp{*}, so if we change this rule to
15498
15499@example
15500#/185 foo #/186 := foo(#1,#2)
15501@end example
15502
15503@noindent
15504then @samp{2+3 foo 4*5} will be parsed as @samp{2+(3 foo (4*5))}.
15505Also, because we've given the righthand expression slightly higher
15506precedence, our new operator will be left-associative:
15507@samp{1 foo 2 foo 3} will be parsed as @samp{(1 foo 2) foo 3}.
15508By raising the precedence of the lefthand expression instead, we
15509can create a right-associative operator.
15510
15511@xref{Composition Basics}, for a table of precedences of the
15512standard Calc operators. For the precedences of operators in other
15513language modes, look in the Calc source file @file{calc-lang.el}.
15514
15515@node Advanced Syntax Patterns, Conditional Syntax Rules, Precedence in Syntax Tables, Syntax Tables
15516@subsubsection Advanced Syntax Patterns
15517
15518@noindent
15519To match a function with a variable number of arguments, you could
15520write
15521
15522@example
15523foo ( # ) := myfunc(#1)
15524foo ( # , # ) := myfunc(#1,#2)
15525foo ( # , # , # ) := myfunc(#1,#2,#3)
15526@end example
15527
15528@noindent
15529but this isn't very elegant. To match variable numbers of items,
15530Calc uses some notations inspired regular expressions and the
15531``extended BNF'' style used by some language designers.
15532
15533@example
15534foo ( @{ # @}*, ) := apply(myfunc,#1)
15535@end example
15536
15537The token @samp{@{} introduces a repeated or optional portion.
15538One of the three tokens @samp{@}*}, @samp{@}+}, or @samp{@}?}
15539ends the portion. These will match zero or more, one or more,
15540or zero or one copies of the enclosed pattern, respectively.
15541In addition, @samp{@}*} and @samp{@}+} can be followed by a
15542separator token (with no space in between, as shown above).
15543Thus @samp{@{ # @}*,} matches nothing, or one expression, or
15544several expressions separated by commas.
15545
15546A complete @samp{@{ ... @}} item matches as a vector of the
15547items that matched inside it. For example, the above rule will
15548match @samp{foo(1,2,3)} to get @samp{apply(myfunc,[1,2,3])}.
15549The Calc @code{apply} function takes a function name and a vector
15550of arguments and builds a call to the function with those
15551arguments, so the net result is the formula @samp{myfunc(1,2,3)}.
15552
15553If the body of a @samp{@{ ... @}} contains several @samp{#}s
15554(or nested @samp{@{ ... @}} constructs), then the items will be
15555strung together into the resulting vector. If the body
15556does not contain anything but literal tokens, the result will
15557always be an empty vector.
15558
15559@example
15560foo ( @{ # , # @}+, ) := bar(#1)
15561foo ( @{ @{ # @}*, @}*; ) := matrix(#1)
15562@end example
15563
15564@noindent
15565will parse @samp{foo(1, 2, 3, 4)} as @samp{bar([1, 2, 3, 4])}, and
15566@samp{foo(1, 2; 3, 4)} as @samp{matrix([[1, 2], [3, 4]])}. Also, after
15567some thought it's easy to see how this pair of rules will parse
15568@samp{foo(1, 2, 3)} as @samp{matrix([[1, 2, 3]])}, since the first
15569rule will only match an even number of arguments. The rule
15570
15571@example
15572foo ( # @{ , # , # @}? ) := bar(#1,#2)
15573@end example
15574
15575@noindent
15576will parse @samp{foo(2,3,4)} as @samp{bar(2,[3,4])}, and
15577@samp{foo(2)} as @samp{bar(2,[])}.
15578
15579The notation @samp{@{ ... @}?.} (note the trailing period) works
15580just the same as regular @samp{@{ ... @}?}, except that it does not
15581count as an argument; the following two rules are equivalent:
15582
15583@example
15584foo ( # , @{ also @}? # ) := bar(#1,#3)
15585foo ( # , @{ also @}?. # ) := bar(#1,#2)
15586@end example
15587
15588@noindent
15589Note that in the first case the optional text counts as @samp{#2},
15590which will always be an empty vector, but in the second case no
15591empty vector is produced.
15592
15593Another variant is @samp{@{ ... @}?$}, which means the body is
15594optional only at the end of the input formula. All built-in syntax
15595rules in Calc use this for closing delimiters, so that during
15596algebraic entry you can type @kbd{[sqrt(2), sqrt(3 @key{RET}}, omitting
15597the closing parenthesis and bracket. Calc does this automatically
15598for trailing @samp{)}, @samp{]}, and @samp{>} tokens in syntax
15599rules, but you can use @samp{@{ ... @}?$} explicitly to get
15600this effect with any token (such as @samp{"@}"} or @samp{end}).
15601Like @samp{@{ ... @}?.}, this notation does not count as an
15602argument. Conversely, you can use quotes, as in @samp{")"}, to
15603prevent a closing-delimiter token from being automatically treated
15604as optional.
15605
15606Calc's parser does not have full backtracking, which means some
15607patterns will not work as you might expect:
15608
15609@example
15610foo ( @{ # , @}? # , # ) := bar(#1,#2,#3)
15611@end example
15612
15613@noindent
15614Here we are trying to make the first argument optional, so that
15615@samp{foo(2,3)} parses as @samp{bar([],2,3)}. Unfortunately, Calc
15616first tries to match @samp{2,} against the optional part of the
15617pattern, finds a match, and so goes ahead to match the rest of the
15618pattern. Later on it will fail to match the second comma, but it
15619doesn't know how to go back and try the other alternative at that
15620point. One way to get around this would be to use two rules:
15621
15622@example
15623foo ( # , # , # ) := bar([#1],#2,#3)
15624foo ( # , # ) := bar([],#1,#2)
15625@end example
15626
15627More precisely, when Calc wants to match an optional or repeated
15628part of a pattern, it scans forward attempting to match that part.
15629If it reaches the end of the optional part without failing, it
15630``finalizes'' its choice and proceeds. If it fails, though, it
15631backs up and tries the other alternative. Thus Calc has ``partial''
15632backtracking. A fully backtracking parser would go on to make sure
15633the rest of the pattern matched before finalizing the choice.
15634
15635@node Conditional Syntax Rules, , Advanced Syntax Patterns, Syntax Tables
15636@subsubsection Conditional Syntax Rules
15637
15638@noindent
15639It is possible to attach a @dfn{condition} to a syntax rule. For
15640example, the rules
15641
15642@example
15643foo ( # ) := ifoo(#1) :: integer(#1)
15644foo ( # ) := gfoo(#1)
15645@end example
15646
15647@noindent
15648will parse @samp{foo(3)} as @samp{ifoo(3)}, but will parse
15649@samp{foo(3.5)} and @samp{foo(x)} as calls to @code{gfoo}. Any
15650number of conditions may be attached; all must be true for the
15651rule to succeed. A condition is ``true'' if it evaluates to a
15652nonzero number. @xref{Logical Operations}, for a list of Calc
15653functions like @code{integer} that perform logical tests.
15654
15655The exact sequence of events is as follows: When Calc tries a
15656rule, it first matches the pattern as usual. It then substitutes
15657@samp{#1}, @samp{#2}, etc., in the conditions, if any. Next, the
15658conditions are simplified and evaluated in order from left to right,
8e7046c3 15659using the algebraic simplifications (@pxref{Simplifying Formulas}).
4009494e
GM
15660Each result is true if it is a nonzero number, or an expression
15661that can be proven to be nonzero (@pxref{Declarations}). If the
15662results of all conditions are true, the expression (such as
15663@samp{ifoo(#1)}) has its @samp{#}s substituted, and that is the
15664result of the parse. If the result of any condition is false, Calc
15665goes on to try the next rule in the syntax table.
15666
15667Syntax rules also support @code{let} conditions, which operate in
15668exactly the same way as they do in algebraic rewrite rules.
15669@xref{Other Features of Rewrite Rules}, for details. A @code{let}
15670condition is always true, but as a side effect it defines a
15671variable which can be used in later conditions, and also in the
15672expression after the @samp{:=} sign:
15673
15674@example
15675foo ( # ) := hifoo(x) :: let(x := #1 + 0.5) :: dnumint(x)
15676@end example
15677
15678@noindent
15679The @code{dnumint} function tests if a value is numerically an
15680integer, i.e., either a true integer or an integer-valued float.
15681This rule will parse @code{foo} with a half-integer argument,
15682like @samp{foo(3.5)}, to a call like @samp{hifoo(4.)}.
15683
15684The lefthand side of a syntax rule @code{let} must be a simple
15685variable, not the arbitrary pattern that is allowed in rewrite
15686rules.
15687
15688The @code{matches} function is also treated specially in syntax
15689rule conditions (again, in the same way as in rewrite rules).
15690@xref{Matching Commands}. If the matching pattern contains
15691meta-variables, then those meta-variables may be used in later
15692conditions and in the result expression. The arguments to
15693@code{matches} are not evaluated in this situation.
15694
15695@example
15696sum ( # , # ) := sum(#1,a,b,c) :: matches(#2, a=[b..c])
15697@end example
15698
15699@noindent
15700This is another way to implement the Maple mode @code{sum} notation.
15701In this approach, we allow @samp{#2} to equal the whole expression
15702@samp{i=1..10}. Then, we use @code{matches} to break it apart into
15703its components. If the expression turns out not to match the pattern,
15704the syntax rule will fail. Note that @kbd{Z S} always uses Calc's
15705Normal language mode for editing expressions in syntax rules, so we
15706must use regular Calc notation for the interval @samp{[b..c]} that
15707will correspond to the Maple mode interval @samp{1..10}.
15708
15709@node Modes Variable, Calc Mode Line, Language Modes, Mode Settings
15710@section The @code{Modes} Variable
15711
15712@noindent
15713@kindex m g
15714@pindex calc-get-modes
15715The @kbd{m g} (@code{calc-get-modes}) command pushes onto the stack
15716a vector of numbers that describes the various mode settings that
15717are in effect. With a numeric prefix argument, it pushes only the
15718@var{n}th mode, i.e., the @var{n}th element of this vector. Keyboard
15719macros can use the @kbd{m g} command to modify their behavior based
15720on the current mode settings.
15721
15722@cindex @code{Modes} variable
15723@vindex Modes
15724The modes vector is also available in the special variable
15725@code{Modes}. In other words, @kbd{m g} is like @kbd{s r Modes @key{RET}}.
15726It will not work to store into this variable; in fact, if you do,
15727@code{Modes} will cease to track the current modes. (The @kbd{m g}
15728command will continue to work, however.)
15729
15730In general, each number in this vector is suitable as a numeric
15731prefix argument to the associated mode-setting command. (Recall
15732that the @kbd{~} key takes a number from the stack and gives it as
15733a numeric prefix to the next command.)
15734
15735The elements of the modes vector are as follows:
15736
15737@enumerate
15738@item
15739Current precision. Default is 12; associated command is @kbd{p}.
15740
15741@item
15742Binary word size. Default is 32; associated command is @kbd{b w}.
15743
15744@item
15745Stack size (not counting the value about to be pushed by @kbd{m g}).
15746This is zero if @kbd{m g} is executed with an empty stack.
15747
15748@item
15749Number radix. Default is 10; command is @kbd{d r}.
15750
15751@item
15752Floating-point format. This is the number of digits, plus the
15753constant 0 for normal notation, 10000 for scientific notation,
1575420000 for engineering notation, or 30000 for fixed-point notation.
15755These codes are acceptable as prefix arguments to the @kbd{d n}
15756command, but note that this may lose information: For example,
15757@kbd{d s} and @kbd{C-u 12 d s} have similar (but not quite
15758identical) effects if the current precision is 12, but they both
15759produce a code of 10012, which will be treated by @kbd{d n} as
15760@kbd{C-u 12 d s}. If the precision then changes, the float format
15761will still be frozen at 12 significant figures.
15762
15763@item
15764Angular mode. Default is 1 (degrees). Other values are 2 (radians)
15765and 3 (HMS). The @kbd{m d} command accepts these prefixes.
15766
15767@item
15768Symbolic mode. Value is 0 or 1; default is 0. Command is @kbd{m s}.
15769
15770@item
15771Fraction mode. Value is 0 or 1; default is 0. Command is @kbd{m f}.
15772
15773@item
15774Polar mode. Value is 0 (rectangular) or 1 (polar); default is 0.
15775Command is @kbd{m p}.
15776
15777@item
15778Matrix/Scalar mode. Default value is @mathit{-1}. Value is 0 for Scalar
15779mode, @mathit{-2} for Matrix mode, @mathit{-3} for square Matrix mode,
40ba43b4 15780or @var{N} for
4009494e 15781@texline @math{N\times N}
40ba43b4 15782@infoline @var{N}x@var{N}
4009494e
GM
15783Matrix mode. Command is @kbd{m v}.
15784
15785@item
15786Simplification mode. Default is 1. Value is @mathit{-1} for off (@kbd{m O}),
157870 for @kbd{m N}, 2 for @kbd{m B}, 3 for @kbd{m A}, 4 for @kbd{m E},
15788or 5 for @w{@kbd{m U}}. The @kbd{m D} command accepts these prefixes.
15789
15790@item
15791Infinite mode. Default is @mathit{-1} (off). Value is 1 if the mode is on,
15792or 0 if the mode is on with positive zeros. Command is @kbd{m i}.
15793@end enumerate
15794
15795For example, the sequence @kbd{M-1 m g @key{RET} 2 + ~ p} increases the
15796precision by two, leaving a copy of the old precision on the stack.
15797Later, @kbd{~ p} will restore the original precision using that
15798stack value. (This sequence might be especially useful inside a
15799keyboard macro.)
15800
15801As another example, @kbd{M-3 m g 1 - ~ @key{DEL}} deletes all but the
15802oldest (bottommost) stack entry.
15803
15804Yet another example: The HP-48 ``round'' command rounds a number
15805to the current displayed precision. You could roughly emulate this
15806in Calc with the sequence @kbd{M-5 m g 10000 % ~ c c}. (This
15807would not work for fixed-point mode, but it wouldn't be hard to
15808do a full emulation with the help of the @kbd{Z [} and @kbd{Z ]}
15809programming commands. @xref{Conditionals in Macros}.)
15810
15811@node Calc Mode Line, , Modes Variable, Mode Settings
15812@section The Calc Mode Line
15813
15814@noindent
15815@cindex Mode line indicators
15816This section is a summary of all symbols that can appear on the
15817Calc mode line, the highlighted bar that appears under the Calc
15818stack window (or under an editing window in Embedded mode).
15819
15820The basic mode line format is:
15821
15822@example
92e15881 15823--%*-Calc: 12 Deg @var{other modes} (Calculator)
4009494e
GM
15824@end example
15825
92e15881 15826The @samp{%*} indicates that the buffer is ``read-only''; it shows that
4009494e
GM
15827regular Emacs commands are not allowed to edit the stack buffer
15828as if it were text.
15829
15830The word @samp{Calc:} changes to @samp{CalcEmbed:} if Embedded mode
15831is enabled. The words after this describe the various Calc modes
15832that are in effect.
15833
15834The first mode is always the current precision, an integer.
15835The second mode is always the angular mode, either @code{Deg},
15836@code{Rad}, or @code{Hms}.
15837
15838Here is a complete list of the remaining symbols that can appear
15839on the mode line:
15840
15841@table @code
15842@item Alg
15843Algebraic mode (@kbd{m a}; @pxref{Algebraic Entry}).
15844
15845@item Alg[(
15846Incomplete algebraic mode (@kbd{C-u m a}).
15847
15848@item Alg*
15849Total algebraic mode (@kbd{m t}).
15850
15851@item Symb
15852Symbolic mode (@kbd{m s}; @pxref{Symbolic Mode}).
15853
15854@item Matrix
15855Matrix mode (@kbd{m v}; @pxref{Matrix Mode}).
15856
15857@item Matrix@var{n}
15858Dimensioned Matrix mode (@kbd{C-u @var{n} m v}; @pxref{Matrix Mode}).
15859
15860@item SqMatrix
15861Square Matrix mode (@kbd{C-u m v}; @pxref{Matrix Mode}).
15862
15863@item Scalar
15864Scalar mode (@kbd{m v}; @pxref{Matrix Mode}).
15865
15866@item Polar
15867Polar complex mode (@kbd{m p}; @pxref{Polar Mode}).
15868
15869@item Frac
15870Fraction mode (@kbd{m f}; @pxref{Fraction Mode}).
15871
15872@item Inf
15873Infinite mode (@kbd{m i}; @pxref{Infinite Mode}).
15874
15875@item +Inf
15876Positive Infinite mode (@kbd{C-u 0 m i}).
15877
15878@item NoSimp
15879Default simplifications off (@kbd{m O}; @pxref{Simplification Modes}).
15880
15881@item NumSimp
15882Default simplifications for numeric arguments only (@kbd{m N}).
15883
15884@item BinSimp@var{w}
15885Binary-integer simplification mode; word size @var{w} (@kbd{m B}, @kbd{b w}).
15886
8e7046c3
JB
15887@item BasicSimp
15888Basic simplification mode (@kbd{m I}).
4009494e
GM
15889
15890@item ExtSimp
15891Extended algebraic simplification mode (@kbd{m E}).
15892
15893@item UnitSimp
15894Units simplification mode (@kbd{m U}).
15895
15896@item Bin
15897Current radix is 2 (@kbd{d 2}; @pxref{Radix Modes}).
15898
15899@item Oct
15900Current radix is 8 (@kbd{d 8}).
15901
15902@item Hex
15903Current radix is 16 (@kbd{d 6}).
15904
15905@item Radix@var{n}
15906Current radix is @var{n} (@kbd{d r}).
15907
15908@item Zero
15909Leading zeros (@kbd{d z}; @pxref{Radix Modes}).
15910
15911@item Big
15912Big language mode (@kbd{d B}; @pxref{Normal Language Modes}).
15913
15914@item Flat
15915One-line normal language mode (@kbd{d O}).
15916
15917@item Unform
15918Unformatted language mode (@kbd{d U}).
15919
15920@item C
15921C language mode (@kbd{d C}; @pxref{C FORTRAN Pascal}).
15922
15923@item Pascal
15924Pascal language mode (@kbd{d P}).
15925
15926@item Fortran
15927FORTRAN language mode (@kbd{d F}).
15928
15929@item TeX
15930@TeX{} language mode (@kbd{d T}; @pxref{TeX and LaTeX Language Modes}).
15931
15932@item LaTeX
c1dabff0 15933@LaTeX{} language mode (@kbd{d L}; @pxref{TeX and LaTeX Language Modes}).
4009494e
GM
15934
15935@item Eqn
15936@dfn{Eqn} language mode (@kbd{d E}; @pxref{Eqn Language Mode}).
15937
15938@item Math
15939Mathematica language mode (@kbd{d M}; @pxref{Mathematica Language Mode}).
15940
15941@item Maple
15942Maple language mode (@kbd{d W}; @pxref{Maple Language Mode}).
15943
15944@item Norm@var{n}
15945Normal float mode with @var{n} digits (@kbd{d n}; @pxref{Float Formats}).
15946
15947@item Fix@var{n}
15948Fixed point mode with @var{n} digits after the point (@kbd{d f}).
15949
15950@item Sci
15951Scientific notation mode (@kbd{d s}).
15952
15953@item Sci@var{n}
15954Scientific notation with @var{n} digits (@kbd{d s}).
15955
15956@item Eng
15957Engineering notation mode (@kbd{d e}).
15958
15959@item Eng@var{n}
15960Engineering notation with @var{n} digits (@kbd{d e}).
15961
15962@item Left@var{n}
15963Left-justified display indented by @var{n} (@kbd{d <}; @pxref{Justification}).
15964
15965@item Right
15966Right-justified display (@kbd{d >}).
15967
15968@item Right@var{n}
15969Right-justified display with width @var{n} (@kbd{d >}).
15970
15971@item Center
15972Centered display (@kbd{d =}).
15973
15974@item Center@var{n}
15975Centered display with center column @var{n} (@kbd{d =}).
15976
15977@item Wid@var{n}
15978Line breaking with width @var{n} (@kbd{d b}; @pxref{Normal Language Modes}).
15979
15980@item Wide
15981No line breaking (@kbd{d b}).
15982
15983@item Break
15984Selections show deep structure (@kbd{j b}; @pxref{Making Selections}).
15985
15986@item Save
dcf7843e 15987Record modes in @file{~/.emacs.d/calc.el} (@kbd{m R}; @pxref{General Mode Commands}).
4009494e
GM
15988
15989@item Local
15990Record modes in Embedded buffer (@kbd{m R}).
15991
15992@item LocEdit
15993Record modes as editing-only in Embedded buffer (@kbd{m R}).
15994
15995@item LocPerm
15996Record modes as permanent-only in Embedded buffer (@kbd{m R}).
15997
15998@item Global
15999Record modes as global in Embedded buffer (@kbd{m R}).
16000
16001@item Manual
16002Automatic recomputation turned off (@kbd{m C}; @pxref{Automatic
16003Recomputation}).
16004
16005@item Graph
16006GNUPLOT process is alive in background (@pxref{Graphics}).
16007
16008@item Sel
16009Top-of-stack has a selection (Embedded only; @pxref{Making Selections}).
16010
16011@item Dirty
16012The stack display may not be up-to-date (@pxref{Display Modes}).
16013
16014@item Inv
16015``Inverse'' prefix was pressed (@kbd{I}; @pxref{Inverse and Hyperbolic}).
16016
16017@item Hyp
16018``Hyperbolic'' prefix was pressed (@kbd{H}).
16019
16020@item Keep
16021``Keep-arguments'' prefix was pressed (@kbd{K}).
16022
16023@item Narrow
16024Stack is truncated (@kbd{d t}; @pxref{Truncating the Stack}).
16025@end table
16026
16027In addition, the symbols @code{Active} and @code{~Active} can appear
16028as minor modes on an Embedded buffer's mode line. @xref{Embedded Mode}.
16029
16030@node Arithmetic, Scientific Functions, Mode Settings, Top
16031@chapter Arithmetic Functions
16032
16033@noindent
16034This chapter describes the Calc commands for doing simple calculations
16035on numbers, such as addition, absolute value, and square roots. These
16036commands work by removing the top one or two values from the stack,
16037performing the desired operation, and pushing the result back onto the
16038stack. If the operation cannot be performed, the result pushed is a
16039formula instead of a number, such as @samp{2/0} (because division by zero
16040is invalid) or @samp{sqrt(x)} (because the argument @samp{x} is a formula).
16041
16042Most of the commands described here can be invoked by a single keystroke.
16043Some of the more obscure ones are two-letter sequences beginning with
16044the @kbd{f} (``functions'') prefix key.
16045
16046@xref{Prefix Arguments}, for a discussion of the effect of numeric
16047prefix arguments on commands in this chapter which do not otherwise
16048interpret a prefix argument.
16049
16050@menu
16051* Basic Arithmetic::
16052* Integer Truncation::
16053* Complex Number Functions::
16054* Conversions::
16055* Date Arithmetic::
16056* Financial Functions::
16057* Binary Functions::
16058@end menu
16059
16060@node Basic Arithmetic, Integer Truncation, Arithmetic, Arithmetic
16061@section Basic Arithmetic
16062
16063@noindent
16064@kindex +
16065@pindex calc-plus
16066@ignore
16067@mindex @null
16068@end ignore
16069@tindex +
16070The @kbd{+} (@code{calc-plus}) command adds two numbers. The numbers may
16071be any of the standard Calc data types. The resulting sum is pushed back
16072onto the stack.
16073
16074If both arguments of @kbd{+} are vectors or matrices (of matching dimensions),
16075the result is a vector or matrix sum. If one argument is a vector and the
16076other a scalar (i.e., a non-vector), the scalar is added to each of the
16077elements of the vector to form a new vector. If the scalar is not a
16078number, the operation is left in symbolic form: Suppose you added @samp{x}
16079to the vector @samp{[1,2]}. You may want the result @samp{[1+x,2+x]}, or
16080you may plan to substitute a 2-vector for @samp{x} in the future. Since
16081the Calculator can't tell which interpretation you want, it makes the
16082safest assumption. @xref{Reducing and Mapping}, for a way to add @samp{x}
16083to every element of a vector.
16084
16085If either argument of @kbd{+} is a complex number, the result will in general
16086be complex. If one argument is in rectangular form and the other polar,
16087the current Polar mode determines the form of the result. If Symbolic
16088mode is enabled, the sum may be left as a formula if the necessary
16089conversions for polar addition are non-trivial.
16090
16091If both arguments of @kbd{+} are HMS forms, the forms are added according to
16092the usual conventions of hours-minutes-seconds notation. If one argument
16093is an HMS form and the other is a number, that number is converted from
16094degrees or radians (depending on the current Angular mode) to HMS format
16095and then the two HMS forms are added.
16096
16097If one argument of @kbd{+} is a date form, the other can be either a
16098real number, which advances the date by a certain number of days, or
16099an HMS form, which advances the date by a certain amount of time.
16100Subtracting two date forms yields the number of days between them.
16101Adding two date forms is meaningless, but Calc interprets it as the
16102subtraction of one date form and the negative of the other. (The
16103negative of a date form can be understood by remembering that dates
16104are stored as the number of days before or after Jan 1, 1 AD.)
16105
16106If both arguments of @kbd{+} are error forms, the result is an error form
16107with an appropriately computed standard deviation. If one argument is an
16108error form and the other is a number, the number is taken to have zero error.
16109Error forms may have symbolic formulas as their mean and/or error parts;
16110adding these will produce a symbolic error form result. However, adding an
16111error form to a plain symbolic formula (as in @samp{(a +/- b) + c}) will not
16112work, for the same reasons just mentioned for vectors. Instead you must
16113write @samp{(a +/- b) + (c +/- 0)}.
16114
16115If both arguments of @kbd{+} are modulo forms with equal values of @expr{M},
16116or if one argument is a modulo form and the other a plain number, the
16117result is a modulo form which represents the sum, modulo @expr{M}, of
16118the two values.
16119
16120If both arguments of @kbd{+} are intervals, the result is an interval
16121which describes all possible sums of the possible input values. If
16122one argument is a plain number, it is treated as the interval
16123@w{@samp{[x ..@: x]}}.
16124
16125If one argument of @kbd{+} is an infinity and the other is not, the
16126result is that same infinity. If both arguments are infinite and in
16127the same direction, the result is the same infinity, but if they are
16128infinite in different directions the result is @code{nan}.
16129
16130@kindex -
16131@pindex calc-minus
16132@ignore
16133@mindex @null
16134@end ignore
16135@tindex -
16136The @kbd{-} (@code{calc-minus}) command subtracts two values. The top
16137number on the stack is subtracted from the one behind it, so that the
16138computation @kbd{5 @key{RET} 2 -} produces 3, not @mathit{-3}. All options
16139available for @kbd{+} are available for @kbd{-} as well.
16140
16141@kindex *
16142@pindex calc-times
16143@ignore
16144@mindex @null
16145@end ignore
16146@tindex *
16147The @kbd{*} (@code{calc-times}) command multiplies two numbers. If one
16148argument is a vector and the other a scalar, the scalar is multiplied by
16149the elements of the vector to produce a new vector. If both arguments
16150are vectors, the interpretation depends on the dimensions of the
16151vectors: If both arguments are matrices, a matrix multiplication is
16152done. If one argument is a matrix and the other a plain vector, the
16153vector is interpreted as a row vector or column vector, whichever is
16154dimensionally correct. If both arguments are plain vectors, the result
16155is a single scalar number which is the dot product of the two vectors.
16156
16157If one argument of @kbd{*} is an HMS form and the other a number, the
16158HMS form is multiplied by that amount. It is an error to multiply two
16159HMS forms together, or to attempt any multiplication involving date
16160forms. Error forms, modulo forms, and intervals can be multiplied;
16161see the comments for addition of those forms. When two error forms
16162or intervals are multiplied they are considered to be statistically
16163independent; thus, @samp{[-2 ..@: 3] * [-2 ..@: 3]} is @samp{[-6 ..@: 9]},
16164whereas @w{@samp{[-2 ..@: 3] ^ 2}} is @samp{[0 ..@: 9]}.
16165
16166@kindex /
16167@pindex calc-divide
16168@ignore
16169@mindex @null
16170@end ignore
16171@tindex /
40ba43b4 16172The @kbd{/} (@code{calc-divide}) command divides two numbers.
4009494e
GM
16173
16174When combining multiplication and division in an algebraic formula, it
16175is good style to use parentheses to distinguish between possible
16176interpretations; the expression @samp{a/b*c} should be written
16177@samp{(a/b)*c} or @samp{a/(b*c)}, as appropriate. Without the
16178parentheses, Calc will interpret @samp{a/b*c} as @samp{a/(b*c)}, since
16179in algebraic entry Calc gives division a lower precedence than
16180multiplication. (This is not standard across all computer languages, and
40ba43b4 16181Calc may change the precedence depending on the language mode being used.
4009494e
GM
16182@xref{Language Modes}.) This default ordering can be changed by setting
16183the customizable variable @code{calc-multiplication-has-precedence} to
16184@code{nil} (@pxref{Customizing Calc}); this will give multiplication and
16185division equal precedences. Note that Calc's default choice of
16186precedence allows @samp{a b / c d} to be used as a shortcut for
16187@smallexample
16188@group
16189a b
16190---.
16191c d
16192@end group
16193@end smallexample
16194
16195When dividing a scalar @expr{B} by a square matrix @expr{A}, the
16196computation performed is @expr{B} times the inverse of @expr{A}. This
16197also occurs if @expr{B} is itself a vector or matrix, in which case the
16198effect is to solve the set of linear equations represented by @expr{B}.
16199If @expr{B} is a matrix with the same number of rows as @expr{A}, or a
16200plain vector (which is interpreted here as a column vector), then the
16201equation @expr{A X = B} is solved for the vector or matrix @expr{X}.
16202Otherwise, if @expr{B} is a non-square matrix with the same number of
16203@emph{columns} as @expr{A}, the equation @expr{X A = B} is solved. If
16204you wish a vector @expr{B} to be interpreted as a row vector to be
16205solved as @expr{X A = B}, make it into a one-row matrix with @kbd{C-u 1
16206v p} first. To force a left-handed solution with a square matrix
16207@expr{B}, transpose @expr{A} and @expr{B} before dividing, then
16208transpose the result.
16209
16210HMS forms can be divided by real numbers or by other HMS forms. Error
16211forms can be divided in any combination of ways. Modulo forms where both
16212values and the modulo are integers can be divided to get an integer modulo
16213form result. Intervals can be divided; dividing by an interval that
16214encompasses zero or has zero as a limit will result in an infinite
16215interval.
16216
16217@kindex ^
16218@pindex calc-power
16219@ignore
16220@mindex @null
16221@end ignore
16222@tindex ^
16223The @kbd{^} (@code{calc-power}) command raises a number to a power. If
16224the power is an integer, an exact result is computed using repeated
16225multiplications. For non-integer powers, Calc uses Newton's method or
16226logarithms and exponentials. Square matrices can be raised to integer
16227powers. If either argument is an error (or interval or modulo) form,
16228the result is also an error (or interval or modulo) form.
16229
16230@kindex I ^
16231@tindex nroot
16232If you press the @kbd{I} (inverse) key first, the @kbd{I ^} command
16233computes an Nth root: @kbd{125 @key{RET} 3 I ^} computes the number 5.
16234(This is entirely equivalent to @kbd{125 @key{RET} 1:3 ^}.)
16235
16236@kindex \
16237@pindex calc-idiv
16238@tindex idiv
16239@ignore
16240@mindex @null
16241@end ignore
16242@tindex \
16243The @kbd{\} (@code{calc-idiv}) command divides two numbers on the stack
16244to produce an integer result. It is equivalent to dividing with
16245@key{/}, then rounding down with @kbd{F} (@code{calc-floor}), only a bit
16246more convenient and efficient. Also, since it is an all-integer
16247operation when the arguments are integers, it avoids problems that
16248@kbd{/ F} would have with floating-point roundoff.
16249
16250@kindex %
16251@pindex calc-mod
16252@ignore
16253@mindex @null
16254@end ignore
16255@tindex %
16256The @kbd{%} (@code{calc-mod}) command performs a ``modulo'' (or ``remainder'')
16257operation. Mathematically, @samp{a%b = a - (a\b)*b}, and is defined
16258for all real numbers @expr{a} and @expr{b} (except @expr{b=0}). For
16259positive @expr{b}, the result will always be between 0 (inclusive) and
16260@expr{b} (exclusive). Modulo does not work for HMS forms and error forms.
16261If @expr{a} is a modulo form, its modulo is changed to @expr{b}, which
16262must be positive real number.
16263
16264@kindex :
16265@pindex calc-fdiv
16266@tindex fdiv
16267The @kbd{:} (@code{calc-fdiv}) [@code{fdiv}] command
16268divides the two integers on the top of the stack to produce a fractional
16269result. This is a convenient shorthand for enabling Fraction mode (with
16270@kbd{m f}) temporarily and using @samp{/}. Note that during numeric entry
16271the @kbd{:} key is interpreted as a fraction separator, so to divide 8 by 6
16272you would have to type @kbd{8 @key{RET} 6 @key{RET} :}. (Of course, in
16273this case, it would be much easier simply to enter the fraction directly
16274as @kbd{8:6 @key{RET}}!)
16275
16276@kindex n
16277@pindex calc-change-sign
16278The @kbd{n} (@code{calc-change-sign}) command negates the number on the top
16279of the stack. It works on numbers, vectors and matrices, HMS forms, date
16280forms, error forms, intervals, and modulo forms.
16281
16282@kindex A
16283@pindex calc-abs
16284@tindex abs
16285The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the absolute
16286value of a number. The result of @code{abs} is always a nonnegative
16287real number: With a complex argument, it computes the complex magnitude.
16288With a vector or matrix argument, it computes the Frobenius norm, i.e.,
16289the square root of the sum of the squares of the absolute values of the
16290elements. The absolute value of an error form is defined by replacing
16291the mean part with its absolute value and leaving the error part the same.
16292The absolute value of a modulo form is undefined. The absolute value of
16293an interval is defined in the obvious way.
16294
16295@kindex f A
16296@pindex calc-abssqr
16297@tindex abssqr
16298The @kbd{f A} (@code{calc-abssqr}) [@code{abssqr}] command computes the
16299absolute value squared of a number, vector or matrix, or error form.
16300
16301@kindex f s
16302@pindex calc-sign
16303@tindex sign
16304The @kbd{f s} (@code{calc-sign}) [@code{sign}] command returns 1 if its
16305argument is positive, @mathit{-1} if its argument is negative, or 0 if its
16306argument is zero. In algebraic form, you can also write @samp{sign(a,x)}
16307which evaluates to @samp{x * sign(a)}, i.e., either @samp{x}, @samp{-x}, or
16308zero depending on the sign of @samp{a}.
16309
16310@kindex &
16311@pindex calc-inv
16312@tindex inv
16313@cindex Reciprocal
16314The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
16315reciprocal of a number, i.e., @expr{1 / x}. Operating on a square
16316matrix, it computes the inverse of that matrix.
16317
16318@kindex Q
16319@pindex calc-sqrt
16320@tindex sqrt
16321The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] command computes the square
16322root of a number. For a negative real argument, the result will be a
16323complex number whose form is determined by the current Polar mode.
16324
16325@kindex f h
16326@pindex calc-hypot
16327@tindex hypot
16328The @kbd{f h} (@code{calc-hypot}) [@code{hypot}] command computes the square
16329root of the sum of the squares of two numbers. That is, @samp{hypot(a,b)}
16330is the length of the hypotenuse of a right triangle with sides @expr{a}
16331and @expr{b}. If the arguments are complex numbers, their squared
16332magnitudes are used.
16333
16334@kindex f Q
16335@pindex calc-isqrt
16336@tindex isqrt
16337The @kbd{f Q} (@code{calc-isqrt}) [@code{isqrt}] command computes the
16338integer square root of an integer. This is the true square root of the
16339number, rounded down to an integer. For example, @samp{isqrt(10)}
16340produces 3. Note that, like @kbd{\} [@code{idiv}], this uses exact
16341integer arithmetic throughout to avoid roundoff problems. If the input
16342is a floating-point number or other non-integer value, this is exactly
16343the same as @samp{floor(sqrt(x))}.
16344
16345@kindex f n
16346@kindex f x
16347@pindex calc-min
16348@tindex min
16349@pindex calc-max
16350@tindex max
16351The @kbd{f n} (@code{calc-min}) [@code{min}] and @kbd{f x} (@code{calc-max})
16352[@code{max}] commands take the minimum or maximum of two real numbers,
16353respectively. These commands also work on HMS forms, date forms,
16354intervals, and infinities. (In algebraic expressions, these functions
16355take any number of arguments and return the maximum or minimum among
16356all the arguments.)
16357
16358@kindex f M
16359@kindex f X
16360@pindex calc-mant-part
16361@tindex mant
16362@pindex calc-xpon-part
16363@tindex xpon
16364The @kbd{f M} (@code{calc-mant-part}) [@code{mant}] function extracts
16365the ``mantissa'' part @expr{m} of its floating-point argument; @kbd{f X}
16366(@code{calc-xpon-part}) [@code{xpon}] extracts the ``exponent'' part
40ba43b4 16367@expr{e}. The original number is equal to
4009494e
GM
16368@texline @math{m \times 10^e},
16369@infoline @expr{m * 10^e},
16370where @expr{m} is in the interval @samp{[1.0 ..@: 10.0)} except that
16371@expr{m=e=0} if the original number is zero. For integers
16372and fractions, @code{mant} returns the number unchanged and @code{xpon}
16373returns zero. The @kbd{v u} (@code{calc-unpack}) command can also be
16374used to ``unpack'' a floating-point number; this produces an integer
16375mantissa and exponent, with the constraint that the mantissa is not
16376a multiple of ten (again except for the @expr{m=e=0} case).
16377
16378@kindex f S
16379@pindex calc-scale-float
16380@tindex scf
16381The @kbd{f S} (@code{calc-scale-float}) [@code{scf}] function scales a number
16382by a given power of ten. Thus, @samp{scf(mant(x), xpon(x)) = x} for any
16383real @samp{x}. The second argument must be an integer, but the first
16384may actually be any numeric value. For example, @samp{scf(5,-2) = 0.05}
16385or @samp{1:20} depending on the current Fraction mode.
16386
16387@kindex f [
16388@kindex f ]
16389@pindex calc-decrement
16390@pindex calc-increment
16391@tindex decr
16392@tindex incr
16393The @kbd{f [} (@code{calc-decrement}) [@code{decr}] and @kbd{f ]}
16394(@code{calc-increment}) [@code{incr}] functions decrease or increase
16395a number by one unit. For integers, the effect is obvious. For
16396floating-point numbers, the change is by one unit in the last place.
16397For example, incrementing @samp{12.3456} when the current precision
16398is 6 digits yields @samp{12.3457}. If the current precision had been
163998 digits, the result would have been @samp{12.345601}. Incrementing
40ba43b4 16400@samp{0.0} produces
4009494e 16401@texline @math{10^{-p}},
40ba43b4 16402@infoline @expr{10^-p},
4009494e
GM
16403where @expr{p} is the current
16404precision. These operations are defined only on integers and floats.
16405With numeric prefix arguments, they change the number by @expr{n} units.
16406
16407Note that incrementing followed by decrementing, or vice-versa, will
16408almost but not quite always cancel out. Suppose the precision is
164096 digits and the number @samp{9.99999} is on the stack. Incrementing
16410will produce @samp{10.0000}; decrementing will produce @samp{9.9999}.
16411One digit has been dropped. This is an unavoidable consequence of the
16412way floating-point numbers work.
16413
16414Incrementing a date/time form adjusts it by a certain number of seconds.
16415Incrementing a pure date form adjusts it by a certain number of days.
16416
16417@node Integer Truncation, Complex Number Functions, Basic Arithmetic, Arithmetic
16418@section Integer Truncation
16419
16420@noindent
16421There are four commands for truncating a real number to an integer,
16422differing mainly in their treatment of negative numbers. All of these
16423commands have the property that if the argument is an integer, the result
16424is the same integer. An integer-valued floating-point argument is converted
16425to integer form.
16426
16427If you press @kbd{H} (@code{calc-hyperbolic}) first, the result will be
16428expressed as an integer-valued floating-point number.
16429
16430@cindex Integer part of a number
16431@kindex F
16432@pindex calc-floor
16433@tindex floor
16434@tindex ffloor
16435@ignore
16436@mindex @null
16437@end ignore
16438@kindex H F
16439The @kbd{F} (@code{calc-floor}) [@code{floor} or @code{ffloor}] command
16440truncates a real number to the next lower integer, i.e., toward minus
16441infinity. Thus @kbd{3.6 F} produces 3, but @kbd{_3.6 F} produces
16442@mathit{-4}.
16443
16444@kindex I F
16445@pindex calc-ceiling
16446@tindex ceil
16447@tindex fceil
16448@ignore
16449@mindex @null
16450@end ignore
16451@kindex H I F
16452The @kbd{I F} (@code{calc-ceiling}) [@code{ceil} or @code{fceil}]
16453command truncates toward positive infinity. Thus @kbd{3.6 I F} produces
164544, and @kbd{_3.6 I F} produces @mathit{-3}.
16455
16456@kindex R
16457@pindex calc-round
16458@tindex round
16459@tindex fround
16460@ignore
16461@mindex @null
16462@end ignore
16463@kindex H R
16464The @kbd{R} (@code{calc-round}) [@code{round} or @code{fround}] command
16465rounds to the nearest integer. When the fractional part is .5 exactly,
16466this command rounds away from zero. (All other rounding in the
16467Calculator uses this convention as well.) Thus @kbd{3.5 R} produces 4
16468but @kbd{3.4 R} produces 3; @kbd{_3.5 R} produces @mathit{-4}.
16469
16470@kindex I R
16471@pindex calc-trunc
16472@tindex trunc
16473@tindex ftrunc
16474@ignore
16475@mindex @null
16476@end ignore
16477@kindex H I R
16478The @kbd{I R} (@code{calc-trunc}) [@code{trunc} or @code{ftrunc}]
16479command truncates toward zero. In other words, it ``chops off''
16480everything after the decimal point. Thus @kbd{3.6 I R} produces 3 and
16481@kbd{_3.6 I R} produces @mathit{-3}.
16482
16483These functions may not be applied meaningfully to error forms, but they
16484do work for intervals. As a convenience, applying @code{floor} to a
16485modulo form floors the value part of the form. Applied to a vector,
16486these functions operate on all elements of the vector one by one.
16487Applied to a date form, they operate on the internal numerical
16488representation of dates, converting a date/time form into a pure date.
16489
16490@ignore
16491@starindex
16492@end ignore
16493@tindex rounde
16494@ignore
16495@starindex
16496@end ignore
16497@tindex roundu
16498@ignore
16499@starindex
16500@end ignore
16501@tindex frounde
16502@ignore
16503@starindex
16504@end ignore
16505@tindex froundu
16506There are two more rounding functions which can only be entered in
16507algebraic notation. The @code{roundu} function is like @code{round}
16508except that it rounds up, toward plus infinity, when the fractional
16509part is .5. This distinction matters only for negative arguments.
16510Also, @code{rounde} rounds to an even number in the case of a tie,
16511rounding up or down as necessary. For example, @samp{rounde(3.5)} and
16512@samp{rounde(4.5)} both return 4, but @samp{rounde(5.5)} returns 6.
16513The advantage of round-to-even is that the net error due to rounding
16514after a long calculation tends to cancel out to zero. An important
16515subtle point here is that the number being fed to @code{rounde} will
16516already have been rounded to the current precision before @code{rounde}
16517begins. For example, @samp{rounde(2.500001)} with a current precision
16518of 6 will incorrectly, or at least surprisingly, yield 2 because the
16519argument will first have been rounded down to @expr{2.5} (which
16520@code{rounde} sees as an exact tie between 2 and 3).
16521
16522Each of these functions, when written in algebraic formulas, allows
16523a second argument which specifies the number of digits after the
16524decimal point to keep. For example, @samp{round(123.4567, 2)} will
16525produce the answer 123.46, and @samp{round(123.4567, -1)} will
16526produce 120 (i.e., the cutoff is one digit to the @emph{left} of
16527the decimal point). A second argument of zero is equivalent to
16528no second argument at all.
16529
16530@cindex Fractional part of a number
16531To compute the fractional part of a number (i.e., the amount which, when
16532added to `@tfn{floor(}@var{n}@tfn{)}', will produce @var{n}) just take @var{n}
16533modulo 1 using the @code{%} command.
16534
16535Note also the @kbd{\} (integer quotient), @kbd{f I} (integer logarithm),
16536and @kbd{f Q} (integer square root) commands, which are analogous to
16537@kbd{/}, @kbd{B}, and @kbd{Q}, respectively, except that they take integer
16538arguments and return the result rounded down to an integer.
16539
16540@node Complex Number Functions, Conversions, Integer Truncation, Arithmetic
16541@section Complex Number Functions
16542
16543@noindent
16544@kindex J
16545@pindex calc-conj
16546@tindex conj
16547The @kbd{J} (@code{calc-conj}) [@code{conj}] command computes the
16548complex conjugate of a number. For complex number @expr{a+bi}, the
16549complex conjugate is @expr{a-bi}. If the argument is a real number,
16550this command leaves it the same. If the argument is a vector or matrix,
16551this command replaces each element by its complex conjugate.
16552
16553@kindex G
16554@pindex calc-argument
16555@tindex arg
16556The @kbd{G} (@code{calc-argument}) [@code{arg}] command computes the
16557``argument'' or polar angle of a complex number. For a number in polar
16558notation, this is simply the second component of the pair
16559@texline `@tfn{(}@var{r}@tfn{;}@math{\theta}@tfn{)}'.
16560@infoline `@tfn{(}@var{r}@tfn{;}@var{theta}@tfn{)}'.
16561The result is expressed according to the current angular mode and will
16562be in the range @mathit{-180} degrees (exclusive) to @mathit{+180} degrees
16563(inclusive), or the equivalent range in radians.
16564
16565@pindex calc-imaginary
16566The @code{calc-imaginary} command multiplies the number on the
16567top of the stack by the imaginary number @expr{i = (0,1)}. This
16568command is not normally bound to a key in Calc, but it is available
16569on the @key{IMAG} button in Keypad mode.
16570
16571@kindex f r
16572@pindex calc-re
16573@tindex re
16574The @kbd{f r} (@code{calc-re}) [@code{re}] command replaces a complex number
16575by its real part. This command has no effect on real numbers. (As an
16576added convenience, @code{re} applied to a modulo form extracts
16577the value part.)
16578
16579@kindex f i
16580@pindex calc-im
16581@tindex im
16582The @kbd{f i} (@code{calc-im}) [@code{im}] command replaces a complex number
16583by its imaginary part; real numbers are converted to zero. With a vector
16584or matrix argument, these functions operate element-wise.
16585
16586@ignore
16587@mindex v p
16588@end ignore
16589@kindex v p (complex)
65d0154b 16590@kindex V p (complex)
4009494e
GM
16591@pindex calc-pack
16592The @kbd{v p} (@code{calc-pack}) command can pack the top two numbers on
16593the stack into a composite object such as a complex number. With
16594a prefix argument of @mathit{-1}, it produces a rectangular complex number;
16595with an argument of @mathit{-2}, it produces a polar complex number.
16596(Also, @pxref{Building Vectors}.)
16597
16598@ignore
16599@mindex v u
16600@end ignore
16601@kindex v u (complex)
65d0154b 16602@kindex V u (complex)
4009494e
GM
16603@pindex calc-unpack
16604The @kbd{v u} (@code{calc-unpack}) command takes the complex number
16605(or other composite object) on the top of the stack and unpacks it
16606into its separate components.
16607
16608@node Conversions, Date Arithmetic, Complex Number Functions, Arithmetic
16609@section Conversions
16610
16611@noindent
16612The commands described in this section convert numbers from one form
16613to another; they are two-key sequences beginning with the letter @kbd{c}.
16614
16615@kindex c f
16616@pindex calc-float
16617@tindex pfloat
16618The @kbd{c f} (@code{calc-float}) [@code{pfloat}] command converts the
16619number on the top of the stack to floating-point form. For example,
16620@expr{23} is converted to @expr{23.0}, @expr{3:2} is converted to
16621@expr{1.5}, and @expr{2.3} is left the same. If the value is a composite
16622object such as a complex number or vector, each of the components is
16623converted to floating-point. If the value is a formula, all numbers
16624in the formula are converted to floating-point. Note that depending
16625on the current floating-point precision, conversion to floating-point
16626format may lose information.
16627
16628As a special exception, integers which appear as powers or subscripts
16629are not floated by @kbd{c f}. If you really want to float a power,
16630you can use a @kbd{j s} command to select the power followed by @kbd{c f}.
16631Because @kbd{c f} cannot examine the formula outside of the selection,
16632it does not notice that the thing being floated is a power.
16633@xref{Selecting Subformulas}.
16634
16635The normal @kbd{c f} command is ``pervasive'' in the sense that it
16636applies to all numbers throughout the formula. The @code{pfloat}
16637algebraic function never stays around in a formula; @samp{pfloat(a + 1)}
16638changes to @samp{a + 1.0} as soon as it is evaluated.
16639
16640@kindex H c f
16641@tindex float
16642With the Hyperbolic flag, @kbd{H c f} [@code{float}] operates
16643only on the number or vector of numbers at the top level of its
16644argument. Thus, @samp{float(1)} is 1.0, but @samp{float(a + 1)}
16645is left unevaluated because its argument is not a number.
16646
16647You should use @kbd{H c f} if you wish to guarantee that the final
16648value, once all the variables have been assigned, is a float; you
16649would use @kbd{c f} if you wish to do the conversion on the numbers
16650that appear right now.
16651
16652@kindex c F
16653@pindex calc-fraction
16654@tindex pfrac
16655The @kbd{c F} (@code{calc-fraction}) [@code{pfrac}] command converts a
16656floating-point number into a fractional approximation. By default, it
16657produces a fraction whose decimal representation is the same as the
16658input number, to within the current precision. You can also give a
16659numeric prefix argument to specify a tolerance, either directly, or,
16660if the prefix argument is zero, by using the number on top of the stack
16661as the tolerance. If the tolerance is a positive integer, the fraction
16662is correct to within that many significant figures. If the tolerance is
16663a non-positive integer, it specifies how many digits fewer than the current
16664precision to use. If the tolerance is a floating-point number, the
16665fraction is correct to within that absolute amount.
16666
16667@kindex H c F
16668@tindex frac
16669The @code{pfrac} function is pervasive, like @code{pfloat}.
16670There is also a non-pervasive version, @kbd{H c F} [@code{frac}],
16671which is analogous to @kbd{H c f} discussed above.
16672
16673@kindex c d
16674@pindex calc-to-degrees
16675@tindex deg
16676The @kbd{c d} (@code{calc-to-degrees}) [@code{deg}] command converts a
16677number into degrees form. The value on the top of the stack may be an
16678HMS form (interpreted as degrees-minutes-seconds), or a real number which
16679will be interpreted in radians regardless of the current angular mode.
16680
16681@kindex c r
16682@pindex calc-to-radians
16683@tindex rad
16684The @kbd{c r} (@code{calc-to-radians}) [@code{rad}] command converts an
16685HMS form or angle in degrees into an angle in radians.
16686
16687@kindex c h
16688@pindex calc-to-hms
16689@tindex hms
16690The @kbd{c h} (@code{calc-to-hms}) [@code{hms}] command converts a real
16691number, interpreted according to the current angular mode, to an HMS
16692form describing the same angle. In algebraic notation, the @code{hms}
16693function also accepts three arguments: @samp{hms(@var{h}, @var{m}, @var{s})}.
16694(The three-argument version is independent of the current angular mode.)
16695
16696@pindex calc-from-hms
16697The @code{calc-from-hms} command converts the HMS form on the top of the
16698stack into a real number according to the current angular mode.
16699
16700@kindex c p
16701@kindex I c p
16702@pindex calc-polar
16703@tindex polar
16704@tindex rect
16705The @kbd{c p} (@code{calc-polar}) command converts the complex number on
16706the top of the stack from polar to rectangular form, or from rectangular
16707to polar form, whichever is appropriate. Real numbers are left the same.
16708This command is equivalent to the @code{rect} or @code{polar}
16709functions in algebraic formulas, depending on the direction of
16710conversion. (It uses @code{polar}, except that if the argument is
16711already a polar complex number, it uses @code{rect} instead. The
16712@kbd{I c p} command always uses @code{rect}.)
16713
16714@kindex c c
16715@pindex calc-clean
16716@tindex pclean
16717The @kbd{c c} (@code{calc-clean}) [@code{pclean}] command ``cleans'' the
16718number on the top of the stack. Floating point numbers are re-rounded
16719according to the current precision. Polar numbers whose angular
16720components have strayed from the @mathit{-180} to @mathit{+180} degree range
16721are normalized. (Note that results will be undesirable if the current
16722angular mode is different from the one under which the number was
16723produced!) Integers and fractions are generally unaffected by this
16724operation. Vectors and formulas are cleaned by cleaning each component
16725number (i.e., pervasively).
16726
1dcac243
JB
16727If the simplification mode is set below basic simplification, it is raised
16728for the purposes of this command. Thus, @kbd{c c} applies the basic
16729simplifications even if their automatic application is disabled.
16730@xref{Simplification Modes}.
4009494e
GM
16731
16732@cindex Roundoff errors, correcting
16733A numeric prefix argument to @kbd{c c} sets the floating-point precision
16734to that value for the duration of the command. A positive prefix (of at
16735least 3) sets the precision to the specified value; a negative or zero
16736prefix decreases the precision by the specified amount.
16737
16738@kindex c 0-9
16739@pindex calc-clean-num
16740The keystroke sequences @kbd{c 0} through @kbd{c 9} are equivalent
16741to @kbd{c c} with the corresponding negative prefix argument. If roundoff
16742errors have changed 2.0 into 1.999999, typing @kbd{c 1} to clip off one
16743decimal place often conveniently does the trick.
16744
16745The @kbd{c c} command with a numeric prefix argument, and the @kbd{c 0}
16746through @kbd{c 9} commands, also ``clip'' very small floating-point
16747numbers to zero. If the exponent is less than or equal to the negative
16748of the specified precision, the number is changed to 0.0. For example,
16749if the current precision is 12, then @kbd{c 2} changes the vector
16750@samp{[1e-8, 1e-9, 1e-10, 1e-11]} to @samp{[1e-8, 1e-9, 0, 0]}.
16751Numbers this small generally arise from roundoff noise.
16752
16753If the numbers you are using really are legitimately this small,
16754you should avoid using the @kbd{c 0} through @kbd{c 9} commands.
16755(The plain @kbd{c c} command rounds to the current precision but
16756does not clip small numbers.)
16757
16758One more property of @kbd{c 0} through @kbd{c 9}, and of @kbd{c c} with
16759a prefix argument, is that integer-valued floats are converted to
16760plain integers, so that @kbd{c 1} on @samp{[1., 1.5, 2., 2.5, 3.]}
16761produces @samp{[1, 1.5, 2, 2.5, 3]}. This is not done for huge
16762numbers (@samp{1e100} is technically an integer-valued float, but
16763you wouldn't want it automatically converted to a 100-digit integer).
16764
16765@kindex H c 0-9
16766@kindex H c c
16767@tindex clean
16768With the Hyperbolic flag, @kbd{H c c} and @kbd{H c 0} through @kbd{H c 9}
16769operate non-pervasively [@code{clean}].
16770
16771@node Date Arithmetic, Financial Functions, Conversions, Arithmetic
16772@section Date Arithmetic
16773
16774@noindent
16775@cindex Date arithmetic, additional functions
16776The commands described in this section perform various conversions
16777and calculations involving date forms (@pxref{Date Forms}). They
16778use the @kbd{t} (for time/date) prefix key followed by shifted
16779letters.
16780
16781The simplest date arithmetic is done using the regular @kbd{+} and @kbd{-}
16782commands. In particular, adding a number to a date form advances the
16783date form by a certain number of days; adding an HMS form to a date
16784form advances the date by a certain amount of time; and subtracting two
16785date forms produces a difference measured in days. The commands
16786described here provide additional, more specialized operations on dates.
16787
16788Many of these commands accept a numeric prefix argument; if you give
16789plain @kbd{C-u} as the prefix, these commands will instead take the
16790additional argument from the top of the stack.
16791
16792@menu
16793* Date Conversions::
16794* Date Functions::
16795* Time Zones::
16796* Business Days::
16797@end menu
16798
16799@node Date Conversions, Date Functions, Date Arithmetic, Date Arithmetic
16800@subsection Date Conversions
16801
16802@noindent
16803@kindex t D
16804@pindex calc-date
16805@tindex date
16806The @kbd{t D} (@code{calc-date}) [@code{date}] command converts a
16807date form into a number, measured in days since Jan 1, 1 AD. The
16808result will be an integer if @var{date} is a pure date form, or a
16809fraction or float if @var{date} is a date/time form. Or, if its
16810argument is a number, it converts this number into a date form.
16811
16812With a numeric prefix argument, @kbd{t D} takes that many objects
16813(up to six) from the top of the stack and interprets them in one
16814of the following ways:
16815
16816The @samp{date(@var{year}, @var{month}, @var{day})} function
16817builds a pure date form out of the specified year, month, and
16818day, which must all be integers. @var{Year} is a year number,
16819such as 1991 (@emph{not} the same as 91!). @var{Month} must be
16820an integer in the range 1 to 12; @var{day} must be in the range
168211 to 31. If the specified month has fewer than 31 days and
16822@var{day} is too large, the equivalent day in the following
16823month will be used.
16824
16825The @samp{date(@var{month}, @var{day})} function builds a
16826pure date form using the current year, as determined by the
16827real-time clock.
16828
16829The @samp{date(@var{year}, @var{month}, @var{day}, @var{hms})}
16830function builds a date/time form using an @var{hms} form.
16831
16832The @samp{date(@var{year}, @var{month}, @var{day}, @var{hour},
16833@var{minute}, @var{second})} function builds a date/time form.
16834@var{hour} should be an integer in the range 0 to 23;
16835@var{minute} should be an integer in the range 0 to 59;
16836@var{second} should be any real number in the range @samp{[0 .. 60)}.
16837The last two arguments default to zero if omitted.
16838
16839@kindex t J
16840@pindex calc-julian
16841@tindex julian
16842@cindex Julian day counts, conversions
16843The @kbd{t J} (@code{calc-julian}) [@code{julian}] command converts
16844a date form into a Julian day count, which is the number of days
7c1a0036 16845since noon (GMT) on Jan 1, 4713 BC. A pure date is converted to an
40ba43b4 16846integer Julian count representing noon of that day. A date/time form
7c1a0036 16847is converted to an exact floating-point Julian count, adjusted to
4009494e
GM
16848interpret the date form in the current time zone but the Julian
16849day count in Greenwich Mean Time. A numeric prefix argument allows
16850you to specify the time zone; @pxref{Time Zones}. Use a prefix of
16851zero to suppress the time zone adjustment. Note that pure date forms
16852are never time-zone adjusted.
16853
16854This command can also do the opposite conversion, from a Julian day
16855count (either an integer day, or a floating-point day and time in
16856the GMT zone), into a pure date form or a date/time form in the
16857current or specified time zone.
16858
16859@kindex t U
16860@pindex calc-unix-time
16861@tindex unixtime
16862@cindex Unix time format, conversions
16863The @kbd{t U} (@code{calc-unix-time}) [@code{unixtime}] command
16864converts a date form into a Unix time value, which is the number of
16865seconds since midnight on Jan 1, 1970, or vice-versa. The numeric result
16866will be an integer if the current precision is 12 or less; for higher
333f9019 16867precision, the result may be a float with (@var{precision}@minus{}12)
4009494e
GM
16868digits after the decimal. Just as for @kbd{t J}, the numeric time
16869is interpreted in the GMT time zone and the date form is interpreted
16870in the current or specified zone. Some systems use Unix-like
16871numbering but with the local time zone; give a prefix of zero to
16872suppress the adjustment if so.
16873
16874@kindex t C
16875@pindex calc-convert-time-zones
16876@tindex tzconv
16877@cindex Time Zones, converting between
16878The @kbd{t C} (@code{calc-convert-time-zones}) [@code{tzconv}]
16879command converts a date form from one time zone to another. You
16880are prompted for each time zone name in turn; you can answer with
16881any suitable Calc time zone expression (@pxref{Time Zones}).
16882If you answer either prompt with a blank line, the local time
16883zone is used for that prompt. You can also answer the first
16884prompt with @kbd{$} to take the two time zone names from the
16885stack (and the date to be converted from the third stack level).
16886
16887@node Date Functions, Business Days, Date Conversions, Date Arithmetic
16888@subsection Date Functions
16889
16890@noindent
16891@kindex t N
16892@pindex calc-now
16893@tindex now
16894The @kbd{t N} (@code{calc-now}) [@code{now}] command pushes the
16895current date and time on the stack as a date form. The time is
16896reported in terms of the specified time zone; with no numeric prefix
16897argument, @kbd{t N} reports for the current time zone.
16898
16899@kindex t P
16900@pindex calc-date-part
16901The @kbd{t P} (@code{calc-date-part}) command extracts one part
16902of a date form. The prefix argument specifies the part; with no
16903argument, this command prompts for a part code from 1 to 9.
16904The various part codes are described in the following paragraphs.
16905
16906@tindex year
16907The @kbd{M-1 t P} [@code{year}] function extracts the year number
16908from a date form as an integer, e.g., 1991. This and the
16909following functions will also accept a real number for an
16910argument, which is interpreted as a standard Calc day number.
16911Note that this function will never return zero, since the year
169121 BC immediately precedes the year 1 AD.
16913
16914@tindex month
16915The @kbd{M-2 t P} [@code{month}] function extracts the month number
16916from a date form as an integer in the range 1 to 12.
16917
16918@tindex day
16919The @kbd{M-3 t P} [@code{day}] function extracts the day number
16920from a date form as an integer in the range 1 to 31.
16921
16922@tindex hour
16923The @kbd{M-4 t P} [@code{hour}] function extracts the hour from
16924a date form as an integer in the range 0 (midnight) to 23. Note
16925that 24-hour time is always used. This returns zero for a pure
16926date form. This function (and the following two) also accept
16927HMS forms as input.
16928
16929@tindex minute
16930The @kbd{M-5 t P} [@code{minute}] function extracts the minute
16931from a date form as an integer in the range 0 to 59.
16932
16933@tindex second
16934The @kbd{M-6 t P} [@code{second}] function extracts the second
16935from a date form. If the current precision is 12 or less,
16936the result is an integer in the range 0 to 59. For higher
333f9019 16937precision, the result may instead be a floating-point number.
4009494e
GM
16938
16939@tindex weekday
16940The @kbd{M-7 t P} [@code{weekday}] function extracts the weekday
16941number from a date form as an integer in the range 0 (Sunday)
16942to 6 (Saturday).
16943
16944@tindex yearday
16945The @kbd{M-8 t P} [@code{yearday}] function extracts the day-of-year
16946number from a date form as an integer in the range 1 (January 1)
16947to 366 (December 31 of a leap year).
16948
16949@tindex time
16950The @kbd{M-9 t P} [@code{time}] function extracts the time portion
16951of a date form as an HMS form. This returns @samp{0@@ 0' 0"}
16952for a pure date form.
16953
16954@kindex t M
16955@pindex calc-new-month
16956@tindex newmonth
16957The @kbd{t M} (@code{calc-new-month}) [@code{newmonth}] command
16958computes a new date form that represents the first day of the month
16959specified by the input date. The result is always a pure date
16960form; only the year and month numbers of the input are retained.
16961With a numeric prefix argument @var{n} in the range from 1 to 31,
16962@kbd{t M} computes the @var{n}th day of the month. (If @var{n}
16963is greater than the actual number of days in the month, or if
16964@var{n} is zero, the last day of the month is used.)
16965
16966@kindex t Y
16967@pindex calc-new-year
16968@tindex newyear
16969The @kbd{t Y} (@code{calc-new-year}) [@code{newyear}] command
16970computes a new pure date form that represents the first day of
16971the year specified by the input. The month, day, and time
16972of the input date form are lost. With a numeric prefix argument
16973@var{n} in the range from 1 to 366, @kbd{t Y} computes the
16974@var{n}th day of the year (366 is treated as 365 in non-leap
16975years). A prefix argument of 0 computes the last day of the
16976year (December 31). A negative prefix argument from @mathit{-1} to
16977@mathit{-12} computes the first day of the @var{n}th month of the year.
16978
16979@kindex t W
16980@pindex calc-new-week
16981@tindex newweek
16982The @kbd{t W} (@code{calc-new-week}) [@code{newweek}] command
16983computes a new pure date form that represents the Sunday on or before
16984the input date. With a numeric prefix argument, it can be made to
16985use any day of the week as the starting day; the argument must be in
16986the range from 0 (Sunday) to 6 (Saturday). This function always
16987subtracts between 0 and 6 days from the input date.
16988
16989Here's an example use of @code{newweek}: Find the date of the next
16990Wednesday after a given date. Using @kbd{M-3 t W} or @samp{newweek(d, 3)}
16991will give you the @emph{preceding} Wednesday, so @samp{newweek(d+7, 3)}
16992will give you the following Wednesday. A further look at the definition
16993of @code{newweek} shows that if the input date is itself a Wednesday,
16994this formula will return the Wednesday one week in the future. An
16995exercise for the reader is to modify this formula to yield the same day
16996if the input is already a Wednesday. Another interesting exercise is
16997to preserve the time-of-day portion of the input (@code{newweek} resets
16998the time to midnight; hint:@: how can @code{newweek} be defined in terms
16999of the @code{weekday} function?).
17000
17001@ignore
17002@starindex
17003@end ignore
17004@tindex pwday
17005The @samp{pwday(@var{date})} function (not on any key) computes the
17006day-of-month number of the Sunday on or before @var{date}. With
17007two arguments, @samp{pwday(@var{date}, @var{day})} computes the day
17008number of the Sunday on or before day number @var{day} of the month
17009specified by @var{date}. The @var{day} must be in the range from
170107 to 31; if the day number is greater than the actual number of days
17011in the month, the true number of days is used instead. Thus
17012@samp{pwday(@var{date}, 7)} finds the first Sunday of the month, and
17013@samp{pwday(@var{date}, 31)} finds the last Sunday of the month.
17014With a third @var{weekday} argument, @code{pwday} can be made to look
17015for any day of the week instead of Sunday.
17016
17017@kindex t I
17018@pindex calc-inc-month
17019@tindex incmonth
17020The @kbd{t I} (@code{calc-inc-month}) [@code{incmonth}] command
17021increases a date form by one month, or by an arbitrary number of
17022months specified by a numeric prefix argument. The time portion,
17023if any, of the date form stays the same. The day also stays the
17024same, except that if the new month has fewer days the day
17025number may be reduced to lie in the valid range. For example,
17026@samp{incmonth(<Jan 31, 1991>)} produces @samp{<Feb 28, 1991>}.
17027Because of this, @kbd{t I t I} and @kbd{M-2 t I} do not always give
17028the same results (@samp{<Mar 28, 1991>} versus @samp{<Mar 31, 1991>}
17029in this case).
17030
17031@ignore
17032@starindex
17033@end ignore
17034@tindex incyear
17035The @samp{incyear(@var{date}, @var{step})} function increases
17036a date form by the specified number of years, which may be
17037any positive or negative integer. Note that @samp{incyear(d, n)}
17038is equivalent to @w{@samp{incmonth(d, 12*n)}}, but these do not have
17039simple equivalents in terms of day arithmetic because
17040months and years have varying lengths. If the @var{step}
17041argument is omitted, 1 year is assumed. There is no keyboard
17042command for this function; use @kbd{C-u 12 t I} instead.
17043
17044There is no @code{newday} function at all because @kbd{F} [@code{floor}]
17045serves this purpose. Similarly, instead of @code{incday} and
17046@code{incweek} simply use @expr{d + n} or @expr{d + 7 n}.
17047
17048@xref{Basic Arithmetic}, for the @kbd{f ]} [@code{incr}] command
17049which can adjust a date/time form by a certain number of seconds.
17050
17051@node Business Days, Time Zones, Date Functions, Date Arithmetic
17052@subsection Business Days
17053
17054@noindent
17055Often time is measured in ``business days'' or ``working days,''
17056where weekends and holidays are skipped. Calc's normal date
17057arithmetic functions use calendar days, so that subtracting two
17058consecutive Mondays will yield a difference of 7 days. By contrast,
17059subtracting two consecutive Mondays would yield 5 business days
17060(assuming two-day weekends and the absence of holidays).
17061
17062@kindex t +
17063@kindex t -
17064@tindex badd
17065@tindex bsub
17066@pindex calc-business-days-plus
17067@pindex calc-business-days-minus
17068The @kbd{t +} (@code{calc-business-days-plus}) [@code{badd}]
17069and @kbd{t -} (@code{calc-business-days-minus}) [@code{bsub}]
17070commands perform arithmetic using business days. For @kbd{t +},
17071one argument must be a date form and the other must be a real
17072number (positive or negative). If the number is not an integer,
17073then a certain amount of time is added as well as a number of
17074days; for example, adding 0.5 business days to a time in Friday
17075evening will produce a time in Monday morning. It is also
17076possible to add an HMS form; adding @samp{12@@ 0' 0"} also adds
17077half a business day. For @kbd{t -}, the arguments are either a
17078date form and a number or HMS form, or two date forms, in which
17079case the result is the number of business days between the two
17080dates.
17081
17082@cindex @code{Holidays} variable
17083@vindex Holidays
17084By default, Calc considers any day that is not a Saturday or
17085Sunday to be a business day. You can define any number of
17086additional holidays by editing the variable @code{Holidays}.
17087(There is an @w{@kbd{s H}} convenience command for editing this
17088variable.) Initially, @code{Holidays} contains the vector
17089@samp{[sat, sun]}. Entries in the @code{Holidays} vector may
17090be any of the following kinds of objects:
17091
17092@itemize @bullet
17093@item
17094Date forms (pure dates, not date/time forms). These specify
17095particular days which are to be treated as holidays.
17096
17097@item
17098Intervals of date forms. These specify a range of days, all of
17099which are holidays (e.g., Christmas week). @xref{Interval Forms}.
17100
17101@item
17102Nested vectors of date forms. Each date form in the vector is
17103considered to be a holiday.
17104
17105@item
17106Any Calc formula which evaluates to one of the above three things.
17107If the formula involves the variable @expr{y}, it stands for a
17108yearly repeating holiday; @expr{y} will take on various year
17109numbers like 1992. For example, @samp{date(y, 12, 25)} specifies
17110Christmas day, and @samp{newweek(date(y, 11, 7), 4) + 21} specifies
17111Thanksgiving (which is held on the fourth Thursday of November).
17112If the formula involves the variable @expr{m}, that variable
17113takes on month numbers from 1 to 12: @samp{date(y, m, 15)} is
17114a holiday that takes place on the 15th of every month.
17115
17116@item
17117A weekday name, such as @code{sat} or @code{sun}. This is really
17118a variable whose name is a three-letter, lower-case day name.
17119
17120@item
17121An interval of year numbers (integers). This specifies the span of
17122years over which this holiday list is to be considered valid. Any
17123business-day arithmetic that goes outside this range will result
17124in an error message. Use this if you are including an explicit
17125list of holidays, rather than a formula to generate them, and you
17126want to make sure you don't accidentally go beyond the last point
17127where the holidays you entered are complete. If there is no
17128limiting interval in the @code{Holidays} vector, the default
17129@samp{[1 .. 2737]} is used. (This is the absolute range of years
17130for which Calc's business-day algorithms will operate.)
17131
17132@item
17133An interval of HMS forms. This specifies the span of hours that
17134are to be considered one business day. For example, if this
17135range is @samp{[9@@ 0' 0" .. 17@@ 0' 0"]} (i.e., 9am to 5pm), then
17136the business day is only eight hours long, so that @kbd{1.5 t +}
17137on @samp{<4:00pm Fri Dec 13, 1991>} will add one business day and
17138four business hours to produce @samp{<12:00pm Tue Dec 17, 1991>}.
17139Likewise, @kbd{t -} will now express differences in time as
17140fractions of an eight-hour day. Times before 9am will be treated
17141as 9am by business date arithmetic, and times at or after 5pm will
17142be treated as 4:59:59pm. If there is no HMS interval in @code{Holidays},
17143the full 24-hour day @samp{[0@ 0' 0" .. 24@ 0' 0"]} is assumed.
17144(Regardless of the type of bounds you specify, the interval is
17145treated as inclusive on the low end and exclusive on the high end,
17146so that the work day goes from 9am up to, but not including, 5pm.)
17147@end itemize
17148
17149If the @code{Holidays} vector is empty, then @kbd{t +} and
17150@kbd{t -} will act just like @kbd{+} and @kbd{-} because there will
17151then be no difference between business days and calendar days.
17152
17153Calc expands the intervals and formulas you give into a complete
17154list of holidays for internal use. This is done mainly to make
17155sure it can detect multiple holidays. (For example,
17156@samp{<Jan 1, 1989>} is both New Year's Day and a Sunday, but
17157Calc's algorithms take care to count it only once when figuring
17158the number of holidays between two dates.)
17159
17160Since the complete list of holidays for all the years from 1 to
171612737 would be huge, Calc actually computes only the part of the
17162list between the smallest and largest years that have been involved
17163in business-day calculations so far. Normally, you won't have to
17164worry about this. Keep in mind, however, that if you do one
17165calculation for 1992, and another for 1792, even if both involve
17166only a small range of years, Calc will still work out all the
17167holidays that fall in that 200-year span.
17168
17169If you add a (positive) number of days to a date form that falls on a
17170weekend or holiday, the date form is treated as if it were the most
17171recent business day. (Thus adding one business day to a Friday,
17172Saturday, or Sunday will all yield the following Monday.) If you
17173subtract a number of days from a weekend or holiday, the date is
17174effectively on the following business day. (So subtracting one business
17175day from Saturday, Sunday, or Monday yields the preceding Friday.) The
17176difference between two dates one or both of which fall on holidays
17177equals the number of actual business days between them. These
17178conventions are consistent in the sense that, if you add @var{n}
17179business days to any date, the difference between the result and the
17180original date will come out to @var{n} business days. (It can't be
17181completely consistent though; a subtraction followed by an addition
17182might come out a bit differently, since @kbd{t +} is incapable of
17183producing a date that falls on a weekend or holiday.)
17184
17185@ignore
17186@starindex
17187@end ignore
17188@tindex holiday
17189There is a @code{holiday} function, not on any keys, that takes
17190any date form and returns 1 if that date falls on a weekend or
17191holiday, as defined in @code{Holidays}, or 0 if the date is a
17192business day.
17193
17194@node Time Zones, , Business Days, Date Arithmetic
17195@subsection Time Zones
17196
17197@noindent
17198@cindex Time zones
17199@cindex Daylight saving time
17200Time zones and daylight saving time are a complicated business.
17201The conversions to and from Julian and Unix-style dates automatically
17202compute the correct time zone and daylight saving adjustment to use,
17203provided they can figure out this information. This section describes
17204Calc's time zone adjustment algorithm in detail, in case you want to
17205do conversions in different time zones or in case Calc's algorithms
17206can't determine the right correction to use.
17207
17208Adjustments for time zones and daylight saving time are done by
17209@kbd{t U}, @kbd{t J}, @kbd{t N}, and @kbd{t C}, but not by any other
17210commands. In particular, @samp{<may 1 1991> - <apr 1 1991>} evaluates
17211to exactly 30 days even though there is a daylight-saving
17212transition in between. This is also true for Julian pure dates:
17213@samp{julian(<may 1 1991>) - julian(<apr 1 1991>)}. But Julian
17214and Unix date/times will adjust for daylight saving time: using Calc's
17215default daylight saving time rule (see the explanation below),
17216@samp{julian(<12am may 1 1991>) - julian(<12am apr 1 1991>)}
17217evaluates to @samp{29.95833} (that's 29 days and 23 hours)
17218because one hour was lost when daylight saving commenced on
17219April 7, 1991.
17220
17221In brief, the idiom @samp{julian(@var{date1}) - julian(@var{date2})}
17222computes the actual number of 24-hour periods between two dates, whereas
17223@samp{@var{date1} - @var{date2}} computes the number of calendar
17224days between two dates without taking daylight saving into account.
17225
17226@pindex calc-time-zone
17227@ignore
17228@starindex
17229@end ignore
17230@tindex tzone
17231The @code{calc-time-zone} [@code{tzone}] command converts the time
17232zone specified by its numeric prefix argument into a number of
17233seconds difference from Greenwich mean time (GMT). If the argument
17234is a number, the result is simply that value multiplied by 3600.
17235Typical arguments for North America are 5 (Eastern) or 8 (Pacific). If
17236Daylight Saving time is in effect, one hour should be subtracted from
17237the normal difference.
17238
17239If you give a prefix of plain @kbd{C-u}, @code{calc-time-zone} (like other
17240date arithmetic commands that include a time zone argument) takes the
17241zone argument from the top of the stack. (In the case of @kbd{t J}
17242and @kbd{t U}, the normal argument is then taken from the second-to-top
17243stack position.) This allows you to give a non-integer time zone
17244adjustment. The time-zone argument can also be an HMS form, or
17245it can be a variable which is a time zone name in upper- or lower-case.
17246For example @samp{tzone(PST) = tzone(8)} and @samp{tzone(pdt) = tzone(7)}
17247(for Pacific standard and daylight saving times, respectively).
17248
17249North American and European time zone names are defined as follows;
17250note that for each time zone there is one name for standard time,
17251another for daylight saving time, and a third for ``generalized'' time
17252in which the daylight saving adjustment is computed from context.
17253
17254@smallexample
17255@group
17256YST PST MST CST EST AST NST GMT WET MET MEZ
17257 9 8 7 6 5 4 3.5 0 -1 -2 -2
17258
17259YDT PDT MDT CDT EDT ADT NDT BST WETDST METDST MESZ
17260 8 7 6 5 4 3 2.5 -1 -2 -3 -3
17261
17262YGT PGT MGT CGT EGT AGT NGT BGT WEGT MEGT MEGZ
172639/8 8/7 7/6 6/5 5/4 4/3 3.5/2.5 0/-1 -1/-2 -2/-3 -2/-3
17264@end group
17265@end smallexample
17266
17267@vindex math-tzone-names
17268To define time zone names that do not appear in the above table,
17269you must modify the Lisp variable @code{math-tzone-names}. This
17270is a list of lists describing the different time zone names; its
17271structure is best explained by an example. The three entries for
17272Pacific Time look like this:
17273
17274@smallexample
17275@group
17276( ( "PST" 8 0 ) ; Name as an upper-case string, then standard
17277 ( "PDT" 8 -1 ) ; adjustment, then daylight saving adjustment.
17278 ( "PGT" 8 "PST" "PDT" ) ) ; Generalized time zone.
17279@end group
17280@end smallexample
17281
17282@cindex @code{TimeZone} variable
17283@vindex TimeZone
17284With no arguments, @code{calc-time-zone} or @samp{tzone()} will by
17285default get the time zone and daylight saving information from the
17286calendar (@pxref{Daylight Saving,Calendar/Diary,The Calendar and the Diary,
17287emacs,The GNU Emacs Manual}). To use a different time zone, or if the
40ba43b4 17288calendar does not give the desired result, you can set the Calc variable
4009494e
GM
17289@code{TimeZone} (which is by default @code{nil}) to an appropriate
17290time zone name. (The easiest way to do this is to edit the
17291@code{TimeZone} variable using Calc's @kbd{s T} command, then use the
17292@kbd{s p} (@code{calc-permanent-variable}) command to save the value of
40ba43b4 17293@code{TimeZone} permanently.)
4009494e
GM
17294If the time zone given by @code{TimeZone} is a generalized time zone,
17295e.g., @code{EGT}, Calc examines the date being converted to tell whether
17296to use standard or daylight saving time. But if the current time zone
17297is explicit, e.g., @code{EST} or @code{EDT}, then that adjustment is
17298used exactly and Calc's daylight saving algorithm is not consulted.
17299The special time zone name @code{local}
17300is equivalent to no argument; i.e., it uses the information obtained
17301from the calendar.
17302
17303The @kbd{t J} and @code{t U} commands with no numeric prefix
17304arguments do the same thing as @samp{tzone()}; namely, use the
40ba43b4 17305information from the calendar if @code{TimeZone} is @code{nil},
4009494e
GM
17306otherwise use the time zone given by @code{TimeZone}.
17307
17308@vindex math-daylight-savings-hook
17309@findex math-std-daylight-savings
40ba43b4 17310When Calc computes the daylight saving information itself (i.e., when
4009494e
GM
17311the @code{TimeZone} variable is set), it will by default consider
17312daylight saving time to begin at 2 a.m.@: on the second Sunday of March
17313(for years from 2007 on) or on the last Sunday in April (for years
17314before 2007), and to end at 2 a.m.@: on the first Sunday of
17315November. (for years from 2007 on) or the last Sunday in October (for
17316years before 2007). These are the rules that have been in effect in
17317much of North America since 1966 and take into account the rule change
17318that began in 2007. If you are in a country that uses different rules
17319for computing daylight saving time, you have two choices: Write your own
17320daylight saving hook, or control time zones explicitly by setting the
17321@code{TimeZone} variable and/or always giving a time-zone argument for
17322the conversion functions.
17323
17324The Lisp variable @code{math-daylight-savings-hook} holds the
17325name of a function that is used to compute the daylight saving
17326adjustment for a given date. The default is
17327@code{math-std-daylight-savings}, which computes an adjustment
17328(either 0 or @mathit{-1}) using the North American rules given above.
17329
17330The daylight saving hook function is called with four arguments:
17331The date, as a floating-point number in standard Calc format;
17332a six-element list of the date decomposed into year, month, day,
17333hour, minute, and second, respectively; a string which contains
17334the generalized time zone name in upper-case, e.g., @code{"WEGT"};
17335and a special adjustment to be applied to the hour value when
17336converting into a generalized time zone (see below).
17337
17338@findex math-prev-weekday-in-month
17339The Lisp function @code{math-prev-weekday-in-month} is useful for
17340daylight saving computations. This is an internal version of
17341the user-level @code{pwday} function described in the previous
17342section. It takes four arguments: The floating-point date value,
17343the corresponding six-element date list, the day-of-month number,
17344and the weekday number (0-6).
17345
17346The default daylight saving hook ignores the time zone name, but a
17347more sophisticated hook could use different algorithms for different
17348time zones. It would also be possible to use different algorithms
17349depending on the year number, but the default hook always uses the
17350algorithm for 1987 and later. Here is a listing of the default
17351daylight saving hook:
17352
17353@smallexample
17354(defun math-std-daylight-savings (date dt zone bump)
17355 (cond ((< (nth 1 dt) 4) 0)
17356 ((= (nth 1 dt) 4)
17357 (let ((sunday (math-prev-weekday-in-month date dt 7 0)))
17358 (cond ((< (nth 2 dt) sunday) 0)
17359 ((= (nth 2 dt) sunday)
17360 (if (>= (nth 3 dt) (+ 3 bump)) -1 0))
17361 (t -1))))
17362 ((< (nth 1 dt) 10) -1)
17363 ((= (nth 1 dt) 10)
17364 (let ((sunday (math-prev-weekday-in-month date dt 31 0)))
17365 (cond ((< (nth 2 dt) sunday) -1)
17366 ((= (nth 2 dt) sunday)
17367 (if (>= (nth 3 dt) (+ 2 bump)) 0 -1))
17368 (t 0))))
17369 (t 0))
17370)
17371@end smallexample
17372
17373@noindent
17374The @code{bump} parameter is equal to zero when Calc is converting
17375from a date form in a generalized time zone into a GMT date value.
17376It is @mathit{-1} when Calc is converting in the other direction. The
17377adjustments shown above ensure that the conversion behaves correctly
17378and reasonably around the 2 a.m.@: transition in each direction.
17379
17380There is a ``missing'' hour between 2 a.m.@: and 3 a.m.@: at the
17381beginning of daylight saving time; converting a date/time form that
17382falls in this hour results in a time value for the following hour,
17383from 3 a.m.@: to 4 a.m. At the end of daylight saving time, the
17384hour from 1 a.m.@: to 2 a.m.@: repeats itself; converting a date/time
17385form that falls in this hour results in a time value for the first
40ba43b4 17386manifestation of that time (@emph{not} the one that occurs one hour
4009494e
GM
17387later).
17388
17389If @code{math-daylight-savings-hook} is @code{nil}, then the
17390daylight saving adjustment is always taken to be zero.
17391
17392In algebraic formulas, @samp{tzone(@var{zone}, @var{date})}
17393computes the time zone adjustment for a given zone name at a
17394given date. The @var{date} is ignored unless @var{zone} is a
17395generalized time zone. If @var{date} is a date form, the
17396daylight saving computation is applied to it as it appears.
17397If @var{date} is a numeric date value, it is adjusted for the
17398daylight-saving version of @var{zone} before being given to
17399the daylight saving hook. This odd-sounding rule ensures
17400that the daylight-saving computation is always done in
17401local time, not in the GMT time that a numeric @var{date}
17402is typically represented in.
17403
17404@ignore
17405@starindex
17406@end ignore
17407@tindex dsadj
17408The @samp{dsadj(@var{date}, @var{zone})} function computes the
17409daylight saving adjustment that is appropriate for @var{date} in
17410time zone @var{zone}. If @var{zone} is explicitly in or not in
17411daylight saving time (e.g., @code{PDT} or @code{PST}) the
17412@var{date} is ignored. If @var{zone} is a generalized time zone,
17413the algorithms described above are used. If @var{zone} is omitted,
17414the computation is done for the current time zone.
17415
4009494e
GM
17416@node Financial Functions, Binary Functions, Date Arithmetic, Arithmetic
17417@section Financial Functions
17418
17419@noindent
17420Calc's financial or business functions use the @kbd{b} prefix
17421key followed by a shifted letter. (The @kbd{b} prefix followed by
17422a lower-case letter is used for operations on binary numbers.)
17423
17424Note that the rate and the number of intervals given to these
17425functions must be on the same time scale, e.g., both months or
17426both years. Mixing an annual interest rate with a time expressed
17427in months will give you very wrong answers!
17428
17429It is wise to compute these functions to a higher precision than
17430you really need, just to make sure your answer is correct to the
17431last penny; also, you may wish to check the definitions at the end
17432of this section to make sure the functions have the meaning you expect.
17433
17434@menu
17435* Percentages::
17436* Future Value::
17437* Present Value::
17438* Related Financial Functions::
17439* Depreciation Functions::
17440* Definitions of Financial Functions::
17441@end menu
17442
17443@node Percentages, Future Value, Financial Functions, Financial Functions
17444@subsection Percentages
17445
17446@kindex M-%
17447@pindex calc-percent
17448@tindex %
17449@tindex percent
17450The @kbd{M-%} (@code{calc-percent}) command takes a percentage value,
17451say 5.4, and converts it to an equivalent actual number. For example,
17452@kbd{5.4 M-%} enters 0.054 on the stack. (That's the @key{META} or
17453@key{ESC} key combined with @kbd{%}.)
17454
17455Actually, @kbd{M-%} creates a formula of the form @samp{5.4%}.
17456You can enter @samp{5.4%} yourself during algebraic entry. The
17457@samp{%} operator simply means, ``the preceding value divided by
17458100.'' The @samp{%} operator has very high precedence, so that
17459@samp{1+8%} is interpreted as @samp{1+(8%)}, not as @samp{(1+8)%}.
17460(The @samp{%} operator is just a postfix notation for the
17461@code{percent} function, just like @samp{20!} is the notation for
17462@samp{fact(20)}, or twenty-factorial.)
17463
17464The formula @samp{5.4%} would normally evaluate immediately to
174650.054, but the @kbd{M-%} command suppresses evaluation as it puts
17466the formula onto the stack. However, the next Calc command that
17467uses the formula @samp{5.4%} will evaluate it as its first step.
17468The net effect is that you get to look at @samp{5.4%} on the stack,
17469but Calc commands see it as @samp{0.054}, which is what they expect.
17470
17471In particular, @samp{5.4%} and @samp{0.054} are suitable values
17472for the @var{rate} arguments of the various financial functions,
17473but the number @samp{5.4} is probably @emph{not} suitable---it
17474represents a rate of 540 percent!
17475
17476The key sequence @kbd{M-% *} effectively means ``percent-of.''
17477For example, @kbd{68 @key{RET} 25 M-% *} computes 17, which is 25% of
1747868 (and also 68% of 25, which comes out to the same thing).
17479
17480@kindex c %
17481@pindex calc-convert-percent
17482The @kbd{c %} (@code{calc-convert-percent}) command converts the
17483value on the top of the stack from numeric to percentage form.
17484For example, if 0.08 is on the stack, @kbd{c %} converts it to
17485@samp{8%}. The quantity is the same, it's just represented
17486differently. (Contrast this with @kbd{M-%}, which would convert
17487this number to @samp{0.08%}.) The @kbd{=} key is a convenient way
17488to convert a formula like @samp{8%} back to numeric form, 0.08.
17489
17490To compute what percentage one quantity is of another quantity,
17491use @kbd{/ c %}. For example, @w{@kbd{17 @key{RET} 68 / c %}} displays
17492@samp{25%}.
17493
17494@kindex b %
17495@pindex calc-percent-change
17496@tindex relch
17497The @kbd{b %} (@code{calc-percent-change}) [@code{relch}] command
17498calculates the percentage change from one number to another.
17499For example, @kbd{40 @key{RET} 50 b %} produces the answer @samp{25%},
17500since 50 is 25% larger than 40. A negative result represents a
17501decrease: @kbd{50 @key{RET} 40 b %} produces @samp{-20%}, since 40 is
1750220% smaller than 50. (The answers are different in magnitude
17503because, in the first case, we're increasing by 25% of 40, but
17504in the second case, we're decreasing by 20% of 50.) The effect
17505of @kbd{40 @key{RET} 50 b %} is to compute @expr{(50-40)/40}, converting
17506the answer to percentage form as if by @kbd{c %}.
17507
17508@node Future Value, Present Value, Percentages, Financial Functions
17509@subsection Future Value
17510
17511@noindent
17512@kindex b F
17513@pindex calc-fin-fv
17514@tindex fv
17515The @kbd{b F} (@code{calc-fin-fv}) [@code{fv}] command computes
17516the future value of an investment. It takes three arguments
17517from the stack: @samp{fv(@var{rate}, @var{n}, @var{payment})}.
17518If you give payments of @var{payment} every year for @var{n}
17519years, and the money you have paid earns interest at @var{rate} per
17520year, then this function tells you what your investment would be
17521worth at the end of the period. (The actual interval doesn't
17522have to be years, as long as @var{n} and @var{rate} are expressed
17523in terms of the same intervals.) This function assumes payments
17524occur at the @emph{end} of each interval.
17525
17526@kindex I b F
17527@tindex fvb
17528The @kbd{I b F} [@code{fvb}] command does the same computation,
17529but assuming your payments are at the beginning of each interval.
17530Suppose you plan to deposit $1000 per year in a savings account
17531earning 5.4% interest, starting right now. How much will be
17532in the account after five years? @code{fvb(5.4%, 5, 1000) = 5870.73}.
17533Thus you will have earned $870 worth of interest over the years.
17534Using the stack, this calculation would have been
17535@kbd{5.4 M-% 5 @key{RET} 1000 I b F}. Note that the rate is expressed
17536as a number between 0 and 1, @emph{not} as a percentage.
17537
17538@kindex H b F
17539@tindex fvl
17540The @kbd{H b F} [@code{fvl}] command computes the future value
17541of an initial lump sum investment. Suppose you could deposit
17542those five thousand dollars in the bank right now; how much would
17543they be worth in five years? @code{fvl(5.4%, 5, 5000) = 6503.89}.
17544
17545The algebraic functions @code{fv} and @code{fvb} accept an optional
17546fourth argument, which is used as an initial lump sum in the sense
17547of @code{fvl}. In other words, @code{fv(@var{rate}, @var{n},
17548@var{payment}, @var{initial}) = fv(@var{rate}, @var{n}, @var{payment})
17549+ fvl(@var{rate}, @var{n}, @var{initial})}.
17550
17551To illustrate the relationships between these functions, we could
17552do the @code{fvb} calculation ``by hand'' using @code{fvl}. The
17553final balance will be the sum of the contributions of our five
17554deposits at various times. The first deposit earns interest for
17555five years: @code{fvl(5.4%, 5, 1000) = 1300.78}. The second
17556deposit only earns interest for four years: @code{fvl(5.4%, 4, 1000) =
175571234.13}. And so on down to the last deposit, which earns one
17558year's interest: @code{fvl(5.4%, 1, 1000) = 1054.00}. The sum of
17559these five values is, sure enough, $5870.73, just as was computed
17560by @code{fvb} directly.
17561
17562What does @code{fv(5.4%, 5, 1000) = 5569.96} mean? The payments
17563are now at the ends of the periods. The end of one year is the same
17564as the beginning of the next, so what this really means is that we've
17565lost the payment at year zero (which contributed $1300.78), but we're
17566now counting the payment at year five (which, since it didn't have
17567a chance to earn interest, counts as $1000). Indeed, @expr{5569.96 =
175685870.73 - 1300.78 + 1000} (give or take a bit of roundoff error).
17569
17570@node Present Value, Related Financial Functions, Future Value, Financial Functions
17571@subsection Present Value
17572
17573@noindent
17574@kindex b P
17575@pindex calc-fin-pv
17576@tindex pv
17577The @kbd{b P} (@code{calc-fin-pv}) [@code{pv}] command computes
17578the present value of an investment. Like @code{fv}, it takes
17579three arguments: @code{pv(@var{rate}, @var{n}, @var{payment})}.
17580It computes the present value of a series of regular payments.
17581Suppose you have the chance to make an investment that will
17582pay $2000 per year over the next four years; as you receive
17583these payments you can put them in the bank at 9% interest.
17584You want to know whether it is better to make the investment, or
17585to keep the money in the bank where it earns 9% interest right
17586from the start. The calculation @code{pv(9%, 4, 2000)} gives the
17587result 6479.44. If your initial investment must be less than this,
17588say, $6000, then the investment is worthwhile. But if you had to
17589put up $7000, then it would be better just to leave it in the bank.
17590
17591Here is the interpretation of the result of @code{pv}: You are
17592trying to compare the return from the investment you are
17593considering, which is @code{fv(9%, 4, 2000) = 9146.26}, with
17594the return from leaving the money in the bank, which is
17595@code{fvl(9%, 4, @var{x})} where @var{x} is the amount of money
17596you would have to put up in advance. The @code{pv} function
17597finds the break-even point, @expr{x = 6479.44}, at which
17598@code{fvl(9%, 4, 6479.44)} is also equal to 9146.26. This is
17599the largest amount you should be willing to invest.
17600
17601@kindex I b P
17602@tindex pvb
17603The @kbd{I b P} [@code{pvb}] command solves the same problem,
17604but with payments occurring at the beginning of each interval.
17605It has the same relationship to @code{fvb} as @code{pv} has
17606to @code{fv}. For example @code{pvb(9%, 4, 2000) = 7062.59},
17607a larger number than @code{pv} produced because we get to start
17608earning interest on the return from our investment sooner.
17609
17610@kindex H b P
17611@tindex pvl
17612The @kbd{H b P} [@code{pvl}] command computes the present value of
17613an investment that will pay off in one lump sum at the end of the
17614period. For example, if we get our $8000 all at the end of the
17615four years, @code{pvl(9%, 4, 8000) = 5667.40}. This is much
17616less than @code{pv} reported, because we don't earn any interest
17617on the return from this investment. Note that @code{pvl} and
17618@code{fvl} are simple inverses: @code{fvl(9%, 4, 5667.40) = 8000}.
17619
17620You can give an optional fourth lump-sum argument to @code{pv}
17621and @code{pvb}; this is handled in exactly the same way as the
17622fourth argument for @code{fv} and @code{fvb}.
17623
17624@kindex b N
17625@pindex calc-fin-npv
17626@tindex npv
17627The @kbd{b N} (@code{calc-fin-npv}) [@code{npv}] command computes
17628the net present value of a series of irregular investments.
17629The first argument is the interest rate. The second argument is
17630a vector which represents the expected return from the investment
17631at the end of each interval. For example, if the rate represents
17632a yearly interest rate, then the vector elements are the return
17633from the first year, second year, and so on.
17634
17635Thus, @code{npv(9%, [2000,2000,2000,2000]) = pv(9%, 4, 2000) = 6479.44}.
17636Obviously this function is more interesting when the payments are
17637not all the same!
17638
17639The @code{npv} function can actually have two or more arguments.
17640Multiple arguments are interpreted in the same way as for the
17641vector statistical functions like @code{vsum}.
17642@xref{Single-Variable Statistics}. Basically, if there are several
17643payment arguments, each either a vector or a plain number, all these
17644values are collected left-to-right into the complete list of payments.
17645A numeric prefix argument on the @kbd{b N} command says how many
17646payment values or vectors to take from the stack.
17647
17648@kindex I b N
17649@tindex npvb
17650The @kbd{I b N} [@code{npvb}] command computes the net present
17651value where payments occur at the beginning of each interval
17652rather than at the end.
17653
17654@node Related Financial Functions, Depreciation Functions, Present Value, Financial Functions
17655@subsection Related Financial Functions
17656
17657@noindent
17658The functions in this section are basically inverses of the
17659present value functions with respect to the various arguments.
17660
17661@kindex b M
17662@pindex calc-fin-pmt
17663@tindex pmt
17664The @kbd{b M} (@code{calc-fin-pmt}) [@code{pmt}] command computes
17665the amount of periodic payment necessary to amortize a loan.
17666Thus @code{pmt(@var{rate}, @var{n}, @var{amount})} equals the
17667value of @var{payment} such that @code{pv(@var{rate}, @var{n},
17668@var{payment}) = @var{amount}}.
17669
17670@kindex I b M
17671@tindex pmtb
17672The @kbd{I b M} [@code{pmtb}] command does the same computation
17673but using @code{pvb} instead of @code{pv}. Like @code{pv} and
17674@code{pvb}, these functions can also take a fourth argument which
17675represents an initial lump-sum investment.
17676
17677@kindex H b M
17678The @kbd{H b M} key just invokes the @code{fvl} function, which is
17679the inverse of @code{pvl}. There is no explicit @code{pmtl} function.
17680
17681@kindex b #
17682@pindex calc-fin-nper
17683@tindex nper
17684The @kbd{b #} (@code{calc-fin-nper}) [@code{nper}] command computes
17685the number of regular payments necessary to amortize a loan.
17686Thus @code{nper(@var{rate}, @var{payment}, @var{amount})} equals
17687the value of @var{n} such that @code{pv(@var{rate}, @var{n},
17688@var{payment}) = @var{amount}}. If @var{payment} is too small
17689ever to amortize a loan for @var{amount} at interest rate @var{rate},
17690the @code{nper} function is left in symbolic form.
17691
17692@kindex I b #
17693@tindex nperb
17694The @kbd{I b #} [@code{nperb}] command does the same computation
17695but using @code{pvb} instead of @code{pv}. You can give a fourth
17696lump-sum argument to these functions, but the computation will be
17697rather slow in the four-argument case.
17698
17699@kindex H b #
17700@tindex nperl
17701The @kbd{H b #} [@code{nperl}] command does the same computation
17702using @code{pvl}. By exchanging @var{payment} and @var{amount} you
17703can also get the solution for @code{fvl}. For example,
17704@code{nperl(8%, 2000, 1000) = 9.006}, so if you place $1000 in a
17705bank account earning 8%, it will take nine years to grow to $2000.
17706
17707@kindex b T
17708@pindex calc-fin-rate
17709@tindex rate
17710The @kbd{b T} (@code{calc-fin-rate}) [@code{rate}] command computes
17711the rate of return on an investment. This is also an inverse of @code{pv}:
17712@code{rate(@var{n}, @var{payment}, @var{amount})} computes the value of
17713@var{rate} such that @code{pv(@var{rate}, @var{n}, @var{payment}) =
17714@var{amount}}. The result is expressed as a formula like @samp{6.3%}.
17715
17716@kindex I b T
17717@kindex H b T
17718@tindex rateb
17719@tindex ratel
17720The @kbd{I b T} [@code{rateb}] and @kbd{H b T} [@code{ratel}]
17721commands solve the analogous equations with @code{pvb} or @code{pvl}
17722in place of @code{pv}. Also, @code{rate} and @code{rateb} can
17723accept an optional fourth argument just like @code{pv} and @code{pvb}.
17724To redo the above example from a different perspective,
17725@code{ratel(9, 2000, 1000) = 8.00597%}, which says you will need an
17726interest rate of 8% in order to double your account in nine years.
17727
17728@kindex b I
17729@pindex calc-fin-irr
17730@tindex irr
17731The @kbd{b I} (@code{calc-fin-irr}) [@code{irr}] command is the
17732analogous function to @code{rate} but for net present value.
17733Its argument is a vector of payments. Thus @code{irr(@var{payments})}
17734computes the @var{rate} such that @code{npv(@var{rate}, @var{payments}) = 0};
17735this rate is known as the @dfn{internal rate of return}.
17736
17737@kindex I b I
17738@tindex irrb
17739The @kbd{I b I} [@code{irrb}] command computes the internal rate of
17740return assuming payments occur at the beginning of each period.
17741
17742@node Depreciation Functions, Definitions of Financial Functions, Related Financial Functions, Financial Functions
17743@subsection Depreciation Functions
17744
17745@noindent
17746The functions in this section calculate @dfn{depreciation}, which is
17747the amount of value that a possession loses over time. These functions
17748are characterized by three parameters: @var{cost}, the original cost
17749of the asset; @var{salvage}, the value the asset will have at the end
17750of its expected ``useful life''; and @var{life}, the number of years
17751(or other periods) of the expected useful life.
17752
17753There are several methods for calculating depreciation that differ in
17754the way they spread the depreciation over the lifetime of the asset.
17755
17756@kindex b S
17757@pindex calc-fin-sln
17758@tindex sln
17759The @kbd{b S} (@code{calc-fin-sln}) [@code{sln}] command computes the
17760``straight-line'' depreciation. In this method, the asset depreciates
17761by the same amount every year (or period). For example,
17762@samp{sln(12000, 2000, 5)} returns 2000. The asset costs $12000
17763initially and will be worth $2000 after five years; it loses $2000
17764per year.
17765
17766@kindex b Y
17767@pindex calc-fin-syd
17768@tindex syd
17769The @kbd{b Y} (@code{calc-fin-syd}) [@code{syd}] command computes the
17770accelerated ``sum-of-years'-digits'' depreciation. Here the depreciation
17771is higher during the early years of the asset's life. Since the
17772depreciation is different each year, @kbd{b Y} takes a fourth @var{period}
17773parameter which specifies which year is requested, from 1 to @var{life}.
17774If @var{period} is outside this range, the @code{syd} function will
17775return zero.
17776
17777@kindex b D
17778@pindex calc-fin-ddb
17779@tindex ddb
17780The @kbd{b D} (@code{calc-fin-ddb}) [@code{ddb}] command computes an
17781accelerated depreciation using the double-declining balance method.
17782It also takes a fourth @var{period} parameter.
17783
17784For symmetry, the @code{sln} function will accept a @var{period}
17785parameter as well, although it will ignore its value except that the
17786return value will as usual be zero if @var{period} is out of range.
17787
17788For example, pushing the vector @expr{[1,2,3,4,5]} (perhaps with @kbd{v x 5})
17789and then mapping @kbd{V M ' [sln(12000,2000,5,$), syd(12000,2000,5,$),
17790ddb(12000,2000,5,$)] @key{RET}} produces a matrix that allows us to compare
17791the three depreciation methods:
17792
17793@example
17794@group
17795[ [ 2000, 3333, 4800 ]
17796 [ 2000, 2667, 2880 ]
17797 [ 2000, 2000, 1728 ]
17798 [ 2000, 1333, 592 ]
17799 [ 2000, 667, 0 ] ]
17800@end group
17801@end example
17802
17803@noindent
17804(Values have been rounded to nearest integers in this figure.)
17805We see that @code{sln} depreciates by the same amount each year,
17806@kbd{syd} depreciates more at the beginning and less at the end,
17807and @kbd{ddb} weights the depreciation even more toward the beginning.
17808
17809Summing columns with @kbd{V R : +} yields @expr{[10000, 10000, 10000]};
17810the total depreciation in any method is (by definition) the
17811difference between the cost and the salvage value.
17812
17813@node Definitions of Financial Functions, , Depreciation Functions, Financial Functions
17814@subsection Definitions
17815
17816@noindent
17817For your reference, here are the actual formulas used to compute
17818Calc's financial functions.
17819
17820Calc will not evaluate a financial function unless the @var{rate} or
17821@var{n} argument is known. However, @var{payment} or @var{amount} can
17822be a variable. Calc expands these functions according to the
17823formulas below for symbolic arguments only when you use the @kbd{a "}
17824(@code{calc-expand-formula}) command, or when taking derivatives or
17825integrals or solving equations involving the functions.
17826
17827@ifnottex
17828These formulas are shown using the conventions of Big display
17829mode (@kbd{d B}); for example, the formula for @code{fv} written
17830linearly is @samp{pmt * ((1 + rate)^n) - 1) / rate}.
17831
17832@example
17833 n
17834 (1 + rate) - 1
17835fv(rate, n, pmt) = pmt * ---------------
17836 rate
17837
17838 n
17839 ((1 + rate) - 1) (1 + rate)
17840fvb(rate, n, pmt) = pmt * ----------------------------
17841 rate
17842
17843 n
17844fvl(rate, n, pmt) = pmt * (1 + rate)
17845
17846 -n
17847 1 - (1 + rate)
17848pv(rate, n, pmt) = pmt * ----------------
17849 rate
17850
17851 -n
17852 (1 - (1 + rate) ) (1 + rate)
17853pvb(rate, n, pmt) = pmt * -----------------------------
17854 rate
17855
17856 -n
17857pvl(rate, n, pmt) = pmt * (1 + rate)
17858
17859 -1 -2 -3
17860npv(rate, [a, b, c]) = a*(1 + rate) + b*(1 + rate) + c*(1 + rate)
17861
17862 -1 -2
17863npvb(rate, [a, b, c]) = a + b*(1 + rate) + c*(1 + rate)
17864
17865 -n
17866 (amt - x * (1 + rate) ) * rate
17867pmt(rate, n, amt, x) = -------------------------------
17868 -n
17869 1 - (1 + rate)
17870
17871 -n
17872 (amt - x * (1 + rate) ) * rate
17873pmtb(rate, n, amt, x) = -------------------------------
17874 -n
17875 (1 - (1 + rate) ) (1 + rate)
17876
17877 amt * rate
17878nper(rate, pmt, amt) = - log(1 - ------------, 1 + rate)
17879 pmt
17880
17881 amt * rate
17882nperb(rate, pmt, amt) = - log(1 - ---------------, 1 + rate)
17883 pmt * (1 + rate)
17884
17885 amt
17886nperl(rate, pmt, amt) = - log(---, 1 + rate)
17887 pmt
17888
17889 1/n
17890 pmt
17891ratel(n, pmt, amt) = ------ - 1
17892 1/n
17893 amt
17894
17895 cost - salv
17896sln(cost, salv, life) = -----------
17897 life
17898
17899 (cost - salv) * (life - per + 1)
17900syd(cost, salv, life, per) = --------------------------------
17901 life * (life + 1) / 2
17902
17903 book * 2
17904ddb(cost, salv, life, per) = --------, book = cost - depreciation so far
17905 life
17906@end example
17907@end ifnottex
17908@tex
4009494e
GM
17909$$ \code{fv}(r, n, p) = p { (1 + r)^n - 1 \over r } $$
17910$$ \code{fvb}(r, n, p) = p { ((1 + r)^n - 1) (1 + r) \over r } $$
17911$$ \code{fvl}(r, n, p) = p (1 + r)^n $$
17912$$ \code{pv}(r, n, p) = p { 1 - (1 + r)^{-n} \over r } $$
17913$$ \code{pvb}(r, n, p) = p { (1 - (1 + r)^{-n}) (1 + r) \over r } $$
17914$$ \code{pvl}(r, n, p) = p (1 + r)^{-n} $$
17915$$ \code{npv}(r, [a,b,c]) = a (1 + r)^{-1} + b (1 + r)^{-2} + c (1 + r)^{-3} $$
17916$$ \code{npvb}(r, [a,b,c]) = a + b (1 + r)^{-1} + c (1 + r)^{-2} $$
17917$$ \code{pmt}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over 1 - (1 + r)^{-n} }$$
17918$$ \code{pmtb}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over
17919 (1 - (1 + r)^{-n}) (1 + r) } $$
17920$$ \code{nper}(r, p, a) = -\code{log}(1 - { a r \over p }, 1 + r) $$
17921$$ \code{nperb}(r, p, a) = -\code{log}(1 - { a r \over p (1 + r) }, 1 + r) $$
17922$$ \code{nperl}(r, p, a) = -\code{log}({a \over p}, 1 + r) $$
17923$$ \code{ratel}(n, p, a) = { p^{1/n} \over a^{1/n} } - 1 $$
17924$$ \code{sln}(c, s, l) = { c - s \over l } $$
17925$$ \code{syd}(c, s, l, p) = { (c - s) (l - p + 1) \over l (l+1) / 2 } $$
17926$$ \code{ddb}(c, s, l, p) = { 2 (c - \hbox{depreciation so far}) \over l } $$
17927@end tex
17928
17929@noindent
17930In @code{pmt} and @code{pmtb}, @expr{x=0} if omitted.
17931
17932These functions accept any numeric objects, including error forms,
17933intervals, and even (though not very usefully) complex numbers. The
17934above formulas specify exactly the behavior of these functions with
17935all sorts of inputs.
17936
17937Note that if the first argument to the @code{log} in @code{nper} is
17938negative, @code{nper} leaves itself in symbolic form rather than
17939returning a (financially meaningless) complex number.
17940
17941@samp{rate(num, pmt, amt)} solves the equation
17942@samp{pv(rate, num, pmt) = amt} for @samp{rate} using @kbd{H a R}
17943(@code{calc-find-root}), with the interval @samp{[.01% .. 100%]}
17944for an initial guess. The @code{rateb} function is the same except
17945that it uses @code{pvb}. Note that @code{ratel} can be solved
17946directly; its formula is shown in the above list.
17947
17948Similarly, @samp{irr(pmts)} solves the equation @samp{npv(rate, pmts) = 0}
17949for @samp{rate}.
17950
17951If you give a fourth argument to @code{nper} or @code{nperb}, Calc
17952will also use @kbd{H a R} to solve the equation using an initial
17953guess interval of @samp{[0 .. 100]}.
17954
17955A fourth argument to @code{fv} simply sums the two components
17956calculated from the above formulas for @code{fv} and @code{fvl}.
17957The same is true of @code{fvb}, @code{pv}, and @code{pvb}.
17958
17959The @kbd{ddb} function is computed iteratively; the ``book'' value
17960starts out equal to @var{cost}, and decreases according to the above
17961formula for the specified number of periods. If the book value
17962would decrease below @var{salvage}, it only decreases to @var{salvage}
17963and the depreciation is zero for all subsequent periods. The @code{ddb}
17964function returns the amount the book value decreased in the specified
17965period.
17966
17967@node Binary Functions, , Financial Functions, Arithmetic
17968@section Binary Number Functions
17969
17970@noindent
17971The commands in this chapter all use two-letter sequences beginning with
17972the @kbd{b} prefix.
17973
17974@cindex Binary numbers
17975The ``binary'' operations actually work regardless of the currently
17976displayed radix, although their results make the most sense in a radix
17977like 2, 8, or 16 (as obtained by the @kbd{d 2}, @kbd{d 8}, or @w{@kbd{d 6}}
17978commands, respectively). You may also wish to enable display of leading
17979zeros with @kbd{d z}. @xref{Radix Modes}.
17980
17981@cindex Word size for binary operations
17982The Calculator maintains a current @dfn{word size} @expr{w}, an
17983arbitrary positive or negative integer. For a positive word size, all
17984of the binary operations described here operate modulo @expr{2^w}. In
17985particular, negative arguments are converted to positive integers modulo
17986@expr{2^w} by all binary functions.
17987
17291a1f 17988If the word size is negative, binary operations produce twos-complement
40ba43b4 17989integers from
4009494e 17990@texline @math{-2^{-w-1}}
40ba43b4
PE
17991@infoline @expr{-(2^(-w-1))}
17992to
4009494e 17993@texline @math{2^{-w-1}-1}
40ba43b4 17994@infoline @expr{2^(-w-1)-1}
4009494e
GM
17995inclusive. Either mode accepts inputs in any range; the sign of
17996@expr{w} affects only the results produced.
17997
17998@kindex b c
17999@pindex calc-clip
18000@tindex clip
18001The @kbd{b c} (@code{calc-clip})
18002[@code{clip}] command can be used to clip a number by reducing it modulo
18003@expr{2^w}. The commands described in this chapter automatically clip
18004their results to the current word size. Note that other operations like
18005addition do not use the current word size, since integer addition
18006generally is not ``binary.'' (However, @pxref{Simplification Modes},
18007@code{calc-bin-simplify-mode}.) For example, with a word size of 8
18008bits @kbd{b c} converts a number to the range 0 to 255; with a word
18009size of @mathit{-8} @kbd{b c} converts to the range @mathit{-128} to 127.
18010
18011@kindex b w
18012@pindex calc-word-size
18013The default word size is 32 bits. All operations except the shifts and
18014rotates allow you to specify a different word size for that one
18015operation by giving a numeric prefix argument: @kbd{C-u 8 b c} clips the
18016top of stack to the range 0 to 255 regardless of the current word size.
18017To set the word size permanently, use @kbd{b w} (@code{calc-word-size}).
18018This command displays a prompt with the current word size; press @key{RET}
18019immediately to keep this word size, or type a new word size at the prompt.
18020
18021When the binary operations are written in symbolic form, they take an
18022optional second (or third) word-size parameter. When a formula like
18023@samp{and(a,b)} is finally evaluated, the word size current at that time
18024will be used, but when @samp{and(a,b,-8)} is evaluated, a word size of
18025@mathit{-8} will always be used. A symbolic binary function will be left
18026in symbolic form unless the all of its argument(s) are integers or
18027integer-valued floats.
18028
18029If either or both arguments are modulo forms for which @expr{M} is a
18030power of two, that power of two is taken as the word size unless a
18031numeric prefix argument overrides it. The current word size is never
18032consulted when modulo-power-of-two forms are involved.
18033
18034@kindex b a
18035@pindex calc-and
18036@tindex and
18037The @kbd{b a} (@code{calc-and}) [@code{and}] command computes the bitwise
18038AND of the two numbers on the top of the stack. In other words, for each
18039of the @expr{w} binary digits of the two numbers (pairwise), the corresponding
18040bit of the result is 1 if and only if both input bits are 1:
18041@samp{and(2#1100, 2#1010) = 2#1000}.
18042
18043@kindex b o
18044@pindex calc-or
18045@tindex or
18046The @kbd{b o} (@code{calc-or}) [@code{or}] command computes the bitwise
18047inclusive OR of two numbers. A bit is 1 if either of the input bits, or
18048both, are 1: @samp{or(2#1100, 2#1010) = 2#1110}.
18049
18050@kindex b x
18051@pindex calc-xor
18052@tindex xor
18053The @kbd{b x} (@code{calc-xor}) [@code{xor}] command computes the bitwise
18054exclusive OR of two numbers. A bit is 1 if exactly one of the input bits
18055is 1: @samp{xor(2#1100, 2#1010) = 2#0110}.
18056
18057@kindex b d
18058@pindex calc-diff
18059@tindex diff
18060The @kbd{b d} (@code{calc-diff}) [@code{diff}] command computes the bitwise
18061difference of two numbers; this is defined by @samp{diff(a,b) = and(a,not(b))},
18062so that @samp{diff(2#1100, 2#1010) = 2#0100}.
18063
18064@kindex b n
18065@pindex calc-not
18066@tindex not
18067The @kbd{b n} (@code{calc-not}) [@code{not}] command computes the bitwise
18068NOT of a number. A bit is 1 if the input bit is 0 and vice-versa.
18069
18070@kindex b l
18071@pindex calc-lshift-binary
18072@tindex lsh
18073The @kbd{b l} (@code{calc-lshift-binary}) [@code{lsh}] command shifts a
18074number left by one bit, or by the number of bits specified in the numeric
18075prefix argument. A negative prefix argument performs a logical right shift,
18076in which zeros are shifted in on the left. In symbolic form, @samp{lsh(a)}
18077is short for @samp{lsh(a,1)}, which in turn is short for @samp{lsh(a,n,w)}.
18078Bits shifted ``off the end,'' according to the current word size, are lost.
18079
18080@kindex H b l
18081@kindex H b r
18082@ignore
18083@mindex @idots
18084@end ignore
18085@kindex H b L
18086@ignore
18087@mindex @null
18088@end ignore
18089@kindex H b R
18090@ignore
18091@mindex @null
18092@end ignore
18093@kindex H b t
18094The @kbd{H b l} command also does a left shift, but it takes two arguments
18095from the stack (the value to shift, and, at top-of-stack, the number of
18096bits to shift). This version interprets the prefix argument just like
18097the regular binary operations, i.e., as a word size. The Hyperbolic flag
18098has a similar effect on the rest of the binary shift and rotate commands.
18099
18100@kindex b r
18101@pindex calc-rshift-binary
18102@tindex rsh
18103The @kbd{b r} (@code{calc-rshift-binary}) [@code{rsh}] command shifts a
18104number right by one bit, or by the number of bits specified in the numeric
18105prefix argument: @samp{rsh(a,n) = lsh(a,-n)}.
18106
18107@kindex b L
18108@pindex calc-lshift-arith
18109@tindex ash
18110The @kbd{b L} (@code{calc-lshift-arith}) [@code{ash}] command shifts a
18111number left. It is analogous to @code{lsh}, except that if the shift
18112is rightward (the prefix argument is negative), an arithmetic shift
18113is performed as described below.
18114
18115@kindex b R
18116@pindex calc-rshift-arith
18117@tindex rash
18118The @kbd{b R} (@code{calc-rshift-arith}) [@code{rash}] command performs
18119an ``arithmetic'' shift to the right, in which the leftmost bit (according
18120to the current word size) is duplicated rather than shifting in zeros.
18121This corresponds to dividing by a power of two where the input is interpreted
18122as a signed, twos-complement number. (The distinction between the @samp{rsh}
18123and @samp{rash} operations is totally independent from whether the word
18124size is positive or negative.) With a negative prefix argument, this
18125performs a standard left shift.
18126
18127@kindex b t
18128@pindex calc-rotate-binary
18129@tindex rot
18130The @kbd{b t} (@code{calc-rotate-binary}) [@code{rot}] command rotates a
18131number one bit to the left. The leftmost bit (according to the current
18132word size) is dropped off the left and shifted in on the right. With a
18133numeric prefix argument, the number is rotated that many bits to the left
18134or right.
18135
18136@xref{Set Operations}, for the @kbd{b p} and @kbd{b u} commands that
18137pack and unpack binary integers into sets. (For example, @kbd{b u}
18138unpacks the number @samp{2#11001} to the set of bit-numbers
18139@samp{[0, 3, 4]}.) Type @kbd{b u V #} to count the number of ``1''
18140bits in a binary integer.
18141
18142Another interesting use of the set representation of binary integers
18143is to reverse the bits in, say, a 32-bit integer. Type @kbd{b u} to
18144unpack; type @kbd{31 @key{TAB} -} to replace each bit-number in the set
18145with 31 minus that bit-number; type @kbd{b p} to pack the set back
18146into a binary integer.
18147
18148@node Scientific Functions, Matrix Functions, Arithmetic, Top
18149@chapter Scientific Functions
18150
18151@noindent
18152The functions described here perform trigonometric and other transcendental
18153calculations. They generally produce floating-point answers correct to the
18154full current precision. The @kbd{H} (Hyperbolic) and @kbd{I} (Inverse)
18155flag keys must be used to get some of these functions from the keyboard.
18156
18157@kindex P
18158@pindex calc-pi
18159@cindex @code{pi} variable
18160@vindex pi
18161@kindex H P
18162@cindex @code{e} variable
18163@vindex e
18164@kindex I P
18165@cindex @code{gamma} variable
18166@vindex gamma
18167@cindex Gamma constant, Euler's
18168@cindex Euler's gamma constant
18169@kindex H I P
18170@cindex @code{phi} variable
18171@cindex Phi, golden ratio
18172@cindex Golden ratio
18173One miscellaneous command is shift-@kbd{P} (@code{calc-pi}), which pushes
18174the value of @cpi{} (at the current precision) onto the stack. With the
18175Hyperbolic flag, it pushes the value @expr{e}, the base of natural logarithms.
40ba43b4 18176With the Inverse flag, it pushes Euler's constant
4009494e 18177@texline @math{\gamma}
40ba43b4 18178@infoline @expr{gamma}
4009494e 18179(about 0.5772). With both Inverse and Hyperbolic, it
40ba43b4 18180pushes the ``golden ratio''
4009494e 18181@texline @math{\phi}
40ba43b4 18182@infoline @expr{phi}
4009494e
GM
18183(about 1.618). (At present, Euler's constant is not available
18184to unlimited precision; Calc knows only the first 100 digits.)
18185In Symbolic mode, these commands push the
18186actual variables @samp{pi}, @samp{e}, @samp{gamma}, and @samp{phi},
18187respectively, instead of their values; @pxref{Symbolic Mode}.
18188
18189@ignore
18190@mindex Q
18191@end ignore
18192@ignore
18193@mindex I Q
18194@end ignore
18195@kindex I Q
18196@tindex sqr
18197The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] function is described elsewhere;
18198@pxref{Basic Arithmetic}. With the Inverse flag [@code{sqr}], this command
18199computes the square of the argument.
18200
18201@xref{Prefix Arguments}, for a discussion of the effect of numeric
18202prefix arguments on commands in this chapter which do not otherwise
18203interpret a prefix argument.
18204
18205@menu
18206* Logarithmic Functions::
18207* Trigonometric and Hyperbolic Functions::
18208* Advanced Math Functions::
18209* Branch Cuts::
18210* Random Numbers::
18211* Combinatorial Functions::
18212* Probability Distribution Functions::
18213@end menu
18214
18215@node Logarithmic Functions, Trigonometric and Hyperbolic Functions, Scientific Functions, Scientific Functions
18216@section Logarithmic Functions
18217
18218@noindent
18219@kindex L
18220@pindex calc-ln
18221@tindex ln
18222@ignore
18223@mindex @null
18224@end ignore
18225@kindex I E
18226The shift-@kbd{L} (@code{calc-ln}) [@code{ln}] command computes the natural
18227logarithm of the real or complex number on the top of the stack. With
18228the Inverse flag it computes the exponential function instead, although
18229this is redundant with the @kbd{E} command.
18230
18231@kindex E
18232@pindex calc-exp
18233@tindex exp
18234@ignore
18235@mindex @null
18236@end ignore
18237@kindex I L
18238The shift-@kbd{E} (@code{calc-exp}) [@code{exp}] command computes the
18239exponential, i.e., @expr{e} raised to the power of the number on the stack.
18240The meanings of the Inverse and Hyperbolic flags follow from those for
18241the @code{calc-ln} command.
18242
18243@kindex H L
18244@kindex H E
18245@pindex calc-log10
18246@tindex log10
18247@tindex exp10
18248@ignore
18249@mindex @null
18250@end ignore
18251@kindex H I L
18252@ignore
18253@mindex @null
18254@end ignore
18255@kindex H I E
18256The @kbd{H L} (@code{calc-log10}) [@code{log10}] command computes the common
18257(base-10) logarithm of a number. (With the Inverse flag [@code{exp10}],
18258it raises ten to a given power.) Note that the common logarithm of a
18259complex number is computed by taking the natural logarithm and dividing
40ba43b4 18260by
4009494e
GM
18261@texline @math{\ln10}.
18262@infoline @expr{ln(10)}.
18263
18264@kindex B
18265@kindex I B
18266@pindex calc-log
18267@tindex log
18268@tindex alog
18269The @kbd{B} (@code{calc-log}) [@code{log}] command computes a logarithm
18270to any base. For example, @kbd{1024 @key{RET} 2 B} produces 10, since
18271@texline @math{2^{10} = 1024}.
40ba43b4 18272@infoline @expr{2^10 = 1024}.
4009494e
GM
18273In certain cases like @samp{log(3,9)}, the result
18274will be either @expr{1:2} or @expr{0.5} depending on the current Fraction
18275mode setting. With the Inverse flag [@code{alog}], this command is
18276similar to @kbd{^} except that the order of the arguments is reversed.
18277
18278@kindex f I
18279@pindex calc-ilog
18280@tindex ilog
18281The @kbd{f I} (@code{calc-ilog}) [@code{ilog}] command computes the
18282integer logarithm of a number to any base. The number and the base must
18283themselves be positive integers. This is the true logarithm, rounded
18284down to an integer. Thus @kbd{ilog(x,10)} is 3 for all @expr{x} in the
18285range from 1000 to 9999. If both arguments are positive integers, exact
18286integer arithmetic is used; otherwise, this is equivalent to
18287@samp{floor(log(x,b))}.
18288
18289@kindex f E
18290@pindex calc-expm1
18291@tindex expm1
18292The @kbd{f E} (@code{calc-expm1}) [@code{expm1}] command computes
18293@texline @math{e^x - 1},
40ba43b4 18294@infoline @expr{exp(x)-1},
4009494e 18295but using an algorithm that produces a more accurate
40ba43b4 18296answer when the result is close to zero, i.e., when
4009494e 18297@texline @math{e^x}
40ba43b4 18298@infoline @expr{exp(x)}
4009494e
GM
18299is close to one.
18300
18301@kindex f L
18302@pindex calc-lnp1
18303@tindex lnp1
18304The @kbd{f L} (@code{calc-lnp1}) [@code{lnp1}] command computes
18305@texline @math{\ln(x+1)},
40ba43b4 18306@infoline @expr{ln(x+1)},
4009494e
GM
18307producing a more accurate answer when @expr{x} is close to zero.
18308
18309@node Trigonometric and Hyperbolic Functions, Advanced Math Functions, Logarithmic Functions, Scientific Functions
18310@section Trigonometric/Hyperbolic Functions
18311
18312@noindent
18313@kindex S
18314@pindex calc-sin
18315@tindex sin
18316The shift-@kbd{S} (@code{calc-sin}) [@code{sin}] command computes the sine
18317of an angle or complex number. If the input is an HMS form, it is interpreted
18318as degrees-minutes-seconds; otherwise, the input is interpreted according
18319to the current angular mode. It is best to use Radians mode when operating
18320on complex numbers.
18321
18322Calc's ``units'' mechanism includes angular units like @code{deg},
18323@code{rad}, and @code{grad}. While @samp{sin(45 deg)} is not evaluated
18324all the time, the @kbd{u s} (@code{calc-simplify-units}) command will
18325simplify @samp{sin(45 deg)} by taking the sine of 45 degrees, regardless
18326of the current angular mode. @xref{Basic Operations on Units}.
18327
18328Also, the symbolic variable @code{pi} is not ordinarily recognized in
18329arguments to trigonometric functions, as in @samp{sin(3 pi / 4)}, but
d2bd74ff 18330the default algebraic simplifications recognize many such
4009494e
GM
18331formulas when the current angular mode is Radians @emph{and} Symbolic
18332mode is enabled; this example would be replaced by @samp{sqrt(2) / 2}.
18333@xref{Symbolic Mode}. Beware, this simplification occurs even if you
18334have stored a different value in the variable @samp{pi}; this is one
18335reason why changing built-in variables is a bad idea. Arguments of
18336the form @expr{x} plus a multiple of @cpiover{2} are also simplified.
18337Calc includes similar formulas for @code{cos} and @code{tan}.
18338
8e7046c3 18339Calc's algebraic simplifications know all angles which are integer multiples of
4009494e
GM
18340@cpiover{12}, @cpiover{10}, or @cpiover{8} radians. In Degrees mode,
18341analogous simplifications occur for integer multiples of 15 or 18
18342degrees, and for arguments plus multiples of 90 degrees.
18343
18344@kindex I S
18345@pindex calc-arcsin
18346@tindex arcsin
18347With the Inverse flag, @code{calc-sin} computes an arcsine. This is also
18348available as the @code{calc-arcsin} command or @code{arcsin} algebraic
18349function. The returned argument is converted to degrees, radians, or HMS
18350notation depending on the current angular mode.
18351
18352@kindex H S
18353@pindex calc-sinh
18354@tindex sinh
18355@kindex H I S
18356@pindex calc-arcsinh
18357@tindex arcsinh
18358With the Hyperbolic flag, @code{calc-sin} computes the hyperbolic
18359sine, also available as @code{calc-sinh} [@code{sinh}]. With the
18360Hyperbolic and Inverse flags, it computes the hyperbolic arcsine
18361(@code{calc-arcsinh}) [@code{arcsinh}].
18362
18363@kindex C
18364@pindex calc-cos
18365@tindex cos
18366@ignore
18367@mindex @idots
18368@end ignore
18369@kindex I C
18370@pindex calc-arccos
18371@ignore
18372@mindex @null
18373@end ignore
18374@tindex arccos
18375@ignore
18376@mindex @null
18377@end ignore
18378@kindex H C
18379@pindex calc-cosh
18380@ignore
18381@mindex @null
18382@end ignore
18383@tindex cosh
18384@ignore
18385@mindex @null
18386@end ignore
18387@kindex H I C
18388@pindex calc-arccosh
18389@ignore
18390@mindex @null
18391@end ignore
18392@tindex arccosh
18393@ignore
18394@mindex @null
18395@end ignore
18396@kindex T
18397@pindex calc-tan
18398@ignore
18399@mindex @null
18400@end ignore
18401@tindex tan
18402@ignore
18403@mindex @null
18404@end ignore
18405@kindex I T
18406@pindex calc-arctan
18407@ignore
18408@mindex @null
18409@end ignore
18410@tindex arctan
18411@ignore
18412@mindex @null
18413@end ignore
18414@kindex H T
18415@pindex calc-tanh
18416@ignore
18417@mindex @null
18418@end ignore
18419@tindex tanh
18420@ignore
18421@mindex @null
18422@end ignore
18423@kindex H I T
18424@pindex calc-arctanh
18425@ignore
18426@mindex @null
18427@end ignore
18428@tindex arctanh
18429The shift-@kbd{C} (@code{calc-cos}) [@code{cos}] command computes the cosine
18430of an angle or complex number, and shift-@kbd{T} (@code{calc-tan}) [@code{tan}]
18431computes the tangent, along with all the various inverse and hyperbolic
18432variants of these functions.
18433
18434@kindex f T
18435@pindex calc-arctan2
18436@tindex arctan2
18437The @kbd{f T} (@code{calc-arctan2}) [@code{arctan2}] command takes two
18438numbers from the stack and computes the arc tangent of their ratio. The
18439result is in the full range from @mathit{-180} (exclusive) to @mathit{+180}
18440(inclusive) degrees, or the analogous range in radians. A similar
18441result would be obtained with @kbd{/} followed by @kbd{I T}, but the
18442value would only be in the range from @mathit{-90} to @mathit{+90} degrees
18443since the division loses information about the signs of the two
18444components, and an error might result from an explicit division by zero
18445which @code{arctan2} would avoid. By (arbitrary) definition,
18446@samp{arctan2(0,0)=0}.
18447
18448@pindex calc-sincos
18449@ignore
18450@starindex
18451@end ignore
18452@tindex sincos
18453@ignore
18454@starindex
18455@end ignore
18456@ignore
18457@mindex arc@idots
18458@end ignore
18459@tindex arcsincos
18460The @code{calc-sincos} [@code{sincos}] command computes the sine and
18461cosine of a number, returning them as a vector of the form
18462@samp{[@var{cos}, @var{sin}]}.
18463With the Inverse flag [@code{arcsincos}], this command takes a two-element
18464vector as an argument and computes @code{arctan2} of the elements.
18465(This command does not accept the Hyperbolic flag.)
18466
18467@pindex calc-sec
18468@tindex sec
18469@pindex calc-csc
18470@tindex csc
18471@pindex calc-cot
18472@tindex cot
18473@pindex calc-sech
18474@tindex sech
18475@pindex calc-csch
18476@tindex csch
18477@pindex calc-coth
18478@tindex coth
18479The remaining trigonometric functions, @code{calc-sec} [@code{sec}],
4bb49b43 18480@code{calc-csc} [@code{csc}] and @code{calc-cot} [@code{cot}], are also
4009494e
GM
18481available. With the Hyperbolic flag, these compute their hyperbolic
18482counterparts, which are also available separately as @code{calc-sech}
4bb49b43 18483[@code{sech}], @code{calc-csch} [@code{csch}] and @code{calc-coth}
9c264403 18484[@code{coth}]. (These commands do not accept the Inverse flag.)
4009494e
GM
18485
18486@node Advanced Math Functions, Branch Cuts, Trigonometric and Hyperbolic Functions, Scientific Functions
18487@section Advanced Mathematical Functions
18488
18489@noindent
18490Calc can compute a variety of less common functions that arise in
18491various branches of mathematics. All of the functions described in
18492this section allow arbitrary complex arguments and, except as noted,
333f9019 18493will work to arbitrarily large precision. They can not at present
4009494e
GM
18494handle error forms or intervals as arguments.
18495
18496NOTE: These functions are still experimental. In particular, their
18497accuracy is not guaranteed in all domains. It is advisable to set the
18498current precision comfortably higher than you actually need when
18499using these functions. Also, these functions may be impractically
18500slow for some values of the arguments.
18501
18502@kindex f g
18503@pindex calc-gamma
18504@tindex gamma
18505The @kbd{f g} (@code{calc-gamma}) [@code{gamma}] command computes the Euler
18506gamma function. For positive integer arguments, this is related to the
18507factorial function: @samp{gamma(n+1) = fact(n)}. For general complex
18508arguments the gamma function can be defined by the following definite
40ba43b4 18509integral:
4009494e 18510@texline @math{\Gamma(a) = \int_0^\infty t^{a-1} e^t dt}.
40ba43b4 18511@infoline @expr{gamma(a) = integ(t^(a-1) exp(t), t, 0, inf)}.
4009494e
GM
18512(The actual implementation uses far more efficient computational methods.)
18513
18514@kindex f G
18515@tindex gammaP
18516@ignore
18517@mindex @idots
18518@end ignore
18519@kindex I f G
18520@ignore
18521@mindex @null
18522@end ignore
18523@kindex H f G
18524@ignore
18525@mindex @null
18526@end ignore
18527@kindex H I f G
18528@pindex calc-inc-gamma
18529@ignore
18530@mindex @null
18531@end ignore
18532@tindex gammaQ
18533@ignore
18534@mindex @null
18535@end ignore
18536@tindex gammag
18537@ignore
18538@mindex @null
18539@end ignore
18540@tindex gammaG
18541The @kbd{f G} (@code{calc-inc-gamma}) [@code{gammaP}] command computes
18542the incomplete gamma function, denoted @samp{P(a,x)}. This is defined by
40ba43b4 18543the integral,
4009494e
GM
18544@texline @math{P(a,x) = \left( \int_0^x t^{a-1} e^t dt \right) / \Gamma(a)}.
18545@infoline @expr{gammaP(a,x) = integ(t^(a-1) exp(t), t, 0, x) / gamma(a)}.
18546This implies that @samp{gammaP(a,inf) = 1} for any @expr{a} (see the
18547definition of the normal gamma function).
18548
18549Several other varieties of incomplete gamma function are defined.
18550The complement of @expr{P(a,x)}, called @expr{Q(a,x) = 1-P(a,x)} by
18551some authors, is computed by the @kbd{I f G} [@code{gammaQ}] command.
18552You can think of this as taking the other half of the integral, from
18553@expr{x} to infinity.
18554
18555@ifnottex
18556The functions corresponding to the integrals that define @expr{P(a,x)}
18557and @expr{Q(a,x)} but without the normalizing @expr{1/gamma(a)}
18558factor are called @expr{g(a,x)} and @expr{G(a,x)}, respectively
18559(where @expr{g} and @expr{G} represent the lower- and upper-case Greek
18560letter gamma). You can obtain these using the @kbd{H f G} [@code{gammag}]
18561and @kbd{H I f G} [@code{gammaG}] commands.
18562@end ifnottex
18563@tex
4009494e
GM
18564The functions corresponding to the integrals that define $P(a,x)$
18565and $Q(a,x)$ but without the normalizing $1/\Gamma(a)$
18566factor are called $\gamma(a,x)$ and $\Gamma(a,x)$, respectively.
18567You can obtain these using the \kbd{H f G} [\code{gammag}] and
18568\kbd{I H f G} [\code{gammaG}] commands.
18569@end tex
18570
18571@kindex f b
18572@pindex calc-beta
18573@tindex beta
18574The @kbd{f b} (@code{calc-beta}) [@code{beta}] command computes the
18575Euler beta function, which is defined in terms of the gamma function as
18576@texline @math{B(a,b) = \Gamma(a) \Gamma(b) / \Gamma(a+b)},
40ba43b4 18577@infoline @expr{beta(a,b) = gamma(a) gamma(b) / gamma(a+b)},
4009494e
GM
18578or by
18579@texline @math{B(a,b) = \int_0^1 t^{a-1} (1-t)^{b-1} dt}.
18580@infoline @expr{beta(a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, 1)}.
18581
18582@kindex f B
18583@kindex H f B
18584@pindex calc-inc-beta
18585@tindex betaI
18586@tindex betaB
18587The @kbd{f B} (@code{calc-inc-beta}) [@code{betaI}] command computes
18588the incomplete beta function @expr{I(x,a,b)}. It is defined by
18589@texline @math{I(x,a,b) = \left( \int_0^x t^{a-1} (1-t)^{b-1} dt \right) / B(a,b)}.
18590@infoline @expr{betaI(x,a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, x) / beta(a,b)}.
18591Once again, the @kbd{H} (hyperbolic) prefix gives the corresponding
18592un-normalized version [@code{betaB}].
18593
18594@kindex f e
18595@kindex I f e
18596@pindex calc-erf
18597@tindex erf
18598@tindex erfc
18599The @kbd{f e} (@code{calc-erf}) [@code{erf}] command computes the
40ba43b4 18600error function
4009494e
GM
18601@texline @math{\hbox{erf}(x) = {2 \over \sqrt{\pi}} \int_0^x e^{-t^2} dt}.
18602@infoline @expr{erf(x) = 2 integ(exp(-(t^2)), t, 0, x) / sqrt(pi)}.
18603The complementary error function @kbd{I f e} (@code{calc-erfc}) [@code{erfc}]
18604is the corresponding integral from @samp{x} to infinity; the sum
18605@texline @math{\hbox{erf}(x) + \hbox{erfc}(x) = 1}.
18606@infoline @expr{erf(x) + erfc(x) = 1}.
18607
18608@kindex f j
18609@kindex f y
18610@pindex calc-bessel-J
18611@pindex calc-bessel-Y
18612@tindex besJ
18613@tindex besY
18614The @kbd{f j} (@code{calc-bessel-J}) [@code{besJ}] and @kbd{f y}
18615(@code{calc-bessel-Y}) [@code{besY}] commands compute the Bessel
18616functions of the first and second kinds, respectively.
18617In @samp{besJ(n,x)} and @samp{besY(n,x)} the ``order'' parameter
18618@expr{n} is often an integer, but is not required to be one.
18619Calc's implementation of the Bessel functions currently limits the
18620precision to 8 digits, and may not be exact even to that precision.
18621Use with care!
18622
18623@node Branch Cuts, Random Numbers, Advanced Math Functions, Scientific Functions
18624@section Branch Cuts and Principal Values
18625
18626@noindent
18627@cindex Branch cuts
18628@cindex Principal values
18629All of the logarithmic, trigonometric, and other scientific functions are
18630defined for complex numbers as well as for reals.
18631This section describes the values
18632returned in cases where the general result is a family of possible values.
18633Calc follows section 12.5.3 of Steele's @dfn{Common Lisp, the Language},
18634second edition, in these matters. This section will describe each
18635function briefly; for a more detailed discussion (including some nifty
18636diagrams), consult Steele's book.
18637
18638Note that the branch cuts for @code{arctan} and @code{arctanh} were
5a83c46e
JB
18639changed between the first and second editions of Steele. Recent
18640versions of Calc follow the second edition.
4009494e
GM
18641
18642The new branch cuts exactly match those of the HP-28/48 calculators.
18643They also match those of Mathematica 1.2, except that Mathematica's
18644@code{arctan} cut is always in the right half of the complex plane,
18645and its @code{arctanh} cut is always in the top half of the plane.
18646Calc's cuts are continuous with quadrants I and III for @code{arctan},
18647or II and IV for @code{arctanh}.
18648
18649Note: The current implementations of these functions with complex arguments
18650are designed with proper behavior around the branch cuts in mind, @emph{not}
18651efficiency or accuracy. You may need to increase the floating precision
18652and wait a while to get suitable answers from them.
18653
18654For @samp{sqrt(a+bi)}: When @expr{a<0} and @expr{b} is small but positive
18655or zero, the result is close to the @expr{+i} axis. For @expr{b} small and
18656negative, the result is close to the @expr{-i} axis. The result always lies
18657in the right half of the complex plane.
18658
18659For @samp{ln(a+bi)}: The real part is defined as @samp{ln(abs(a+bi))}.
18660The imaginary part is defined as @samp{arg(a+bi) = arctan2(b,a)}.
18661Thus the branch cuts for @code{sqrt} and @code{ln} both lie on the
18662negative real axis.
18663
18664The following table describes these branch cuts in another way.
18665If the real and imaginary parts of @expr{z} are as shown, then
18666the real and imaginary parts of @expr{f(z)} will be as shown.
18667Here @code{eps} stands for a small positive value; each
18668occurrence of @code{eps} may stand for a different small value.
18669
18670@smallexample
18671 z sqrt(z) ln(z)
18672----------------------------------------
18673 +, 0 +, 0 any, 0
18674 -, 0 0, + any, pi
18675 -, +eps +eps, + +eps, +
18676 -, -eps +eps, - +eps, -
18677@end smallexample
18678
18679For @samp{z1^z2}: This is defined by @samp{exp(ln(z1)*z2)}.
18680One interesting consequence of this is that @samp{(-8)^1:3} does
18681not evaluate to @mathit{-2} as you might expect, but to the complex
18682number @expr{(1., 1.732)}. Both of these are valid cube roots
18683of @mathit{-8} (as is @expr{(1., -1.732)}); Calc chooses a perhaps
18684less-obvious root for the sake of mathematical consistency.
18685
18686For @samp{arcsin(z)}: This is defined by @samp{-i*ln(i*z + sqrt(1-z^2))}.
18687The branch cuts are on the real axis, less than @mathit{-1} and greater than 1.
18688
18689For @samp{arccos(z)}: This is defined by @samp{-i*ln(z + i*sqrt(1-z^2))},
18690or equivalently by @samp{pi/2 - arcsin(z)}. The branch cuts are on
18691the real axis, less than @mathit{-1} and greater than 1.
18692
18693For @samp{arctan(z)}: This is defined by
18694@samp{(ln(1+i*z) - ln(1-i*z)) / (2*i)}. The branch cuts are on the
18695imaginary axis, below @expr{-i} and above @expr{i}.
18696
18697For @samp{arcsinh(z)}: This is defined by @samp{ln(z + sqrt(1+z^2))}.
18698The branch cuts are on the imaginary axis, below @expr{-i} and
18699above @expr{i}.
18700
18701For @samp{arccosh(z)}: This is defined by
18702@samp{ln(z + (z+1)*sqrt((z-1)/(z+1)))}. The branch cut is on the
18703real axis less than 1.
18704
18705For @samp{arctanh(z)}: This is defined by @samp{(ln(1+z) - ln(1-z)) / 2}.
18706The branch cuts are on the real axis, less than @mathit{-1} and greater than 1.
18707
18708The following tables for @code{arcsin}, @code{arccos}, and
18709@code{arctan} assume the current angular mode is Radians. The
18710hyperbolic functions operate independently of the angular mode.
18711
18712@smallexample
18713 z arcsin(z) arccos(z)
18714-------------------------------------------------------
18715 (-1..1), 0 (-pi/2..pi/2), 0 (0..pi), 0
18716 (-1..1), +eps (-pi/2..pi/2), +eps (0..pi), -eps
18717 (-1..1), -eps (-pi/2..pi/2), -eps (0..pi), +eps
18718 <-1, 0 -pi/2, + pi, -
18719 <-1, +eps -pi/2 + eps, + pi - eps, -
18720 <-1, -eps -pi/2 + eps, - pi - eps, +
18721 >1, 0 pi/2, - 0, +
18722 >1, +eps pi/2 - eps, + +eps, -
18723 >1, -eps pi/2 - eps, - +eps, +
18724@end smallexample
18725
18726@smallexample
18727 z arccosh(z) arctanh(z)
18728-----------------------------------------------------
18729 (-1..1), 0 0, (0..pi) any, 0
18730 (-1..1), +eps +eps, (0..pi) any, +eps
18731 (-1..1), -eps +eps, (-pi..0) any, -eps
18732 <-1, 0 +, pi -, pi/2
18733 <-1, +eps +, pi - eps -, pi/2 - eps
18734 <-1, -eps +, -pi + eps -, -pi/2 + eps
18735 >1, 0 +, 0 +, -pi/2
18736 >1, +eps +, +eps +, pi/2 - eps
18737 >1, -eps +, -eps +, -pi/2 + eps
18738@end smallexample
18739
18740@smallexample
18741 z arcsinh(z) arctan(z)
18742-----------------------------------------------------
18743 0, (-1..1) 0, (-pi/2..pi/2) 0, any
18744 0, <-1 -, -pi/2 -pi/2, -
18745 +eps, <-1 +, -pi/2 + eps pi/2 - eps, -
18746 -eps, <-1 -, -pi/2 + eps -pi/2 + eps, -
18747 0, >1 +, pi/2 pi/2, +
18748 +eps, >1 +, pi/2 - eps pi/2 - eps, +
18749 -eps, >1 -, pi/2 - eps -pi/2 + eps, +
18750@end smallexample
18751
18752Finally, the following identities help to illustrate the relationship
18753between the complex trigonometric and hyperbolic functions. They
18754are valid everywhere, including on the branch cuts.
18755
18756@smallexample
18757sin(i*z) = i*sinh(z) arcsin(i*z) = i*arcsinh(z)
18758cos(i*z) = cosh(z) arcsinh(i*z) = i*arcsin(z)
18759tan(i*z) = i*tanh(z) arctan(i*z) = i*arctanh(z)
18760sinh(i*z) = i*sin(z) cosh(i*z) = cos(z)
18761@end smallexample
18762
18763The ``advanced math'' functions (gamma, Bessel, etc.@:) are also defined
18764for general complex arguments, but their branch cuts and principal values
18765are not rigorously specified at present.
18766
18767@node Random Numbers, Combinatorial Functions, Branch Cuts, Scientific Functions
18768@section Random Numbers
18769
18770@noindent
18771@kindex k r
18772@pindex calc-random
18773@tindex random
18774The @kbd{k r} (@code{calc-random}) [@code{random}] command produces
18775random numbers of various sorts.
18776
18777Given a positive numeric prefix argument @expr{M}, it produces a random
40ba43b4 18778integer @expr{N} in the range
4009494e 18779@texline @math{0 \le N < M}.
40ba43b4 18780@infoline @expr{0 <= N < M}.
f10d0e80 18781Each possible value @expr{N} appears with equal probability.
4009494e
GM
18782
18783With no numeric prefix argument, the @kbd{k r} command takes its argument
18784from the stack instead. Once again, if this is a positive integer @expr{M}
18785the result is a random integer less than @expr{M}. However, note that
18786while numeric prefix arguments are limited to six digits or so, an @expr{M}
18787taken from the stack can be arbitrarily large. If @expr{M} is negative,
40ba43b4 18788the result is a random integer in the range
4009494e
GM
18789@texline @math{M < N \le 0}.
18790@infoline @expr{M < N <= 0}.
18791
18792If the value on the stack is a floating-point number @expr{M}, the result
40ba43b4 18793is a random floating-point number @expr{N} in the range
4009494e
GM
18794@texline @math{0 \le N < M}
18795@infoline @expr{0 <= N < M}
40ba43b4 18796or
4009494e 18797@texline @math{M < N \le 0},
40ba43b4 18798@infoline @expr{M < N <= 0},
4009494e
GM
18799according to the sign of @expr{M}.
18800
18801If @expr{M} is zero, the result is a Gaussian-distributed random real
18802number; the distribution has a mean of zero and a standard deviation
18803of one. The algorithm used generates random numbers in pairs; thus,
18804every other call to this function will be especially fast.
18805
40ba43b4 18806If @expr{M} is an error form
4009494e 18807@texline @math{m} @code{+/-} @math{\sigma}
40ba43b4
PE
18808@infoline @samp{m +/- s}
18809where @var{m} and
4009494e 18810@texline @math{\sigma}
40ba43b4 18811@infoline @var{s}
4009494e 18812are both real numbers, the result uses a Gaussian distribution with mean
40ba43b4 18813@var{m} and standard deviation
4009494e
GM
18814@texline @math{\sigma}.
18815@infoline @var{s}.
18816
18817If @expr{M} is an interval form, the lower and upper bounds specify the
18818acceptable limits of the random numbers. If both bounds are integers,
18819the result is a random integer in the specified range. If either bound
18820is floating-point, the result is a random real number in the specified
18821range. If the interval is open at either end, the result will be sure
18822not to equal that end value. (This makes a big difference for integer
18823intervals, but for floating-point intervals it's relatively minor:
18824with a precision of 6, @samp{random([1.0..2.0))} will return any of one
18825million numbers from 1.00000 to 1.99999; @samp{random([1.0..2.0])} may
18826additionally return 2.00000, but the probability of this happening is
18827extremely small.)
18828
18829If @expr{M} is a vector, the result is one element taken at random from
18830the vector. All elements of the vector are given equal probabilities.
18831
18832@vindex RandSeed
18833The sequence of numbers produced by @kbd{k r} is completely random by
18834default, i.e., the sequence is seeded each time you start Calc using
18835the current time and other information. You can get a reproducible
18836sequence by storing a particular ``seed value'' in the Calc variable
18837@code{RandSeed}. Any integer will do for a seed; integers of from 1
18838to 12 digits are good. If you later store a different integer into
18839@code{RandSeed}, Calc will switch to a different pseudo-random
18840sequence. If you ``unstore'' @code{RandSeed}, Calc will re-seed itself
18841from the current time. If you store the same integer that you used
18842before back into @code{RandSeed}, you will get the exact same sequence
18843of random numbers as before.
18844
18845@pindex calc-rrandom
18846The @code{calc-rrandom} command (not on any key) produces a random real
18847number between zero and one. It is equivalent to @samp{random(1.0)}.
18848
18849@kindex k a
18850@pindex calc-random-again
18851The @kbd{k a} (@code{calc-random-again}) command produces another random
18852number, re-using the most recent value of @expr{M}. With a numeric
18853prefix argument @var{n}, it produces @var{n} more random numbers using
18854that value of @expr{M}.
18855
18856@kindex k h
18857@pindex calc-shuffle
18858@tindex shuffle
18859The @kbd{k h} (@code{calc-shuffle}) command produces a vector of several
18860random values with no duplicates. The value on the top of the stack
18861specifies the set from which the random values are drawn, and may be any
18862of the @expr{M} formats described above. The numeric prefix argument
18863gives the length of the desired list. (If you do not provide a numeric
18864prefix argument, the length of the list is taken from the top of the
18865stack, and @expr{M} from second-to-top.)
18866
18867If @expr{M} is a floating-point number, zero, or an error form (so
18868that the random values are being drawn from the set of real numbers)
18869there is little practical difference between using @kbd{k h} and using
18870@kbd{k r} several times. But if the set of possible values consists
18871of just a few integers, or the elements of a vector, then there is
18872a very real chance that multiple @kbd{k r}'s will produce the same
18873number more than once. The @kbd{k h} command produces a vector whose
18874elements are always distinct. (Actually, there is a slight exception:
18875If @expr{M} is a vector, no given vector element will be drawn more
18876than once, but if several elements of @expr{M} are equal, they may
18877each make it into the result vector.)
18878
18879One use of @kbd{k h} is to rearrange a list at random. This happens
18880if the prefix argument is equal to the number of values in the list:
18881@kbd{[1, 1.5, 2, 2.5, 3] 5 k h} might produce the permuted list
18882@samp{[2.5, 1, 1.5, 3, 2]}. As a convenient feature, if the argument
18883@var{n} is negative it is replaced by the size of the set represented
18884by @expr{M}. Naturally, this is allowed only when @expr{M} specifies
18885a small discrete set of possibilities.
18886
18887To do the equivalent of @kbd{k h} but with duplications allowed,
18888given @expr{M} on the stack and with @var{n} just entered as a numeric
18889prefix, use @kbd{v b} to build a vector of copies of @expr{M}, then use
18890@kbd{V M k r} to ``map'' the normal @kbd{k r} function over the
18891elements of this vector. @xref{Matrix Functions}.
18892
18893@menu
18894* Random Number Generator:: (Complete description of Calc's algorithm)
18895@end menu
18896
18897@node Random Number Generator, , Random Numbers, Random Numbers
18898@subsection Random Number Generator
18899
18900Calc's random number generator uses several methods to ensure that
18901the numbers it produces are highly random. Knuth's @emph{Art of
18902Computer Programming}, Volume II, contains a thorough description
18903of the theory of random number generators and their measurement and
18904characterization.
18905
44e97401 18906If @code{RandSeed} has no stored value, Calc calls Emacs's built-in
4009494e
GM
18907@code{random} function to get a stream of random numbers, which it
18908then treats in various ways to avoid problems inherent in the simple
18909random number generators that many systems use to implement @code{random}.
18910
18911When Calc's random number generator is first invoked, it ``seeds''
18912the low-level random sequence using the time of day, so that the
18913random number sequence will be different every time you use Calc.
18914
18915Since Emacs Lisp doesn't specify the range of values that will be
18916returned by its @code{random} function, Calc exercises the function
18917several times to estimate the range. When Calc subsequently uses
18918the @code{random} function, it takes only 10 bits of the result
18919near the most-significant end. (It avoids at least the bottom
18920four bits, preferably more, and also tries to avoid the top two
18921bits.) This strategy works well with the linear congruential
18922generators that are typically used to implement @code{random}.
18923
18924If @code{RandSeed} contains an integer, Calc uses this integer to
18925seed an ``additive congruential'' method (Knuth's algorithm 3.2.2A,
40ba43b4 18926computing
4009494e 18927@texline @math{X_{n-55} - X_{n-24}}.
40ba43b4 18928@infoline @expr{X_n-55 - X_n-24}).
4009494e
GM
18929This method expands the seed
18930value into a large table which is maintained internally; the variable
18931@code{RandSeed} is changed from, e.g., 42 to the vector @expr{[42]}
18932to indicate that the seed has been absorbed into this table. When
18933@code{RandSeed} contains a vector, @kbd{k r} and related commands
18934continue to use the same internal table as last time. There is no
18935way to extract the complete state of the random number generator
18936so that you can restart it from any point; you can only restart it
18937from the same initial seed value. A simple way to restart from the
18938same seed is to type @kbd{s r RandSeed} to get the seed vector,
18939@kbd{v u} to unpack it back into a number, then @kbd{s t RandSeed}
18940to reseed the generator with that number.
18941
18942Calc uses a ``shuffling'' method as described in algorithm 3.2.2B
18943of Knuth. It fills a table with 13 random 10-bit numbers. Then,
18944to generate a new random number, it uses the previous number to
18945index into the table, picks the value it finds there as the new
18946random number, then replaces that table entry with a new value
18947obtained from a call to the base random number generator (either
18948the additive congruential generator or the @code{random} function
18949supplied by the system). If there are any flaws in the base
18950generator, shuffling will tend to even them out. But if the system
18951provides an excellent @code{random} function, shuffling will not
18952damage its randomness.
18953
18954To create a random integer of a certain number of digits, Calc
18955builds the integer three decimal digits at a time. For each group
18956of three digits, Calc calls its 10-bit shuffling random number generator
18957(which returns a value from 0 to 1023); if the random value is 1000
18958or more, Calc throws it out and tries again until it gets a suitable
18959value.
18960
18961To create a random floating-point number with precision @var{p}, Calc
18962simply creates a random @var{p}-digit integer and multiplies by
18963@texline @math{10^{-p}}.
40ba43b4 18964@infoline @expr{10^-p}.
4009494e
GM
18965The resulting random numbers should be very clean, but note
18966that relatively small numbers will have few significant random digits.
18967In other words, with a precision of 12, you will occasionally get
40ba43b4 18968numbers on the order of
4009494e 18969@texline @math{10^{-9}}
40ba43b4
PE
18970@infoline @expr{10^-9}
18971or
4009494e 18972@texline @math{10^{-10}},
40ba43b4 18973@infoline @expr{10^-10},
4009494e 18974but those numbers will only have two or three random digits since they
40ba43b4 18975correspond to small integers times
4009494e
GM
18976@texline @math{10^{-12}}.
18977@infoline @expr{10^-12}.
18978
18979To create a random integer in the interval @samp{[0 .. @var{m})}, Calc
18980counts the digits in @var{m}, creates a random integer with three
18981additional digits, then reduces modulo @var{m}. Unless @var{m} is a
18982power of ten the resulting values will be very slightly biased toward
18983the lower numbers, but this bias will be less than 0.1%. (For example,
18984if @var{m} is 42, Calc will reduce a random integer less than 100000
18985modulo 42 to get a result less than 42. It is easy to show that the
18986numbers 40 and 41 will be only 2380/2381 as likely to result from this
18987modulo operation as numbers 39 and below.) If @var{m} is a power of
18988ten, however, the numbers should be completely unbiased.
18989
18990The Gaussian random numbers generated by @samp{random(0.0)} use the
18991``polar'' method described in Knuth section 3.4.1C. This method
18992generates a pair of Gaussian random numbers at a time, so only every
18993other call to @samp{random(0.0)} will require significant calculations.
18994
18995@node Combinatorial Functions, Probability Distribution Functions, Random Numbers, Scientific Functions
18996@section Combinatorial Functions
18997
18998@noindent
18999Commands relating to combinatorics and number theory begin with the
19000@kbd{k} key prefix.
19001
19002@kindex k g
19003@pindex calc-gcd
19004@tindex gcd
19005The @kbd{k g} (@code{calc-gcd}) [@code{gcd}] command computes the
19006Greatest Common Divisor of two integers. It also accepts fractions;
19007the GCD of two fractions is defined by taking the GCD of the
19008numerators, and the LCM of the denominators. This definition is
19009consistent with the idea that @samp{a / gcd(a,x)} should yield an
19010integer for any @samp{a} and @samp{x}. For other types of arguments,
19011the operation is left in symbolic form.
19012
19013@kindex k l
19014@pindex calc-lcm
19015@tindex lcm
19016The @kbd{k l} (@code{calc-lcm}) [@code{lcm}] command computes the
19017Least Common Multiple of two integers or fractions. The product of
19018the LCM and GCD of two numbers is equal to the product of the
19019numbers.
19020
19021@kindex k E
19022@pindex calc-extended-gcd
19023@tindex egcd
19024The @kbd{k E} (@code{calc-extended-gcd}) [@code{egcd}] command computes
19025the GCD of two integers @expr{x} and @expr{y} and returns a vector
40ba43b4 19026@expr{[g, a, b]} where
4009494e
GM
19027@texline @math{g = \gcd(x,y) = a x + b y}.
19028@infoline @expr{g = gcd(x,y) = a x + b y}.
19029
19030@kindex !
19031@pindex calc-factorial
19032@tindex fact
19033@ignore
19034@mindex @null
19035@end ignore
19036@tindex !
19037The @kbd{!} (@code{calc-factorial}) [@code{fact}] command computes the
19038factorial of the number at the top of the stack. If the number is an
19039integer, the result is an exact integer. If the number is an
19040integer-valued float, the result is a floating-point approximation. If
19041the number is a non-integral real number, the generalized factorial is used,
19042as defined by the Euler Gamma function. Please note that computation of
19043large factorials can be slow; using floating-point format will help
19044since fewer digits must be maintained. The same is true of many of
19045the commands in this section.
19046
19047@kindex k d
19048@pindex calc-double-factorial
19049@tindex dfact
19050@ignore
19051@mindex @null
19052@end ignore
19053@tindex !!
19054The @kbd{k d} (@code{calc-double-factorial}) [@code{dfact}] command
19055computes the ``double factorial'' of an integer. For an even integer,
19056this is the product of even integers from 2 to @expr{N}. For an odd
19057integer, this is the product of odd integers from 3 to @expr{N}. If
19058the argument is an integer-valued float, the result is a floating-point
19059approximation. This function is undefined for negative even integers.
19060The notation @expr{N!!} is also recognized for double factorials.
19061
19062@kindex k c
19063@pindex calc-choose
19064@tindex choose
19065The @kbd{k c} (@code{calc-choose}) [@code{choose}] command computes the
19066binomial coefficient @expr{N}-choose-@expr{M}, where @expr{M} is the number
19067on the top of the stack and @expr{N} is second-to-top. If both arguments
19068are integers, the result is an exact integer. Otherwise, the result is a
19069floating-point approximation. The binomial coefficient is defined for all
19070real numbers by
19071@texline @math{N! \over M! (N-M)!\,}.
19072@infoline @expr{N! / M! (N-M)!}.
19073
19074@kindex H k c
19075@pindex calc-perm
19076@tindex perm
19077@ifnottex
19078The @kbd{H k c} (@code{calc-perm}) [@code{perm}] command computes the
19079number-of-permutations function @expr{N! / (N-M)!}.
19080@end ifnottex
19081@tex
19082The \kbd{H k c} (\code{calc-perm}) [\code{perm}] command computes the
19083number-of-perm\-utations function $N! \over (N-M)!\,$.
19084@end tex
19085
19086@kindex k b
19087@kindex H k b
19088@pindex calc-bernoulli-number
19089@tindex bern
19090The @kbd{k b} (@code{calc-bernoulli-number}) [@code{bern}] command
19091computes a given Bernoulli number. The value at the top of the stack
19092is a nonnegative integer @expr{n} that specifies which Bernoulli number
19093is desired. The @kbd{H k b} command computes a Bernoulli polynomial,
19094taking @expr{n} from the second-to-top position and @expr{x} from the
19095top of the stack. If @expr{x} is a variable or formula the result is
19096a polynomial in @expr{x}; if @expr{x} is a number the result is a number.
19097
19098@kindex k e
19099@kindex H k e
19100@pindex calc-euler-number
19101@tindex euler
19102The @kbd{k e} (@code{calc-euler-number}) [@code{euler}] command similarly
19103computes an Euler number, and @w{@kbd{H k e}} computes an Euler polynomial.
19104Bernoulli and Euler numbers occur in the Taylor expansions of several
19105functions.
19106
19107@kindex k s
19108@kindex H k s
19109@pindex calc-stirling-number
19110@tindex stir1
19111@tindex stir2
19112The @kbd{k s} (@code{calc-stirling-number}) [@code{stir1}] command
40ba43b4 19113computes a Stirling number of the first
4009494e
GM
19114@texline kind@tie{}@math{n \brack m},
19115@infoline kind,
19116given two integers @expr{n} and @expr{m} on the stack. The @kbd{H k s}
40ba43b4 19117[@code{stir2}] command computes a Stirling number of the second
4009494e
GM
19118@texline kind@tie{}@math{n \brace m}.
19119@infoline kind.
19120These are the number of @expr{m}-cycle permutations of @expr{n} objects,
19121and the number of ways to partition @expr{n} objects into @expr{m}
19122non-empty sets, respectively.
19123
19124@kindex k p
19125@pindex calc-prime-test
19126@cindex Primes
19127The @kbd{k p} (@code{calc-prime-test}) command checks if the integer on
19128the top of the stack is prime. For integers less than eight million, the
19129answer is always exact and reasonably fast. For larger integers, a
19130probabilistic method is used (see Knuth vol. II, section 4.5.4, algorithm P).
19131The number is first checked against small prime factors (up to 13). Then,
19132any number of iterations of the algorithm are performed. Each step either
19133discovers that the number is non-prime, or substantially increases the
19134certainty that the number is prime. After a few steps, the chance that
19135a number was mistakenly described as prime will be less than one percent.
19136(Indeed, this is a worst-case estimate of the probability; in practice
19137even a single iteration is quite reliable.) After the @kbd{k p} command,
19138the number will be reported as definitely prime or non-prime if possible,
19139or otherwise ``probably'' prime with a certain probability of error.
19140
19141@ignore
19142@starindex
19143@end ignore
19144@tindex prime
19145The normal @kbd{k p} command performs one iteration of the primality
19146test. Pressing @kbd{k p} repeatedly for the same integer will perform
19147additional iterations. Also, @kbd{k p} with a numeric prefix performs
19148the specified number of iterations. There is also an algebraic function
19149@samp{prime(n)} or @samp{prime(n,iters)} which returns 1 if @expr{n}
19150is (probably) prime and 0 if not.
19151
19152@kindex k f
19153@pindex calc-prime-factors
19154@tindex prfac
19155The @kbd{k f} (@code{calc-prime-factors}) [@code{prfac}] command
19156attempts to decompose an integer into its prime factors. For numbers up
19157to 25 million, the answer is exact although it may take some time. The
19158result is a vector of the prime factors in increasing order. For larger
19159inputs, prime factors above 5000 may not be found, in which case the
19160last number in the vector will be an unfactored integer greater than 25
19161million (with a warning message). For negative integers, the first
19162element of the list will be @mathit{-1}. For inputs @mathit{-1}, @mathit{0}, and
19163@mathit{1}, the result is a list of the same number.
19164
19165@kindex k n
19166@pindex calc-next-prime
19167@ignore
19168@mindex nextpr@idots
19169@end ignore
19170@tindex nextprime
19171The @kbd{k n} (@code{calc-next-prime}) [@code{nextprime}] command finds
19172the next prime above a given number. Essentially, it searches by calling
19173@code{calc-prime-test} on successive integers until it finds one that
19174passes the test. This is quite fast for integers less than eight million,
19175but once the probabilistic test comes into play the search may be rather
19176slow. Ordinarily this command stops for any prime that passes one iteration
19177of the primality test. With a numeric prefix argument, a number must pass
19178the specified number of iterations before the search stops. (This only
19179matters when searching above eight million.) You can always use additional
19180@kbd{k p} commands to increase your certainty that the number is indeed
19181prime.
19182
19183@kindex I k n
19184@pindex calc-prev-prime
19185@ignore
19186@mindex prevpr@idots
19187@end ignore
19188@tindex prevprime
19189The @kbd{I k n} (@code{calc-prev-prime}) [@code{prevprime}] command
19190analogously finds the next prime less than a given number.
19191
19192@kindex k t
19193@pindex calc-totient
19194@tindex totient
19195The @kbd{k t} (@code{calc-totient}) [@code{totient}] command computes the
40ba43b4 19196Euler ``totient''
4009494e
GM
19197@texline function@tie{}@math{\phi(n)},
19198@infoline function,
19199the number of integers less than @expr{n} which
19200are relatively prime to @expr{n}.
19201
19202@kindex k m
19203@pindex calc-moebius
19204@tindex moebius
19205The @kbd{k m} (@code{calc-moebius}) [@code{moebius}] command computes the
19206@texline M@"obius @math{\mu}
19207@infoline Moebius ``mu''
19208function. If the input number is a product of @expr{k}
19209distinct factors, this is @expr{(-1)^k}. If the input number has any
19210duplicate factors (i.e., can be divided by the same prime more than once),
19211the result is zero.
19212
19213@node Probability Distribution Functions, , Combinatorial Functions, Scientific Functions
19214@section Probability Distribution Functions
19215
19216@noindent
19217The functions in this section compute various probability distributions.
19218For continuous distributions, this is the integral of the probability
19219density function from @expr{x} to infinity. (These are the ``upper
19220tail'' distribution functions; there are also corresponding ``lower
19221tail'' functions which integrate from minus infinity to @expr{x}.)
19222For discrete distributions, the upper tail function gives the sum
19223from @expr{x} to infinity; the lower tail function gives the sum
19224from minus infinity up to, but not including,@w{ }@expr{x}.
19225
19226To integrate from @expr{x} to @expr{y}, just use the distribution
19227function twice and subtract. For example, the probability that a
19228Gaussian random variable with mean 2 and standard deviation 1 will
19229lie in the range from 2.5 to 2.8 is @samp{utpn(2.5,2,1) - utpn(2.8,2,1)}
19230(``the probability that it is greater than 2.5, but not greater than 2.8''),
19231or equivalently @samp{ltpn(2.8,2,1) - ltpn(2.5,2,1)}.
19232
19233@kindex k B
19234@kindex I k B
19235@pindex calc-utpb
19236@tindex utpb
19237@tindex ltpb
19238The @kbd{k B} (@code{calc-utpb}) [@code{utpb}] function uses the
19239binomial distribution. Push the parameters @var{n}, @var{p}, and
19240then @var{x} onto the stack; the result (@samp{utpb(x,n,p)}) is the
19241probability that an event will occur @var{x} or more times out
19242of @var{n} trials, if its probability of occurring in any given
19243trial is @var{p}. The @kbd{I k B} [@code{ltpb}] function is
19244the probability that the event will occur fewer than @var{x} times.
19245
19246The other probability distribution functions similarly take the
19247form @kbd{k @var{X}} (@code{calc-utp@var{x}}) [@code{utp@var{x}}]
19248and @kbd{I k @var{X}} [@code{ltp@var{x}}], for various letters
19249@var{x}. The arguments to the algebraic functions are the value of
19250the random variable first, then whatever other parameters define the
19251distribution. Note these are among the few Calc functions where the
19252order of the arguments in algebraic form differs from the order of
19253arguments as found on the stack. (The random variable comes last on
19254the stack, so that you can type, e.g., @kbd{2 @key{RET} 1 @key{RET} 2.5
19255k N M-@key{RET} @key{DEL} 2.8 k N -}, using @kbd{M-@key{RET} @key{DEL}} to
19256recover the original arguments but substitute a new value for @expr{x}.)
19257
19258@kindex k C
19259@pindex calc-utpc
19260@tindex utpc
19261@ignore
19262@mindex @idots
19263@end ignore
19264@kindex I k C
19265@ignore
19266@mindex @null
19267@end ignore
19268@tindex ltpc
19269The @samp{utpc(x,v)} function uses the chi-square distribution with
19270@texline @math{\nu}
40ba43b4 19271@infoline @expr{v}
4009494e
GM
19272degrees of freedom. It is the probability that a model is
19273correct if its chi-square statistic is @expr{x}.
19274
19275@kindex k F
19276@pindex calc-utpf
19277@tindex utpf
19278@ignore
19279@mindex @idots
19280@end ignore
19281@kindex I k F
19282@ignore
19283@mindex @null
19284@end ignore
19285@tindex ltpf
19286The @samp{utpf(F,v1,v2)} function uses the F distribution, used in
40ba43b4 19287various statistical tests. The parameters
4009494e 19288@texline @math{\nu_1}
40ba43b4
PE
19289@infoline @expr{v1}
19290and
4009494e
GM
19291@texline @math{\nu_2}
19292@infoline @expr{v2}
19293are the degrees of freedom in the numerator and denominator,
19294respectively, used in computing the statistic @expr{F}.
19295
19296@kindex k N
19297@pindex calc-utpn
19298@tindex utpn
19299@ignore
19300@mindex @idots
19301@end ignore
19302@kindex I k N
19303@ignore
19304@mindex @null
19305@end ignore
19306@tindex ltpn
19307The @samp{utpn(x,m,s)} function uses a normal (Gaussian) distribution
40ba43b4 19308with mean @expr{m} and standard deviation
4009494e 19309@texline @math{\sigma}.
40ba43b4 19310@infoline @expr{s}.
4009494e
GM
19311It is the probability that such a normal-distributed random variable
19312would exceed @expr{x}.
19313
19314@kindex k P
19315@pindex calc-utpp
19316@tindex utpp
19317@ignore
19318@mindex @idots
19319@end ignore
19320@kindex I k P
19321@ignore
19322@mindex @null
19323@end ignore
19324@tindex ltpp
19325The @samp{utpp(n,x)} function uses a Poisson distribution with
19326mean @expr{x}. It is the probability that @expr{n} or more such
19327Poisson random events will occur.
19328
19329@kindex k T
19330@pindex calc-ltpt
19331@tindex utpt
19332@ignore
19333@mindex @idots
19334@end ignore
19335@kindex I k T
19336@ignore
19337@mindex @null
19338@end ignore
19339@tindex ltpt
19340The @samp{utpt(t,v)} function uses the Student's ``t'' distribution
40ba43b4 19341with
4009494e 19342@texline @math{\nu}
40ba43b4 19343@infoline @expr{v}
4009494e
GM
19344degrees of freedom. It is the probability that a
19345t-distributed random variable will be greater than @expr{t}.
40ba43b4 19346(Note: This computes the distribution function
4009494e
GM
19347@texline @math{A(t|\nu)}
19348@infoline @expr{A(t|v)}
40ba43b4 19349where
4009494e 19350@texline @math{A(0|\nu) = 1}
40ba43b4
PE
19351@infoline @expr{A(0|v) = 1}
19352and
4009494e 19353@texline @math{A(\infty|\nu) \to 0}.
40ba43b4 19354@infoline @expr{A(inf|v) -> 0}.
4009494e
GM
19355The @code{UTPT} operation on the HP-48 uses a different definition which
19356returns half of Calc's value: @samp{UTPT(t,v) = .5*utpt(t,v)}.)
19357
19358While Calc does not provide inverses of the probability distribution
19359functions, the @kbd{a R} command can be used to solve for the inverse.
19360Since the distribution functions are monotonic, @kbd{a R} is guaranteed
19361to be able to find a solution given any initial guess.
19362@xref{Numerical Solutions}.
19363
19364@node Matrix Functions, Algebra, Scientific Functions, Top
19365@chapter Vector/Matrix Functions
19366
19367@noindent
19368Many of the commands described here begin with the @kbd{v} prefix.
19369(For convenience, the shift-@kbd{V} prefix is equivalent to @kbd{v}.)
19370The commands usually apply to both plain vectors and matrices; some
19371apply only to matrices or only to square matrices. If the argument
19372has the wrong dimensions the operation is left in symbolic form.
19373
19374Vectors are entered and displayed using @samp{[a,b,c]} notation.
19375Matrices are vectors of which all elements are vectors of equal length.
19376(Though none of the standard Calc commands use this concept, a
19377three-dimensional matrix or rank-3 tensor could be defined as a
19378vector of matrices, and so on.)
19379
19380@menu
19381* Packing and Unpacking::
19382* Building Vectors::
19383* Extracting Elements::
19384* Manipulating Vectors::
19385* Vector and Matrix Arithmetic::
19386* Set Operations::
19387* Statistical Operations::
19388* Reducing and Mapping::
19389* Vector and Matrix Formats::
19390@end menu
19391
19392@node Packing and Unpacking, Building Vectors, Matrix Functions, Matrix Functions
19393@section Packing and Unpacking
19394
19395@noindent
19396Calc's ``pack'' and ``unpack'' commands collect stack entries to build
19397composite objects such as vectors and complex numbers. They are
19398described in this chapter because they are most often used to build
19399vectors.
19400
19401@kindex v p
65d0154b 19402@kindex V p
4009494e
GM
19403@pindex calc-pack
19404The @kbd{v p} (@code{calc-pack}) [@code{pack}] command collects several
19405elements from the stack into a matrix, complex number, HMS form, error
19406form, etc. It uses a numeric prefix argument to specify the kind of
19407object to be built; this argument is referred to as the ``packing mode.''
19408If the packing mode is a nonnegative integer, a vector of that
19409length is created. For example, @kbd{C-u 5 v p} will pop the top
19410five stack elements and push back a single vector of those five
19411elements. (@kbd{C-u 0 v p} simply creates an empty vector.)
19412
19413The same effect can be had by pressing @kbd{[} to push an incomplete
19414vector on the stack, using @key{TAB} (@code{calc-roll-down}) to sneak
19415the incomplete object up past a certain number of elements, and
19416then pressing @kbd{]} to complete the vector.
19417
19418Negative packing modes create other kinds of composite objects:
19419
19420@table @cite
19421@item -1
19422Two values are collected to build a complex number. For example,
19423@kbd{5 @key{RET} 7 C-u -1 v p} creates the complex number
19424@expr{(5, 7)}. The result is always a rectangular complex
19425number. The two input values must both be real numbers,
19426i.e., integers, fractions, or floats. If they are not, Calc
19427will instead build a formula like @samp{a + (0, 1) b}. (The
19428other packing modes also create a symbolic answer if the
19429components are not suitable.)
19430
19431@item -2
19432Two values are collected to build a polar complex number.
19433The first is the magnitude; the second is the phase expressed
19434in either degrees or radians according to the current angular
19435mode.
19436
19437@item -3
19438Three values are collected into an HMS form. The first
19439two values (hours and minutes) must be integers or
19440integer-valued floats. The third value may be any real
19441number.
19442
19443@item -4
19444Two values are collected into an error form. The inputs
19445may be real numbers or formulas.
19446
19447@item -5
19448Two values are collected into a modulo form. The inputs
19449must be real numbers.
19450
19451@item -6
19452Two values are collected into the interval @samp{[a .. b]}.
19453The inputs may be real numbers, HMS or date forms, or formulas.
19454
19455@item -7
19456Two values are collected into the interval @samp{[a .. b)}.
19457
19458@item -8
19459Two values are collected into the interval @samp{(a .. b]}.
19460
19461@item -9
19462Two values are collected into the interval @samp{(a .. b)}.
19463
19464@item -10
19465Two integer values are collected into a fraction.
19466
19467@item -11
19468Two values are collected into a floating-point number.
19469The first is the mantissa; the second, which must be an
19470integer, is the exponent. The result is the mantissa
19471times ten to the power of the exponent.
19472
19473@item -12
19474This is treated the same as @mathit{-11} by the @kbd{v p} command.
19475When unpacking, @mathit{-12} specifies that a floating-point mantissa
19476is desired.
19477
19478@item -13
19479A real number is converted into a date form.
19480
19481@item -14
19482Three numbers (year, month, day) are packed into a pure date form.
19483
19484@item -15
19485Six numbers are packed into a date/time form.
19486@end table
19487
19488With any of the two-input negative packing modes, either or both
19489of the inputs may be vectors. If both are vectors of the same
19490length, the result is another vector made by packing corresponding
19491elements of the input vectors. If one input is a vector and the
19492other is a plain number, the number is packed along with each vector
19493element to produce a new vector. For example, @kbd{C-u -4 v p}
19494could be used to convert a vector of numbers and a vector of errors
19495into a single vector of error forms; @kbd{C-u -5 v p} could convert
19496a vector of numbers and a single number @var{M} into a vector of
19497numbers modulo @var{M}.
19498
19499If you don't give a prefix argument to @kbd{v p}, it takes
19500the packing mode from the top of the stack. The elements to
19501be packed then begin at stack level 2. Thus
19502@kbd{1 @key{RET} 2 @key{RET} 4 n v p} is another way to
19503enter the error form @samp{1 +/- 2}.
19504
19505If the packing mode taken from the stack is a vector, the result is a
19506matrix with the dimensions specified by the elements of the vector,
19507which must each be integers. For example, if the packing mode is
19508@samp{[2, 3]}, then six numbers will be taken from the stack and
19509returned in the form @samp{[@w{[a, b, c]}, [d, e, f]]}.
19510
19511If any elements of the vector are negative, other kinds of
19512packing are done at that level as described above. For
19513example, @samp{[2, 3, -4]} takes 12 objects and creates a
19514@texline @math{2\times3}
19515@infoline 2x3
19516matrix of error forms: @samp{[[a +/- b, c +/- d ... ]]}.
19517Also, @samp{[-4, -10]} will convert four integers into an
19518error form consisting of two fractions: @samp{a:b +/- c:d}.
19519
19520@ignore
19521@starindex
19522@end ignore
19523@tindex pack
19524There is an equivalent algebraic function,
19525@samp{pack(@var{mode}, @var{items})} where @var{mode} is a
19526packing mode (an integer or a vector of integers) and @var{items}
19527is a vector of objects to be packed (re-packed, really) according
19528to that mode. For example, @samp{pack([3, -4], [a,b,c,d,e,f])}
19529yields @samp{[a +/- b, @w{c +/- d}, e +/- f]}. The function is
19530left in symbolic form if the packing mode is invalid, or if the
19531number of data items does not match the number of items required
19532by the mode.
19533
19534@kindex v u
65d0154b 19535@kindex V u
4009494e
GM
19536@pindex calc-unpack
19537The @kbd{v u} (@code{calc-unpack}) command takes the vector, complex
19538number, HMS form, or other composite object on the top of the stack and
19539``unpacks'' it, pushing each of its elements onto the stack as separate
19540objects. Thus, it is the ``inverse'' of @kbd{v p}. If the value
19541at the top of the stack is a formula, @kbd{v u} unpacks it by pushing
19542each of the arguments of the top-level operator onto the stack.
19543
19544You can optionally give a numeric prefix argument to @kbd{v u}
19545to specify an explicit (un)packing mode. If the packing mode is
19546negative and the input is actually a vector or matrix, the result
19547will be two or more similar vectors or matrices of the elements.
19548For example, given the vector @samp{[@w{a +/- b}, c^2, d +/- 7]},
19549the result of @kbd{C-u -4 v u} will be the two vectors
19550@samp{[a, c^2, d]} and @w{@samp{[b, 0, 7]}}.
19551
19552Note that the prefix argument can have an effect even when the input is
19553not a vector. For example, if the input is the number @mathit{-5}, then
19554@kbd{c-u -1 v u} yields @mathit{-5} and 0 (the components of @mathit{-5}
19555when viewed as a rectangular complex number); @kbd{C-u -2 v u} yields 5
19556and 180 (assuming Degrees mode); and @kbd{C-u -10 v u} yields @mathit{-5}
19557and 1 (the numerator and denominator of @mathit{-5}, viewed as a rational
19558number). Plain @kbd{v u} with this input would complain that the input
19559is not a composite object.
19560
19561Unpacking mode @mathit{-11} converts a float into an integer mantissa and
19562an integer exponent, where the mantissa is not divisible by 10
19563(except that 0.0 is represented by a mantissa and exponent of 0).
19564Unpacking mode @mathit{-12} converts a float into a floating-point mantissa
19565and integer exponent, where the mantissa (for non-zero numbers)
19566is guaranteed to lie in the range [1 .. 10). In both cases,
19567the mantissa is shifted left or right (and the exponent adjusted
19568to compensate) in order to satisfy these constraints.
19569
19570Positive unpacking modes are treated differently than for @kbd{v p}.
19571A mode of 1 is much like plain @kbd{v u} with no prefix argument,
19572except that in addition to the components of the input object,
19573a suitable packing mode to re-pack the object is also pushed.
19574Thus, @kbd{C-u 1 v u} followed by @kbd{v p} will re-build the
19575original object.
19576
19577A mode of 2 unpacks two levels of the object; the resulting
19578re-packing mode will be a vector of length 2. This might be used
19579to unpack a matrix, say, or a vector of error forms. Higher
19580unpacking modes unpack the input even more deeply.
19581
19582@ignore
19583@starindex
19584@end ignore
19585@tindex unpack
19586There are two algebraic functions analogous to @kbd{v u}.
19587The @samp{unpack(@var{mode}, @var{item})} function unpacks the
19588@var{item} using the given @var{mode}, returning the result as
19589a vector of components. Here the @var{mode} must be an
19590integer, not a vector. For example, @samp{unpack(-4, a +/- b)}
19591returns @samp{[a, b]}, as does @samp{unpack(1, a +/- b)}.
19592
19593@ignore
19594@starindex
19595@end ignore
19596@tindex unpackt
19597The @code{unpackt} function is like @code{unpack} but instead
19598of returning a simple vector of items, it returns a vector of
19599two things: The mode, and the vector of items. For example,
19600@samp{unpackt(1, 2:3 +/- 1:4)} returns @samp{[-4, [2:3, 1:4]]},
19601and @samp{unpackt(2, 2:3 +/- 1:4)} returns @samp{[[-4, -10], [2, 3, 1, 4]]}.
19602The identity for re-building the original object is
19603@samp{apply(pack, unpackt(@var{n}, @var{x})) = @var{x}}. (The
19604@code{apply} function builds a function call given the function
19605name and a vector of arguments.)
19606
19607@cindex Numerator of a fraction, extracting
19608Subscript notation is a useful way to extract a particular part
19609of an object. For example, to get the numerator of a rational
19610number, you can use @samp{unpack(-10, @var{x})_1}.
19611
19612@node Building Vectors, Extracting Elements, Packing and Unpacking, Matrix Functions
19613@section Building Vectors
19614
19615@noindent
19616Vectors and matrices can be added,
19617subtracted, multiplied, and divided; @pxref{Basic Arithmetic}.
19618
19619@kindex |
19620@pindex calc-concat
19621@ignore
19622@mindex @null
19623@end ignore
19624@tindex |
19625The @kbd{|} (@code{calc-concat}) [@code{vconcat}] command ``concatenates'' two vectors
19626into one. For example, after @kbd{@w{[ 1 , 2 ]} [ 3 , 4 ] |}, the stack
19627will contain the single vector @samp{[1, 2, 3, 4]}. If the arguments
19628are matrices, the rows of the first matrix are concatenated with the
19629rows of the second. (In other words, two matrices are just two vectors
19630of row-vectors as far as @kbd{|} is concerned.)
19631
19632If either argument to @kbd{|} is a scalar (a non-vector), it is treated
19633like a one-element vector for purposes of concatenation: @kbd{1 [ 2 , 3 ] |}
19634produces the vector @samp{[1, 2, 3]}. Likewise, if one argument is a
19635matrix and the other is a plain vector, the vector is treated as a
19636one-row matrix.
19637
19638@kindex H |
19639@tindex append
19640The @kbd{H |} (@code{calc-append}) [@code{append}] command concatenates
19641two vectors without any special cases. Both inputs must be vectors.
19642Whether or not they are matrices is not taken into account. If either
19643argument is a scalar, the @code{append} function is left in symbolic form.
19644See also @code{cons} and @code{rcons} below.
19645
19646@kindex I |
19647@kindex H I |
19648The @kbd{I |} and @kbd{H I |} commands are similar, but they use their
19649two stack arguments in the opposite order. Thus @kbd{I |} is equivalent
19650to @kbd{@key{TAB} |}, but possibly more convenient and also a bit faster.
19651
19652@kindex v d
65d0154b 19653@kindex V d
4009494e
GM
19654@pindex calc-diag
19655@tindex diag
19656The @kbd{v d} (@code{calc-diag}) [@code{diag}] function builds a diagonal
19657square matrix. The optional numeric prefix gives the number of rows
19658and columns in the matrix. If the value at the top of the stack is a
19659vector, the elements of the vector are used as the diagonal elements; the
19660prefix, if specified, must match the size of the vector. If the value on
19661the stack is a scalar, it is used for each element on the diagonal, and
19662the prefix argument is required.
19663
40ba43b4 19664To build a constant square matrix, e.g., a
4009494e
GM
19665@texline @math{3\times3}
19666@infoline 3x3
19667matrix filled with ones, use @kbd{0 M-3 v d 1 +}, i.e., build a zero
19668matrix first and then add a constant value to that matrix. (Another
19669alternative would be to use @kbd{v b} and @kbd{v a}; see below.)
19670
19671@kindex v i
65d0154b 19672@kindex V i
4009494e
GM
19673@pindex calc-ident
19674@tindex idn
19675The @kbd{v i} (@code{calc-ident}) [@code{idn}] function builds an identity
19676matrix of the specified size. It is a convenient form of @kbd{v d}
19677where the diagonal element is always one. If no prefix argument is given,
19678this command prompts for one.
19679
19680In algebraic notation, @samp{idn(a,n)} acts much like @samp{diag(a,n)},
19681except that @expr{a} is required to be a scalar (non-vector) quantity.
19682If @expr{n} is omitted, @samp{idn(a)} represents @expr{a} times an
19683identity matrix of unknown size. Calc can operate algebraically on
19684such generic identity matrices, and if one is combined with a matrix
19685whose size is known, it is converted automatically to an identity
19686matrix of a suitable matching size. The @kbd{v i} command with an
19687argument of zero creates a generic identity matrix, @samp{idn(1)}.
19688Note that in dimensioned Matrix mode (@pxref{Matrix Mode}), generic
19689identity matrices are immediately expanded to the current default
19690dimensions.
19691
19692@kindex v x
65d0154b 19693@kindex V x
4009494e
GM
19694@pindex calc-index
19695@tindex index
19696The @kbd{v x} (@code{calc-index}) [@code{index}] function builds a vector
19697of consecutive integers from 1 to @var{n}, where @var{n} is the numeric
19698prefix argument. If you do not provide a prefix argument, you will be
19699prompted to enter a suitable number. If @var{n} is negative, the result
19700is a vector of negative integers from @var{n} to @mathit{-1}.
19701
19702With a prefix argument of just @kbd{C-u}, the @kbd{v x} command takes
19703three values from the stack: @var{n}, @var{start}, and @var{incr} (with
19704@var{incr} at top-of-stack). Counting starts at @var{start} and increases
19705by @var{incr} for successive vector elements. If @var{start} or @var{n}
19706is in floating-point format, the resulting vector elements will also be
19707floats. Note that @var{start} and @var{incr} may in fact be any kind
19708of numbers or formulas.
19709
19710When @var{start} and @var{incr} are specified, a negative @var{n} has a
19711different interpretation: It causes a geometric instead of arithmetic
19712sequence to be generated. For example, @samp{index(-3, a, b)} produces
19713@samp{[a, a b, a b^2]}. If you omit @var{incr} in the algebraic form,
19714@samp{index(@var{n}, @var{start})}, the default value for @var{incr}
19715is one for positive @var{n} or two for negative @var{n}.
19716
19717@kindex v b
65d0154b 19718@kindex V b
4009494e
GM
19719@pindex calc-build-vector
19720@tindex cvec
19721The @kbd{v b} (@code{calc-build-vector}) [@code{cvec}] function builds a
19722vector of @var{n} copies of the value on the top of the stack, where @var{n}
19723is the numeric prefix argument. In algebraic formulas, @samp{cvec(x,n,m)}
19724can also be used to build an @var{n}-by-@var{m} matrix of copies of @var{x}.
19725(Interactively, just use @kbd{v b} twice: once to build a row, then again
19726to build a matrix of copies of that row.)
19727
19728@kindex v h
65d0154b 19729@kindex V h
4009494e 19730@kindex I v h
65d0154b 19731@kindex I V h
4009494e
GM
19732@pindex calc-head
19733@pindex calc-tail
19734@tindex head
19735@tindex tail
19736The @kbd{v h} (@code{calc-head}) [@code{head}] function returns the first
19737element of a vector. The @kbd{I v h} (@code{calc-tail}) [@code{tail}]
19738function returns the vector with its first element removed. In both
19739cases, the argument must be a non-empty vector.
19740
19741@kindex v k
65d0154b 19742@kindex V k
4009494e
GM
19743@pindex calc-cons
19744@tindex cons
19745The @kbd{v k} (@code{calc-cons}) [@code{cons}] function takes a value @var{h}
19746and a vector @var{t} from the stack, and produces the vector whose head is
19747@var{h} and whose tail is @var{t}. This is similar to @kbd{|}, except
19748if @var{h} is itself a vector, @kbd{|} will concatenate the two vectors
19749whereas @code{cons} will insert @var{h} at the front of the vector @var{t}.
19750
19751@kindex H v h
65d0154b 19752@kindex H V h
4009494e
GM
19753@tindex rhead
19754@ignore
19755@mindex @idots
19756@end ignore
19757@kindex H I v h
65d0154b 19758@kindex H I V h
4009494e
GM
19759@ignore
19760@mindex @null
19761@end ignore
19762@kindex H v k
65d0154b 19763@kindex H V k
4009494e
GM
19764@ignore
19765@mindex @null
19766@end ignore
19767@tindex rtail
19768@ignore
19769@mindex @null
19770@end ignore
19771@tindex rcons
19772Each of these three functions also accepts the Hyperbolic flag [@code{rhead},
19773@code{rtail}, @code{rcons}] in which case @var{t} instead represents
19774the @emph{last} single element of the vector, with @var{h}
19775representing the remainder of the vector. Thus the vector
19776@samp{[a, b, c, d] = cons(a, [b, c, d]) = rcons([a, b, c], d)}.
19777Also, @samp{head([a, b, c, d]) = a}, @samp{tail([a, b, c, d]) = [b, c, d]},
19778@samp{rhead([a, b, c, d]) = [a, b, c]}, and @samp{rtail([a, b, c, d]) = d}.
19779
19780@node Extracting Elements, Manipulating Vectors, Building Vectors, Matrix Functions
19781@section Extracting Vector Elements
19782
19783@noindent
19784@kindex v r
65d0154b 19785@kindex V r
4009494e
GM
19786@pindex calc-mrow
19787@tindex mrow
19788The @kbd{v r} (@code{calc-mrow}) [@code{mrow}] command extracts one row of
19789the matrix on the top of the stack, or one element of the plain vector on
19790the top of the stack. The row or element is specified by the numeric
19791prefix argument; the default is to prompt for the row or element number.
19792The matrix or vector is replaced by the specified row or element in the
19793form of a vector or scalar, respectively.
19794
19795@cindex Permutations, applying
19796With a prefix argument of @kbd{C-u} only, @kbd{v r} takes the index of
19797the element or row from the top of the stack, and the vector or matrix
19798from the second-to-top position. If the index is itself a vector of
19799integers, the result is a vector of the corresponding elements of the
19800input vector, or a matrix of the corresponding rows of the input matrix.
19801This command can be used to obtain any permutation of a vector.
19802
19803With @kbd{C-u}, if the index is an interval form with integer components,
19804it is interpreted as a range of indices and the corresponding subvector or
19805submatrix is returned.
19806
19807@cindex Subscript notation
19808@kindex a _
19809@pindex calc-subscript
19810@tindex subscr
19811@tindex _
19812Subscript notation in algebraic formulas (@samp{a_b}) stands for the
19813Calc function @code{subscr}, which is synonymous with @code{mrow}.
19814Thus, @samp{[x, y, z]_k} produces @expr{x}, @expr{y}, or @expr{z} if
19815@expr{k} is one, two, or three, respectively. A double subscript
19816(@samp{M_i_j}, equivalent to @samp{subscr(subscr(M, i), j)}) will
19817access the element at row @expr{i}, column @expr{j} of a matrix.
19818The @kbd{a _} (@code{calc-subscript}) command creates a subscript
19819formula @samp{a_b} out of two stack entries. (It is on the @kbd{a}
19820``algebra'' prefix because subscripted variables are often used
19821purely as an algebraic notation.)
19822
19823@tindex mrrow
19824Given a negative prefix argument, @kbd{v r} instead deletes one row or
19825element from the matrix or vector on the top of the stack. Thus
19826@kbd{C-u 2 v r} replaces a matrix with its second row, but @kbd{C-u -2 v r}
19827replaces the matrix with the same matrix with its second row removed.
19828In algebraic form this function is called @code{mrrow}.
19829
19830@tindex getdiag
19831Given a prefix argument of zero, @kbd{v r} extracts the diagonal elements
19832of a square matrix in the form of a vector. In algebraic form this
19833function is called @code{getdiag}.
19834
19835@kindex v c
65d0154b 19836@kindex V c
4009494e
GM
19837@pindex calc-mcol
19838@tindex mcol
19839@tindex mrcol
19840The @kbd{v c} (@code{calc-mcol}) [@code{mcol} or @code{mrcol}] command is
19841the analogous operation on columns of a matrix. Given a plain vector
19842it extracts (or removes) one element, just like @kbd{v r}. If the
19843index in @kbd{C-u v c} is an interval or vector and the argument is a
19844matrix, the result is a submatrix with only the specified columns
19845retained (and possibly permuted in the case of a vector index).
19846
19847To extract a matrix element at a given row and column, use @kbd{v r} to
19848extract the row as a vector, then @kbd{v c} to extract the column element
19849from that vector. In algebraic formulas, it is often more convenient to
19850use subscript notation: @samp{m_i_j} gives row @expr{i}, column @expr{j}
19851of matrix @expr{m}.
19852
19853@kindex v s
65d0154b 19854@kindex V s
4009494e
GM
19855@pindex calc-subvector
19856@tindex subvec
19857The @kbd{v s} (@code{calc-subvector}) [@code{subvec}] command extracts
19858a subvector of a vector. The arguments are the vector, the starting
19859index, and the ending index, with the ending index in the top-of-stack
19860position. The starting index indicates the first element of the vector
19861to take. The ending index indicates the first element @emph{past} the
19862range to be taken. Thus, @samp{subvec([a, b, c, d, e], 2, 4)} produces
19863the subvector @samp{[b, c]}. You could get the same result using
19864@samp{mrow([a, b, c, d, e], @w{[2 .. 4)})}.
19865
19866If either the start or the end index is zero or negative, it is
19867interpreted as relative to the end of the vector. Thus
19868@samp{subvec([a, b, c, d, e], 2, -2)} also produces @samp{[b, c]}. In
19869the algebraic form, the end index can be omitted in which case it
19870is taken as zero, i.e., elements from the starting element to the
19871end of the vector are used. The infinity symbol, @code{inf}, also
19872has this effect when used as the ending index.
19873
19874@kindex I v s
65d0154b 19875@kindex I V s
4009494e
GM
19876@tindex rsubvec
19877With the Inverse flag, @kbd{I v s} [@code{rsubvec}] removes a subvector
19878from a vector. The arguments are interpreted the same as for the
19879normal @kbd{v s} command. Thus, @samp{rsubvec([a, b, c, d, e], 2, 4)}
19880produces @samp{[a, d, e]}. It is always true that @code{subvec} and
19881@code{rsubvec} return complementary parts of the input vector.
19882
19883@xref{Selecting Subformulas}, for an alternative way to operate on
19884vectors one element at a time.
19885
19886@node Manipulating Vectors, Vector and Matrix Arithmetic, Extracting Elements, Matrix Functions
19887@section Manipulating Vectors
19888
19889@noindent
19890@kindex v l
65d0154b 19891@kindex V l
4009494e
GM
19892@pindex calc-vlength
19893@tindex vlen
19894The @kbd{v l} (@code{calc-vlength}) [@code{vlen}] command computes the
19895length of a vector. The length of a non-vector is considered to be zero.
19896Note that matrices are just vectors of vectors for the purposes of this
19897command.
19898
19899@kindex H v l
65d0154b 19900@kindex H V l
4009494e
GM
19901@tindex mdims
19902With the Hyperbolic flag, @kbd{H v l} [@code{mdims}] computes a vector
19903of the dimensions of a vector, matrix, or higher-order object. For
19904example, @samp{mdims([[a,b,c],[d,e,f]])} returns @samp{[2, 3]} since
40ba43b4 19905its argument is a
4009494e
GM
19906@texline @math{2\times3}
19907@infoline 2x3
19908matrix.
19909
19910@kindex v f
65d0154b 19911@kindex V f
4009494e
GM
19912@pindex calc-vector-find
19913@tindex find
19914The @kbd{v f} (@code{calc-vector-find}) [@code{find}] command searches
19915along a vector for the first element equal to a given target. The target
19916is on the top of the stack; the vector is in the second-to-top position.
19917If a match is found, the result is the index of the matching element.
19918Otherwise, the result is zero. The numeric prefix argument, if given,
19919allows you to select any starting index for the search.
19920
19921@kindex v a
65d0154b 19922@kindex V a
4009494e
GM
19923@pindex calc-arrange-vector
19924@tindex arrange
19925@cindex Arranging a matrix
19926@cindex Reshaping a matrix
19927@cindex Flattening a matrix
19928The @kbd{v a} (@code{calc-arrange-vector}) [@code{arrange}] command
19929rearranges a vector to have a certain number of columns and rows. The
19930numeric prefix argument specifies the number of columns; if you do not
19931provide an argument, you will be prompted for the number of columns.
19932The vector or matrix on the top of the stack is @dfn{flattened} into a
19933plain vector. If the number of columns is nonzero, this vector is
19934then formed into a matrix by taking successive groups of @var{n} elements.
19935If the number of columns does not evenly divide the number of elements
19936in the vector, the last row will be short and the result will not be
19937suitable for use as a matrix. For example, with the matrix
19938@samp{[[1, 2], @w{[3, 4]}]} on the stack, @kbd{v a 4} produces
40ba43b4 19939@samp{[[1, 2, 3, 4]]} (a
4009494e
GM
19940@texline @math{1\times4}
19941@infoline 1x4
40ba43b4 19942matrix), @kbd{v a 1} produces @samp{[[1], [2], [3], [4]]} (a
4009494e
GM
19943@texline @math{4\times1}
19944@infoline 4x1
40ba43b4 19945matrix), @kbd{v a 2} produces @samp{[[1, 2], [3, 4]]} (the original
4009494e
GM
19946@texline @math{2\times2}
19947@infoline 2x2
19948matrix), @w{@kbd{v a 3}} produces @samp{[[1, 2, 3], [4]]} (not a
40ba43b4 19949matrix), and @kbd{v a 0} produces the flattened list
4009494e
GM
19950@samp{[1, 2, @w{3, 4}]}.
19951
19952@cindex Sorting data
65d0154b 19953@kindex v S
4009494e 19954@kindex V S
65d0154b 19955@kindex I v S
4009494e
GM
19956@kindex I V S
19957@pindex calc-sort
19958@tindex sort
19959@tindex rsort
19960The @kbd{V S} (@code{calc-sort}) [@code{sort}] command sorts the elements of
19961a vector into increasing order. Real numbers, real infinities, and
19962constant interval forms come first in this ordering; next come other
19963kinds of numbers, then variables (in alphabetical order), then finally
19964come formulas and other kinds of objects; these are sorted according
19965to a kind of lexicographic ordering with the useful property that
19966one vector is less or greater than another if the first corresponding
19967unequal elements are less or greater, respectively. Since quoted strings
19968are stored by Calc internally as vectors of ASCII character codes
19969(@pxref{Strings}), this means vectors of strings are also sorted into
19970alphabetical order by this command.
19971
19972The @kbd{I V S} [@code{rsort}] command sorts a vector into decreasing order.
19973
19974@cindex Permutation, inverse of
19975@cindex Inverse of permutation
19976@cindex Index tables
19977@cindex Rank tables
65d0154b 19978@kindex v G
4009494e 19979@kindex V G
65d0154b 19980@kindex I v G
4009494e
GM
19981@kindex I V G
19982@pindex calc-grade
19983@tindex grade
19984@tindex rgrade
19985The @kbd{V G} (@code{calc-grade}) [@code{grade}, @code{rgrade}] command
19986produces an index table or permutation vector which, if applied to the
19987input vector (as the index of @kbd{C-u v r}, say), would sort the vector.
19988A permutation vector is just a vector of integers from 1 to @var{n}, where
19989each integer occurs exactly once. One application of this is to sort a
19990matrix of data rows using one column as the sort key; extract that column,
19991grade it with @kbd{V G}, then use the result to reorder the original matrix
19992with @kbd{C-u v r}. Another interesting property of the @code{V G} command
19993is that, if the input is itself a permutation vector, the result will
19994be the inverse of the permutation. The inverse of an index table is
19995a rank table, whose @var{k}th element says where the @var{k}th original
19996vector element will rest when the vector is sorted. To get a rank
19997table, just use @kbd{V G V G}.
19998
19999With the Inverse flag, @kbd{I V G} produces an index table that would
20000sort the input into decreasing order. Note that @kbd{V S} and @kbd{V G}
20001use a ``stable'' sorting algorithm, i.e., any two elements which are equal
20002will not be moved out of their original order. Generally there is no way
20003to tell with @kbd{V S}, since two elements which are equal look the same,
20004but with @kbd{V G} this can be an important issue. In the matrix-of-rows
20005example, suppose you have names and telephone numbers as two columns and
20006you wish to sort by phone number primarily, and by name when the numbers
20007are equal. You can sort the data matrix by names first, and then again
20008by phone numbers. Because the sort is stable, any two rows with equal
20009phone numbers will remain sorted by name even after the second sort.
20010
20011@cindex Histograms
65d0154b 20012@kindex v H
4009494e
GM
20013@kindex V H
20014@pindex calc-histogram
20015@ignore
20016@mindex histo@idots
20017@end ignore
20018@tindex histogram
20019The @kbd{V H} (@code{calc-histogram}) [@code{histogram}] command builds a
20020histogram of a vector of numbers. Vector elements are assumed to be
20021integers or real numbers in the range [0..@var{n}) for some ``number of
20022bins'' @var{n}, which is the numeric prefix argument given to the
20023command. The result is a vector of @var{n} counts of how many times
20024each value appeared in the original vector. Non-integers in the input
20025are rounded down to integers. Any vector elements outside the specified
20026range are ignored. (You can tell if elements have been ignored by noting
20027that the counts in the result vector don't add up to the length of the
20028input vector.)
20029
597517ef
JB
20030If no prefix is given, then you will be prompted for a vector which
20031will be used to determine the bins. (If a positive integer is given at
20032this prompt, it will be still treated as if it were given as a
20033prefix.) Each bin will consist of the interval of numbers closest to
40ba43b4
PE
20034the corresponding number of this new vector; if the vector
20035@expr{[a, b, c, ...]} is entered at the prompt, the bins will be
20036@expr{(-inf, (a+b)/2]}, @expr{((a+b)/2, (b+c)/2]}, etc. The result of
597517ef
JB
20037this command will be a vector counting how many elements of the
20038original vector are in each bin.
20039
20040The result will then be a vector with the same length as this new vector;
20041each element of the new vector will be replaced by the number of
20042elements of the original vector which are closest to it.
20043
65d0154b 20044@kindex H v H
4009494e
GM
20045@kindex H V H
20046With the Hyperbolic flag, @kbd{H V H} pulls two vectors from the stack.
20047The second-to-top vector is the list of numbers as before. The top
20048vector is an equal-sized list of ``weights'' to attach to the elements
20049of the data vector. For example, if the first data element is 4.2 and
20050the first weight is 10, then 10 will be added to bin 4 of the result
20051vector. Without the hyperbolic flag, every element has a weight of one.
20052
20053@kindex v t
65d0154b 20054@kindex V t
4009494e
GM
20055@pindex calc-transpose
20056@tindex trn
20057The @kbd{v t} (@code{calc-transpose}) [@code{trn}] command computes
20058the transpose of the matrix at the top of the stack. If the argument
20059is a plain vector, it is treated as a row vector and transposed into
20060a one-column matrix.
20061
20062@kindex v v
65d0154b 20063@kindex V v
4009494e
GM
20064@pindex calc-reverse-vector
20065@tindex rev
20066The @kbd{v v} (@code{calc-reverse-vector}) [@code{rev}] command reverses
20067a vector end-for-end. Given a matrix, it reverses the order of the rows.
20068(To reverse the columns instead, just use @kbd{v t v v v t}. The same
20069principle can be used to apply other vector commands to the columns of
20070a matrix.)
20071
20072@kindex v m
65d0154b 20073@kindex V m
4009494e
GM
20074@pindex calc-mask-vector
20075@tindex vmask
20076The @kbd{v m} (@code{calc-mask-vector}) [@code{vmask}] command uses
20077one vector as a mask to extract elements of another vector. The mask
20078is in the second-to-top position; the target vector is on the top of
20079the stack. These vectors must have the same length. The result is
20080the same as the target vector, but with all elements which correspond
20081to zeros in the mask vector deleted. Thus, for example,
20082@samp{vmask([1, 0, 1, 0, 1], [a, b, c, d, e])} produces @samp{[a, c, e]}.
20083@xref{Logical Operations}.
20084
20085@kindex v e
65d0154b 20086@kindex V e
4009494e
GM
20087@pindex calc-expand-vector
20088@tindex vexp
20089The @kbd{v e} (@code{calc-expand-vector}) [@code{vexp}] command
20090expands a vector according to another mask vector. The result is a
20091vector the same length as the mask, but with nonzero elements replaced
20092by successive elements from the target vector. The length of the target
20093vector is normally the number of nonzero elements in the mask. If the
20094target vector is longer, its last few elements are lost. If the target
20095vector is shorter, the last few nonzero mask elements are left
20096unreplaced in the result. Thus @samp{vexp([2, 0, 3, 0, 7], [a, b])}
20097produces @samp{[a, 0, b, 0, 7]}.
20098
20099@kindex H v e
65d0154b 20100@kindex H V e
4009494e
GM
20101With the Hyperbolic flag, @kbd{H v e} takes a filler value from the
20102top of the stack; the mask and target vectors come from the third and
20103second elements of the stack. This filler is used where the mask is
20104zero: @samp{vexp([2, 0, 3, 0, 7], [a, b], z)} produces
20105@samp{[a, z, c, z, 7]}. If the filler value is itself a vector,
20106then successive values are taken from it, so that the effect is to
20107interleave two vectors according to the mask:
20108@samp{vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])} produces
20109@samp{[a, x, b, 7, y, 0]}.
20110
20111Another variation on the masking idea is to combine @samp{[a, b, c, d, e]}
20112with the mask @samp{[1, 0, 1, 0, 1]} to produce @samp{[a, 0, c, 0, e]}.
20113You can accomplish this with @kbd{V M a &}, mapping the logical ``and''
20114operation across the two vectors. @xref{Logical Operations}. Note that
20115the @code{? :} operation also discussed there allows other types of
20116masking using vectors.
20117
20118@node Vector and Matrix Arithmetic, Set Operations, Manipulating Vectors, Matrix Functions
20119@section Vector and Matrix Arithmetic
20120
20121@noindent
20122Basic arithmetic operations like addition and multiplication are defined
20123for vectors and matrices as well as for numbers. Division of matrices, in
20124the sense of multiplying by the inverse, is supported. (Division by a
20125matrix actually uses LU-decomposition for greater accuracy and speed.)
20126@xref{Basic Arithmetic}.
20127
20128The following functions are applied element-wise if their arguments are
20129vectors or matrices: @code{change-sign}, @code{conj}, @code{arg},
20130@code{re}, @code{im}, @code{polar}, @code{rect}, @code{clean},
20131@code{float}, @code{frac}. @xref{Function Index}.
20132
65d0154b 20133@kindex v J
4009494e
GM
20134@kindex V J
20135@pindex calc-conj-transpose
20136@tindex ctrn
20137The @kbd{V J} (@code{calc-conj-transpose}) [@code{ctrn}] command computes
20138the conjugate transpose of its argument, i.e., @samp{conj(trn(x))}.
20139
20140@ignore
20141@mindex A
20142@end ignore
20143@kindex A (vectors)
20144@pindex calc-abs (vectors)
20145@ignore
20146@mindex abs
20147@end ignore
20148@tindex abs (vectors)
20149The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the
20150Frobenius norm of a vector or matrix argument. This is the square
20151root of the sum of the squares of the absolute values of the
20152elements of the vector or matrix. If the vector is interpreted as
20153a point in two- or three-dimensional space, this is the distance
20154from that point to the origin.
20155
20156@kindex v n
65d0154b 20157@kindex V n
4009494e
GM
20158@pindex calc-rnorm
20159@tindex rnorm
a8b14149
JB
20160The @kbd{v n} (@code{calc-rnorm}) [@code{rnorm}] command computes the
20161infinity-norm of a vector, or the row norm of a matrix. For a plain
20162vector, this is the maximum of the absolute values of the elements. For
20163a matrix, this is the maximum of the row-absolute-value-sums, i.e., of
20164the sums of the absolute values of the elements along the various rows.
4009494e 20165
65d0154b 20166@kindex v N
4009494e
GM
20167@kindex V N
20168@pindex calc-cnorm
20169@tindex cnorm
20170The @kbd{V N} (@code{calc-cnorm}) [@code{cnorm}] command computes
a8b14149 20171the one-norm of a vector, or column norm of a matrix. For a plain
4009494e
GM
20172vector, this is the sum of the absolute values of the elements.
20173For a matrix, this is the maximum of the column-absolute-value-sums.
20174General @expr{k}-norms for @expr{k} other than one or infinity are
a8b14149
JB
20175not provided. However, the 2-norm (or Frobenius norm) is provided for
20176vectors by the @kbd{A} (@code{calc-abs}) command.
4009494e 20177
65d0154b 20178@kindex v C
4009494e
GM
20179@kindex V C
20180@pindex calc-cross
20181@tindex cross
20182The @kbd{V C} (@code{calc-cross}) [@code{cross}] command computes the
20183right-handed cross product of two vectors, each of which must have
20184exactly three elements.
20185
20186@ignore
20187@mindex &
20188@end ignore
20189@kindex & (matrices)
20190@pindex calc-inv (matrices)
20191@ignore
20192@mindex inv
20193@end ignore
20194@tindex inv (matrices)
20195The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
20196inverse of a square matrix. If the matrix is singular, the inverse
20197operation is left in symbolic form. Matrix inverses are recorded so
20198that once an inverse (or determinant) of a particular matrix has been
20199computed, the inverse and determinant of the matrix can be recomputed
20200quickly in the future.
20201
20202If the argument to @kbd{&} is a plain number @expr{x}, this
20203command simply computes @expr{1/x}. This is okay, because the
20204@samp{/} operator also does a matrix inversion when dividing one
20205by a matrix.
20206
65d0154b 20207@kindex v D
4009494e
GM
20208@kindex V D
20209@pindex calc-mdet
20210@tindex det
20211The @kbd{V D} (@code{calc-mdet}) [@code{det}] command computes the
20212determinant of a square matrix.
20213
65d0154b 20214@kindex v L
4009494e
GM
20215@kindex V L
20216@pindex calc-mlud
20217@tindex lud
20218The @kbd{V L} (@code{calc-mlud}) [@code{lud}] command computes the
20219LU decomposition of a matrix. The result is a list of three matrices
20220which, when multiplied together left-to-right, form the original matrix.
20221The first is a permutation matrix that arises from pivoting in the
20222algorithm, the second is lower-triangular with ones on the diagonal,
20223and the third is upper-triangular.
20224
65d0154b 20225@kindex v T
4009494e
GM
20226@kindex V T
20227@pindex calc-mtrace
20228@tindex tr
20229The @kbd{V T} (@code{calc-mtrace}) [@code{tr}] command computes the
20230trace of a square matrix. This is defined as the sum of the diagonal
20231elements of the matrix.
20232
65d0154b 20233@kindex v K
629f618d
JB
20234@kindex V K
20235@pindex calc-kron
20236@tindex kron
20237The @kbd{V K} (@code{calc-kron}) [@code{kron}] command computes
20238the Kronecker product of two matrices.
20239
4009494e
GM
20240@node Set Operations, Statistical Operations, Vector and Matrix Arithmetic, Matrix Functions
20241@section Set Operations using Vectors
20242
20243@noindent
20244@cindex Sets, as vectors
20245Calc includes several commands which interpret vectors as @dfn{sets} of
20246objects. A set is a collection of objects; any given object can appear
20247only once in the set. Calc stores sets as vectors of objects in
20248sorted order. Objects in a Calc set can be any of the usual things,
20249such as numbers, variables, or formulas. Two set elements are considered
20250equal if they are identical, except that numerically equal numbers like
20251the integer 4 and the float 4.0 are considered equal even though they
20252are not ``identical.'' Variables are treated like plain symbols without
20253attached values by the set operations; subtracting the set @samp{[b]}
20254from @samp{[a, b]} always yields the set @samp{[a]} even though if
20255the variables @samp{a} and @samp{b} both equaled 17, you might
20256expect the answer @samp{[]}.
20257
20258If a set contains interval forms, then it is assumed to be a set of
20259real numbers. In this case, all set operations require the elements
20260of the set to be only things that are allowed in intervals: Real
20261numbers, plus and minus infinity, HMS forms, and date forms. If
20262there are variables or other non-real objects present in a real set,
20263all set operations on it will be left in unevaluated form.
20264
20265If the input to a set operation is a plain number or interval form
20266@var{a}, it is treated like the one-element vector @samp{[@var{a}]}.
20267The result is always a vector, except that if the set consists of a
20268single interval, the interval itself is returned instead.
20269
20270@xref{Logical Operations}, for the @code{in} function which tests if
20271a certain value is a member of a given set. To test if the set @expr{A}
20272is a subset of the set @expr{B}, use @samp{vdiff(A, B) = []}.
20273
65d0154b 20274@kindex v +
4009494e
GM
20275@kindex V +
20276@pindex calc-remove-duplicates
20277@tindex rdup
20278The @kbd{V +} (@code{calc-remove-duplicates}) [@code{rdup}] command
20279converts an arbitrary vector into set notation. It works by sorting
20280the vector as if by @kbd{V S}, then removing duplicates. (For example,
20281@kbd{[a, 5, 4, a, 4.0]} is sorted to @samp{[4, 4.0, 5, a, a]} and then
20282reduced to @samp{[4, 5, a]}). Overlapping intervals are merged as
20283necessary. You rarely need to use @kbd{V +} explicitly, since all the
20284other set-based commands apply @kbd{V +} to their inputs before using
20285them.
20286
65d0154b 20287@kindex v V
4009494e
GM
20288@kindex V V
20289@pindex calc-set-union
20290@tindex vunion
20291The @kbd{V V} (@code{calc-set-union}) [@code{vunion}] command computes
20292the union of two sets. An object is in the union of two sets if and
20293only if it is in either (or both) of the input sets. (You could
20294accomplish the same thing by concatenating the sets with @kbd{|},
20295then using @kbd{V +}.)
20296
65d0154b 20297@kindex v ^
4009494e
GM
20298@kindex V ^
20299@pindex calc-set-intersect
20300@tindex vint
20301The @kbd{V ^} (@code{calc-set-intersect}) [@code{vint}] command computes
20302the intersection of two sets. An object is in the intersection if
20303and only if it is in both of the input sets. Thus if the input
20304sets are disjoint, i.e., if they share no common elements, the result
20305will be the empty vector @samp{[]}. Note that the characters @kbd{V}
20306and @kbd{^} were chosen to be close to the conventional mathematical
40ba43b4 20307notation for set
4009494e
GM
20308@texline union@tie{}(@math{A \cup B})
20309@infoline union
40ba43b4 20310and
4009494e
GM
20311@texline intersection@tie{}(@math{A \cap B}).
20312@infoline intersection.
20313
65d0154b 20314@kindex v -
4009494e
GM
20315@kindex V -
20316@pindex calc-set-difference
20317@tindex vdiff
20318The @kbd{V -} (@code{calc-set-difference}) [@code{vdiff}] command computes
20319the difference between two sets. An object is in the difference
20320@expr{A - B} if and only if it is in @expr{A} but not in @expr{B}.
20321Thus subtracting @samp{[y,z]} from a set will remove the elements
20322@samp{y} and @samp{z} if they are present. You can also think of this
20323as a general @dfn{set complement} operator; if @expr{A} is the set of
20324all possible values, then @expr{A - B} is the ``complement'' of @expr{B}.
20325Obviously this is only practical if the set of all possible values in
20326your problem is small enough to list in a Calc vector (or simple
20327enough to express in a few intervals).
20328
65d0154b 20329@kindex v X
4009494e
GM
20330@kindex V X
20331@pindex calc-set-xor
20332@tindex vxor
20333The @kbd{V X} (@code{calc-set-xor}) [@code{vxor}] command computes
20334the ``exclusive-or,'' or ``symmetric difference'' of two sets.
20335An object is in the symmetric difference of two sets if and only
20336if it is in one, but @emph{not} both, of the sets. Objects that
20337occur in both sets ``cancel out.''
20338
65d0154b 20339@kindex v ~
4009494e
GM
20340@kindex V ~
20341@pindex calc-set-complement
20342@tindex vcompl
20343The @kbd{V ~} (@code{calc-set-complement}) [@code{vcompl}] command
20344computes the complement of a set with respect to the real numbers.
20345Thus @samp{vcompl(x)} is equivalent to @samp{vdiff([-inf .. inf], x)}.
20346For example, @samp{vcompl([2, (3 .. 4]])} evaluates to
20347@samp{[[-inf .. 2), (2 .. 3], (4 .. inf]]}.
20348
65d0154b 20349@kindex v F
4009494e
GM
20350@kindex V F
20351@pindex calc-set-floor
20352@tindex vfloor
20353The @kbd{V F} (@code{calc-set-floor}) [@code{vfloor}] command
20354reinterprets a set as a set of integers. Any non-integer values,
20355and intervals that do not enclose any integers, are removed. Open
20356intervals are converted to equivalent closed intervals. Successive
20357integers are converted into intervals of integers. For example, the
20358complement of the set @samp{[2, 6, 7, 8]} is messy, but if you wanted
20359the complement with respect to the set of integers you could type
20360@kbd{V ~ V F} to get @samp{[[-inf .. 1], [3 .. 5], [9 .. inf]]}.
20361
65d0154b 20362@kindex v E
4009494e
GM
20363@kindex V E
20364@pindex calc-set-enumerate
20365@tindex venum
20366The @kbd{V E} (@code{calc-set-enumerate}) [@code{venum}] command
20367converts a set of integers into an explicit vector. Intervals in
20368the set are expanded out to lists of all integers encompassed by
20369the intervals. This only works for finite sets (i.e., sets which
20370do not involve @samp{-inf} or @samp{inf}).
20371
65d0154b 20372@kindex v :
4009494e
GM
20373@kindex V :
20374@pindex calc-set-span
20375@tindex vspan
20376The @kbd{V :} (@code{calc-set-span}) [@code{vspan}] command converts any
20377set of reals into an interval form that encompasses all its elements.
20378The lower limit will be the smallest element in the set; the upper
20379limit will be the largest element. For an empty set, @samp{vspan([])}
20380returns the empty interval @w{@samp{[0 .. 0)}}.
20381
65d0154b 20382@kindex v #
4009494e
GM
20383@kindex V #
20384@pindex calc-set-cardinality
20385@tindex vcard
20386The @kbd{V #} (@code{calc-set-cardinality}) [@code{vcard}] command counts
20387the number of integers in a set. The result is the length of the vector
20388that would be produced by @kbd{V E}, although the computation is much
20389more efficient than actually producing that vector.
20390
20391@cindex Sets, as binary numbers
20392Another representation for sets that may be more appropriate in some
20393cases is binary numbers. If you are dealing with sets of integers
20394in the range 0 to 49, you can use a 50-bit binary number where a
20395particular bit is 1 if the corresponding element is in the set.
20396@xref{Binary Functions}, for a list of commands that operate on
20397binary numbers. Note that many of the above set operations have
20398direct equivalents in binary arithmetic: @kbd{b o} (@code{calc-or}),
20399@kbd{b a} (@code{calc-and}), @kbd{b d} (@code{calc-diff}),
20400@kbd{b x} (@code{calc-xor}), and @kbd{b n} (@code{calc-not}),
20401respectively. You can use whatever representation for sets is most
20402convenient to you.
20403
20404@kindex b p
20405@kindex b u
20406@pindex calc-pack-bits
20407@pindex calc-unpack-bits
20408@tindex vpack
20409@tindex vunpack
20410The @kbd{b u} (@code{calc-unpack-bits}) [@code{vunpack}] command
20411converts an integer that represents a set in binary into a set
20412in vector/interval notation. For example, @samp{vunpack(67)}
20413returns @samp{[[0 .. 1], 6]}. If the input is negative, the set
20414it represents is semi-infinite: @samp{vunpack(-4) = [2 .. inf)}.
20415Use @kbd{V E} afterwards to expand intervals to individual
20416values if you wish. Note that this command uses the @kbd{b}
20417(binary) prefix key.
20418
20419The @kbd{b p} (@code{calc-pack-bits}) [@code{vpack}] command
20420converts the other way, from a vector or interval representing
20421a set of nonnegative integers into a binary integer describing
20422the same set. The set may include positive infinity, but must
20423not include any negative numbers. The input is interpreted as a
20424set of integers in the sense of @kbd{V F} (@code{vfloor}). Beware
20425that a simple input like @samp{[100]} can result in a huge integer
40ba43b4 20426representation
4009494e
GM
20427@texline (@math{2^{100}}, a 31-digit integer, in this case).
20428@infoline (@expr{2^100}, a 31-digit integer, in this case).
20429
20430@node Statistical Operations, Reducing and Mapping, Set Operations, Matrix Functions
20431@section Statistical Operations on Vectors
20432
20433@noindent
20434@cindex Statistical functions
20435The commands in this section take vectors as arguments and compute
20436various statistical measures on the data stored in the vectors. The
20437references used in the definitions of these functions are Bevington's
20438@emph{Data Reduction and Error Analysis for the Physical Sciences},
20439and @emph{Numerical Recipes} by Press, Flannery, Teukolsky and
20440Vetterling.
20441
20442The statistical commands use the @kbd{u} prefix key followed by
20443a shifted letter or other character.
20444
20445@xref{Manipulating Vectors}, for a description of @kbd{V H}
20446(@code{calc-histogram}).
20447
20448@xref{Curve Fitting}, for the @kbd{a F} command for doing
20449least-squares fits to statistical data.
20450
20451@xref{Probability Distribution Functions}, for several common
20452probability distribution functions.
20453
20454@menu
20455* Single-Variable Statistics::
20456* Paired-Sample Statistics::
20457@end menu
20458
20459@node Single-Variable Statistics, Paired-Sample Statistics, Statistical Operations, Statistical Operations
20460@subsection Single-Variable Statistics
20461
20462@noindent
20463These functions do various statistical computations on single
20464vectors. Given a numeric prefix argument, they actually pop
20465@var{n} objects from the stack and combine them into a data
20466vector. Each object may be either a number or a vector; if a
20467vector, any sub-vectors inside it are ``flattened'' as if by
20468@kbd{v a 0}; @pxref{Manipulating Vectors}. By default one object
20469is popped, which (in order to be useful) is usually a vector.
20470
20471If an argument is a variable name, and the value stored in that
20472variable is a vector, then the stored vector is used. This method
20473has the advantage that if your data vector is large, you can avoid
20474the slow process of manipulating it directly on the stack.
20475
20476These functions are left in symbolic form if any of their arguments
20477are not numbers or vectors, e.g., if an argument is a formula, or
20478a non-vector variable. However, formulas embedded within vector
20479arguments are accepted; the result is a symbolic representation
20480of the computation, based on the assumption that the formula does
20481not itself represent a vector. All varieties of numbers such as
20482error forms and interval forms are acceptable.
20483
20484Some of the functions in this section also accept a single error form
20485or interval as an argument. They then describe a property of the
20486normal or uniform (respectively) statistical distribution described
20487by the argument. The arguments are interpreted in the same way as
20488the @var{M} argument of the random number function @kbd{k r}. In
20489particular, an interval with integer limits is considered an integer
20490distribution, so that @samp{[2 .. 6)} is the same as @samp{[2 .. 5]}.
20491An interval with at least one floating-point limit is a continuous
20492distribution: @samp{[2.0 .. 6.0)} is @emph{not} the same as
20493@samp{[2.0 .. 5.0]}!
20494
20495@kindex u #
20496@pindex calc-vector-count
20497@tindex vcount
20498The @kbd{u #} (@code{calc-vector-count}) [@code{vcount}] command
20499computes the number of data values represented by the inputs.
20500For example, @samp{vcount(1, [2, 3], [[4, 5], [], x, y])} returns 7.
20501If the argument is a single vector with no sub-vectors, this
20502simply computes the length of the vector.
20503
20504@kindex u +
20505@kindex u *
20506@pindex calc-vector-sum
20507@pindex calc-vector-prod
20508@tindex vsum
20509@tindex vprod
20510@cindex Summations (statistical)
20511The @kbd{u +} (@code{calc-vector-sum}) [@code{vsum}] command
20512computes the sum of the data values. The @kbd{u *}
20513(@code{calc-vector-prod}) [@code{vprod}] command computes the
20514product of the data values. If the input is a single flat vector,
20515these are the same as @kbd{V R +} and @kbd{V R *}
20516(@pxref{Reducing and Mapping}).
20517
20518@kindex u X
20519@kindex u N
20520@pindex calc-vector-max
20521@pindex calc-vector-min
20522@tindex vmax
20523@tindex vmin
20524The @kbd{u X} (@code{calc-vector-max}) [@code{vmax}] command
20525computes the maximum of the data values, and the @kbd{u N}
20526(@code{calc-vector-min}) [@code{vmin}] command computes the minimum.
20527If the argument is an interval, this finds the minimum or maximum
20528value in the interval. (Note that @samp{vmax([2..6)) = 5} as
20529described above.) If the argument is an error form, this returns
20530plus or minus infinity.
20531
20532@kindex u M
20533@pindex calc-vector-mean
20534@tindex vmean
20535@cindex Mean of data values
20536The @kbd{u M} (@code{calc-vector-mean}) [@code{vmean}] command
20537computes the average (arithmetic mean) of the data values.
40ba43b4 20538If the inputs are error forms
4009494e 20539@texline @math{x \pm \sigma},
40ba43b4
PE
20540@infoline @samp{x +/- s},
20541this is the weighted mean of the @expr{x} values with weights
4009494e
GM
20542@texline @math{1 /\sigma^2}.
20543@infoline @expr{1 / s^2}.
20544@tex
4009494e
GM
20545$$ \mu = { \displaystyle \sum { x_i \over \sigma_i^2 } \over
20546 \displaystyle \sum { 1 \over \sigma_i^2 } } $$
20547@end tex
20548If the inputs are not error forms, this is simply the sum of the
20549values divided by the count of the values.
20550
20551Note that a plain number can be considered an error form with
40ba43b4 20552error
4009494e 20553@texline @math{\sigma = 0}.
40ba43b4 20554@infoline @expr{s = 0}.
4009494e
GM
20555If the input to @kbd{u M} is a mixture of
20556plain numbers and error forms, the result is the mean of the
20557plain numbers, ignoring all values with non-zero errors. (By the
20558above definitions it's clear that a plain number effectively
20559has an infinite weight, next to which an error form with a finite
20560weight is completely negligible.)
20561
20562This function also works for distributions (error forms or
20563intervals). The mean of an error form `@var{a} @tfn{+/-} @var{b}' is simply
20564@expr{a}. The mean of an interval is the mean of the minimum
20565and maximum values of the interval.
20566
20567@kindex I u M
20568@pindex calc-vector-mean-error
20569@tindex vmeane
20570The @kbd{I u M} (@code{calc-vector-mean-error}) [@code{vmeane}]
20571command computes the mean of the data points expressed as an
20572error form. This includes the estimated error associated with
20573the mean. If the inputs are error forms, the error is the square
20574root of the reciprocal of the sum of the reciprocals of the squares
20575of the input errors. (I.e., the variance is the reciprocal of the
20576sum of the reciprocals of the variances.)
20577@tex
4009494e
GM
20578$$ \sigma_\mu^2 = {1 \over \displaystyle \sum {1 \over \sigma_i^2}} $$
20579@end tex
20580If the inputs are plain
20581numbers, the error is equal to the standard deviation of the values
20582divided by the square root of the number of values. (This works
20583out to be equivalent to calculating the standard deviation and
20584then assuming each value's error is equal to this standard
20585deviation.)
20586@tex
4009494e
GM
20587$$ \sigma_\mu^2 = {\sigma^2 \over N} $$
20588@end tex
20589
20590@kindex H u M
20591@pindex calc-vector-median
20592@tindex vmedian
20593@cindex Median of data values
20594The @kbd{H u M} (@code{calc-vector-median}) [@code{vmedian}]
20595command computes the median of the data values. The values are
20596first sorted into numerical order; the median is the middle
20597value after sorting. (If the number of data values is even,
20598the median is taken to be the average of the two middle values.)
20599The median function is different from the other functions in
20600this section in that the arguments must all be real numbers;
20601variables are not accepted even when nested inside vectors.
20602(Otherwise it is not possible to sort the data values.) If
20603any of the input values are error forms, their error parts are
20604ignored.
20605
20606The median function also accepts distributions. For both normal
20607(error form) and uniform (interval) distributions, the median is
20608the same as the mean.
20609
20610@kindex H I u M
20611@pindex calc-vector-harmonic-mean
20612@tindex vhmean
20613@cindex Harmonic mean
20614The @kbd{H I u M} (@code{calc-vector-harmonic-mean}) [@code{vhmean}]
20615command computes the harmonic mean of the data values. This is
20616defined as the reciprocal of the arithmetic mean of the reciprocals
20617of the values.
20618@tex
4009494e
GM
20619$$ { N \over \displaystyle \sum {1 \over x_i} } $$
20620@end tex
20621
20622@kindex u G
20623@pindex calc-vector-geometric-mean
20624@tindex vgmean
20625@cindex Geometric mean
20626The @kbd{u G} (@code{calc-vector-geometric-mean}) [@code{vgmean}]
20627command computes the geometric mean of the data values. This
20628is the @var{n}th root of the product of the values. This is also
20629equal to the @code{exp} of the arithmetic mean of the logarithms
20630of the data values.
20631@tex
4009494e
GM
20632$$ \exp \left ( \sum { \ln x_i } \right ) =
20633 \left ( \prod { x_i } \right)^{1 / N} $$
20634@end tex
20635
20636@kindex H u G
20637@tindex agmean
20638The @kbd{H u G} [@code{agmean}] command computes the ``arithmetic-geometric
20639mean'' of two numbers taken from the stack. This is computed by
20640replacing the two numbers with their arithmetic mean and geometric
20641mean, then repeating until the two values converge.
20642@tex
4009494e
GM
20643$$ a_{i+1} = { a_i + b_i \over 2 } , \qquad b_{i+1} = \sqrt{a_i b_i} $$
20644@end tex
20645
20646@cindex Root-mean-square
20647Another commonly used mean, the RMS (root-mean-square), can be computed
20648for a vector of numbers simply by using the @kbd{A} command.
20649
20650@kindex u S
20651@pindex calc-vector-sdev
20652@tindex vsdev
20653@cindex Standard deviation
20654@cindex Sample statistics
20655The @kbd{u S} (@code{calc-vector-sdev}) [@code{vsdev}] command
40ba43b4 20656computes the standard
4009494e
GM
20657@texline deviation@tie{}@math{\sigma}
20658@infoline deviation
20659of the data values. If the values are error forms, the errors are used
20660as weights just as for @kbd{u M}. This is the @emph{sample} standard
20661deviation, whose value is the square root of the sum of the squares of
20662the differences between the values and the mean of the @expr{N} values,
20663divided by @expr{N-1}.
20664@tex
4009494e
GM
20665$$ \sigma^2 = {1 \over N - 1} \sum (x_i - \mu)^2 $$
20666@end tex
20667
20668This function also applies to distributions. The standard deviation
20669of a single error form is simply the error part. The standard deviation
20670of a continuous interval happens to equal the difference between the
40ba43b4 20671limits, divided by
4009494e 20672@texline @math{\sqrt{12}}.
40ba43b4 20673@infoline @expr{sqrt(12)}.
4009494e
GM
20674The standard deviation of an integer interval is the same as the
20675standard deviation of a vector of those integers.
20676
20677@kindex I u S
20678@pindex calc-vector-pop-sdev
20679@tindex vpsdev
20680@cindex Population statistics
20681The @kbd{I u S} (@code{calc-vector-pop-sdev}) [@code{vpsdev}]
20682command computes the @emph{population} standard deviation.
20683It is defined by the same formula as above but dividing
20684by @expr{N} instead of by @expr{N-1}. The population standard
20685deviation is used when the input represents the entire set of
20686data values in the distribution; the sample standard deviation
20687is used when the input represents a sample of the set of all
20688data values, so that the mean computed from the input is itself
20689only an estimate of the true mean.
20690@tex
4009494e
GM
20691$$ \sigma^2 = {1 \over N} \sum (x_i - \mu)^2 $$
20692@end tex
20693
20694For error forms and continuous intervals, @code{vpsdev} works
20695exactly like @code{vsdev}. For integer intervals, it computes the
20696population standard deviation of the equivalent vector of integers.
20697
20698@kindex H u S
20699@kindex H I u S
20700@pindex calc-vector-variance
20701@pindex calc-vector-pop-variance
20702@tindex vvar
20703@tindex vpvar
20704@cindex Variance of data values
20705The @kbd{H u S} (@code{calc-vector-variance}) [@code{vvar}] and
20706@kbd{H I u S} (@code{calc-vector-pop-variance}) [@code{vpvar}]
20707commands compute the variance of the data values. The variance
40ba43b4 20708is the
4009494e
GM
20709@texline square@tie{}@math{\sigma^2}
20710@infoline square
20711of the standard deviation, i.e., the sum of the
20712squares of the deviations of the data values from the mean.
20713(This definition also applies when the argument is a distribution.)
20714
20715@ignore
20716@starindex
20717@end ignore
20718@tindex vflat
20719The @code{vflat} algebraic function returns a vector of its
20720arguments, interpreted in the same way as the other functions
20721in this section. For example, @samp{vflat(1, [2, [3, 4]], 5)}
20722returns @samp{[1, 2, 3, 4, 5]}.
20723
20724@node Paired-Sample Statistics, , Single-Variable Statistics, Statistical Operations
20725@subsection Paired-Sample Statistics
20726
20727@noindent
20728The functions in this section take two arguments, which must be
20729vectors of equal size. The vectors are each flattened in the same
20730way as by the single-variable statistical functions. Given a numeric
20731prefix argument of 1, these functions instead take one object from
40ba43b4 20732the stack, which must be an
4009494e
GM
20733@texline @math{N\times2}
20734@infoline Nx2
20735matrix of data values. Once again, variable names can be used in place
20736of actual vectors and matrices.
20737
20738@kindex u C
20739@pindex calc-vector-covariance
20740@tindex vcov
20741@cindex Covariance
20742The @kbd{u C} (@code{calc-vector-covariance}) [@code{vcov}] command
20743computes the sample covariance of two vectors. The covariance
20744of vectors @var{x} and @var{y} is the sum of the products of the
20745differences between the elements of @var{x} and the mean of @var{x}
20746times the differences between the corresponding elements of @var{y}
20747and the mean of @var{y}, all divided by @expr{N-1}. Note that
20748the variance of a vector is just the covariance of the vector
20749with itself. Once again, if the inputs are error forms the
20750errors are used as weight factors. If both @var{x} and @var{y}
20751are composed of error forms, the error for a given data point
20752is taken as the square root of the sum of the squares of the two
20753input errors.
20754@tex
4009494e
GM
20755$$ \sigma_{x\!y}^2 = {1 \over N-1} \sum (x_i - \mu_x) (y_i - \mu_y) $$
20756$$ \sigma_{x\!y}^2 =
20757 {\displaystyle {1 \over N-1}
20758 \sum {(x_i - \mu_x) (y_i - \mu_y) \over \sigma_i^2}
20759 \over \displaystyle {1 \over N} \sum {1 \over \sigma_i^2}}
20760$$
20761@end tex
20762
20763@kindex I u C
20764@pindex calc-vector-pop-covariance
20765@tindex vpcov
20766The @kbd{I u C} (@code{calc-vector-pop-covariance}) [@code{vpcov}]
20767command computes the population covariance, which is the same as the
20768sample covariance computed by @kbd{u C} except dividing by @expr{N}
20769instead of @expr{N-1}.
20770
20771@kindex H u C
20772@pindex calc-vector-correlation
20773@tindex vcorr
20774@cindex Correlation coefficient
20775@cindex Linear correlation
20776The @kbd{H u C} (@code{calc-vector-correlation}) [@code{vcorr}]
20777command computes the linear correlation coefficient of two vectors.
20778This is defined by the covariance of the vectors divided by the
20779product of their standard deviations. (There is no difference
20780between sample or population statistics here.)
20781@tex
4009494e
GM
20782$$ r_{x\!y} = { \sigma_{x\!y}^2 \over \sigma_x^2 \sigma_y^2 } $$
20783@end tex
20784
20785@node Reducing and Mapping, Vector and Matrix Formats, Statistical Operations, Matrix Functions
20786@section Reducing and Mapping Vectors
20787
20788@noindent
20789The commands in this section allow for more general operations on the
20790elements of vectors.
20791
65d0154b 20792@kindex v A
4009494e
GM
20793@kindex V A
20794@pindex calc-apply
20795@tindex apply
20796The simplest of these operations is @kbd{V A} (@code{calc-apply})
20797[@code{apply}], which applies a given operator to the elements of a vector.
20798For example, applying the hypothetical function @code{f} to the vector
20799@w{@samp{[1, 2, 3]}} would produce the function call @samp{f(1, 2, 3)}.
20800Applying the @code{+} function to the vector @samp{[a, b]} gives
20801@samp{a + b}. Applying @code{+} to the vector @samp{[a, b, c]} is an
20802error, since the @code{+} function expects exactly two arguments.
20803
20804While @kbd{V A} is useful in some cases, you will usually find that either
20805@kbd{V R} or @kbd{V M}, described below, is closer to what you want.
20806
20807@menu
20808* Specifying Operators::
20809* Mapping::
20810* Reducing::
20811* Nesting and Fixed Points::
20812* Generalized Products::
20813@end menu
20814
20815@node Specifying Operators, Mapping, Reducing and Mapping, Reducing and Mapping
20816@subsection Specifying Operators
20817
20818@noindent
20819Commands in this section (like @kbd{V A}) prompt you to press the key
20820corresponding to the desired operator. Press @kbd{?} for a partial
20821list of the available operators. Generally, an operator is any key or
20822sequence of keys that would normally take one or more arguments from
20823the stack and replace them with a result. For example, @kbd{V A H C}
20824uses the hyperbolic cosine operator, @code{cosh}. (Since @code{cosh}
20825expects one argument, @kbd{V A H C} requires a vector with a single
20826element as its argument.)
20827
20828You can press @kbd{x} at the operator prompt to select any algebraic
20829function by name to use as the operator. This includes functions you
20830have defined yourself using the @kbd{Z F} command. (@xref{Algebraic
20831Definitions}.) If you give a name for which no function has been
20832defined, the result is left in symbolic form, as in @samp{f(1, 2, 3)}.
20833Calc will prompt for the number of arguments the function takes if it
20834can't figure it out on its own (say, because you named a function that
20835is currently undefined). It is also possible to type a digit key before
20836the function name to specify the number of arguments, e.g.,
20837@kbd{V M 3 x f @key{RET}} calls @code{f} with three arguments even if it
20838looks like it ought to have only two. This technique may be necessary
20839if the function allows a variable number of arguments. For example,
20840the @kbd{v e} [@code{vexp}] function accepts two or three arguments;
20841if you want to map with the three-argument version, you will have to
20842type @kbd{V M 3 v e}.
20843
20844It is also possible to apply any formula to a vector by treating that
20845formula as a function. When prompted for the operator to use, press
20846@kbd{'} (the apostrophe) and type your formula as an algebraic entry.
20847You will then be prompted for the argument list, which defaults to a
20848list of all variables that appear in the formula, sorted into alphabetic
20849order. For example, suppose you enter the formula @w{@samp{x + 2y^x}}.
20850The default argument list would be @samp{(x y)}, which means that if
20851this function is applied to the arguments @samp{[3, 10]} the result will
20852be @samp{3 + 2*10^3}. (If you plan to use a certain formula in this
20853way often, you might consider defining it as a function with @kbd{Z F}.)
20854
20855Another way to specify the arguments to the formula you enter is with
20856@kbd{$}, @kbd{$$}, and so on. For example, @kbd{V A ' $$ + 2$^$$}
20857has the same effect as the previous example. The argument list is
20858automatically taken to be @samp{($$ $)}. (The order of the arguments
20859may seem backwards, but it is analogous to the way normal algebraic
20860entry interacts with the stack.)
20861
20862If you press @kbd{$} at the operator prompt, the effect is similar to
20863the apostrophe except that the relevant formula is taken from top-of-stack
20864instead. The actual vector arguments of the @kbd{V A $} or related command
20865then start at the second-to-top stack position. You will still be
20866prompted for an argument list.
20867
20868@cindex Nameless functions
20869@cindex Generic functions
20870A function can be written without a name using the notation @samp{<#1 - #2>},
20871which means ``a function of two arguments that computes the first
20872argument minus the second argument.'' The symbols @samp{#1} and @samp{#2}
20873are placeholders for the arguments. You can use any names for these
20874placeholders if you wish, by including an argument list followed by a
20875colon: @samp{<x, y : x - y>}. When you type @kbd{V A ' $$ + 2$^$$ @key{RET}},
20876Calc builds the nameless function @samp{<#1 + 2 #2^#1>} as the function
20877to map across the vectors. When you type @kbd{V A ' x + 2y^x @key{RET} @key{RET}},
20878Calc builds the nameless function @w{@samp{<x, y : x + 2 y^x>}}. In both
20879cases, Calc also writes the nameless function to the Trail so that you
20880can get it back later if you wish.
20881
20882If there is only one argument, you can write @samp{#} in place of @samp{#1}.
20883(Note that @samp{< >} notation is also used for date forms. Calc tells
20884that @samp{<@var{stuff}>} is a nameless function by the presence of
20885@samp{#} signs inside @var{stuff}, or by the fact that @var{stuff}
20886begins with a list of variables followed by a colon.)
20887
20888You can type a nameless function directly to @kbd{V A '}, or put one on
20889the stack and use it with @w{@kbd{V A $}}. Calc will not prompt for an
20890argument list in this case, since the nameless function specifies the
20891argument list as well as the function itself. In @kbd{V A '}, you can
20892omit the @samp{< >} marks if you use @samp{#} notation for the arguments,
20893so that @kbd{V A ' #1+#2 @key{RET}} is the same as @kbd{V A ' <#1+#2> @key{RET}},
20894which in turn is the same as @kbd{V A ' $$+$ @key{RET}}.
20895
20896@cindex Lambda expressions
20897@ignore
20898@starindex
20899@end ignore
20900@tindex lambda
20901The internal format for @samp{<x, y : x + y>} is @samp{lambda(x, y, x + y)}.
20902(The word @code{lambda} derives from Lisp notation and the theory of
20903functions.) The internal format for @samp{<#1 + #2>} is @samp{lambda(ArgA,
20904ArgB, ArgA + ArgB)}. Note that there is no actual Calc function called
20905@code{lambda}; the whole point is that the @code{lambda} expression is
20906used in its symbolic form, not evaluated for an answer until it is applied
20907to specific arguments by a command like @kbd{V A} or @kbd{V M}.
20908
20909(Actually, @code{lambda} does have one special property: Its arguments
20910are never evaluated; for example, putting @samp{<(2/3) #>} on the stack
20911will not simplify the @samp{2/3} until the nameless function is actually
20912called.)
20913
20914@tindex add
20915@tindex sub
20916@ignore
20917@mindex @idots
20918@end ignore
20919@tindex mul
20920@ignore
20921@mindex @null
20922@end ignore
20923@tindex div
20924@ignore
20925@mindex @null
20926@end ignore
20927@tindex pow
20928@ignore
20929@mindex @null
20930@end ignore
20931@tindex neg
20932@ignore
20933@mindex @null
20934@end ignore
20935@tindex mod
20936@ignore
20937@mindex @null
20938@end ignore
20939@tindex vconcat
20940As usual, commands like @kbd{V A} have algebraic function name equivalents.
20941For example, @kbd{V A k g} with an argument of @samp{v} is equivalent to
20942@samp{apply(gcd, v)}. The first argument specifies the operator name,
20943and is either a variable whose name is the same as the function name,
20944or a nameless function like @samp{<#^3+1>}. Operators that are normally
20945written as algebraic symbols have the names @code{add}, @code{sub},
20946@code{mul}, @code{div}, @code{pow}, @code{neg}, @code{mod}, and
20947@code{vconcat}.
20948
20949@ignore
20950@starindex
20951@end ignore
20952@tindex call
20953The @code{call} function builds a function call out of several arguments:
20954@samp{call(gcd, x, y)} is the same as @samp{apply(gcd, [x, y])}, which
20955in turn is the same as @samp{gcd(x, y)}. The first argument of @code{call},
20956like the other functions described here, may be either a variable naming a
20957function, or a nameless function (@samp{call(<#1+2#2>, x, y)} is the same
20958as @samp{x + 2y}).
20959
20960(Experts will notice that it's not quite proper to use a variable to name
20961a function, since the name @code{gcd} corresponds to the Lisp variable
20962@code{var-gcd} but to the Lisp function @code{calcFunc-gcd}. Calc
20963automatically makes this translation, so you don't have to worry
20964about it.)
20965
20966@node Mapping, Reducing, Specifying Operators, Reducing and Mapping
20967@subsection Mapping
20968
20969@noindent
65d0154b 20970@kindex v M
4009494e
GM
20971@kindex V M
20972@pindex calc-map
20973@tindex map
20974The @kbd{V M} (@code{calc-map}) [@code{map}] command applies a given
20975operator elementwise to one or more vectors. For example, mapping
20976@code{A} [@code{abs}] produces a vector of the absolute values of the
20977elements in the input vector. Mapping @code{+} pops two vectors from
20978the stack, which must be of equal length, and produces a vector of the
20979pairwise sums of the elements. If either argument is a non-vector, it
20980is duplicated for each element of the other vector. For example,
20981@kbd{[1,2,3] 2 V M ^} squares the elements of the specified vector.
20982With the 2 listed first, it would have computed a vector of powers of
20983two. Mapping a user-defined function pops as many arguments from the
20984stack as the function requires. If you give an undefined name, you will
20985be prompted for the number of arguments to use.
20986
20987If any argument to @kbd{V M} is a matrix, the operator is normally mapped
20988across all elements of the matrix. For example, given the matrix
20989@expr{[[1, -2, 3], [-4, 5, -6]]}, @kbd{V M A} takes six absolute values to
40ba43b4 20990produce another
4009494e
GM
20991@texline @math{3\times2}
20992@infoline 3x2
20993matrix, @expr{[[1, 2, 3], [4, 5, 6]]}.
20994
20995@tindex mapr
20996The command @kbd{V M _} [@code{mapr}] (i.e., type an underscore at the
20997operator prompt) maps by rows instead. For example, @kbd{V M _ A} views
20998the above matrix as a vector of two 3-element row vectors. It produces
20999a new vector which contains the absolute values of those row vectors,
21000namely @expr{[3.74, 8.77]}. (Recall, the absolute value of a vector is
21001defined as the square root of the sum of the squares of the elements.)
21002Some operators accept vectors and return new vectors; for example,
21003@kbd{v v} reverses a vector, so @kbd{V M _ v v} would reverse each row
21004of the matrix to get a new matrix, @expr{[[3, -2, 1], [-6, 5, -4]]}.
21005
21006Sometimes a vector of vectors (representing, say, strings, sets, or lists)
21007happens to look like a matrix. If so, remember to use @kbd{V M _} if you
21008want to map a function across the whole strings or sets rather than across
21009their individual elements.
21010
21011@tindex mapc
21012The command @kbd{V M :} [@code{mapc}] maps by columns. Basically, it
21013transposes the input matrix, maps by rows, and then, if the result is a
21014matrix, transposes again. For example, @kbd{V M : A} takes the absolute
21015values of the three columns of the matrix, treating each as a 2-vector,
21016and @kbd{V M : v v} reverses the columns to get the matrix
21017@expr{[[-4, 5, -6], [1, -2, 3]]}.
21018
21019(The symbols @kbd{_} and @kbd{:} were chosen because they had row-like
21020and column-like appearances, and were not already taken by useful
21021operators. Also, they appear shifted on most keyboards so they are easy
21022to type after @kbd{V M}.)
21023
21024The @kbd{_} and @kbd{:} modifiers have no effect on arguments that are
21025not matrices (so if none of the arguments are matrices, they have no
21026effect at all). If some of the arguments are matrices and others are
21027plain numbers, the plain numbers are held constant for all rows of the
21028matrix (so that @kbd{2 V M _ ^} squares every row of a matrix; squaring
21029a vector takes a dot product of the vector with itself).
21030
21031If some of the arguments are vectors with the same lengths as the
21032rows (for @kbd{V M _}) or columns (for @kbd{V M :}) of the matrix
21033arguments, those vectors are also held constant for every row or
21034column.
21035
21036Sometimes it is useful to specify another mapping command as the operator
21037to use with @kbd{V M}. For example, @kbd{V M _ V A +} applies @kbd{V A +}
21038to each row of the input matrix, which in turn adds the two values on that
21039row. If you give another vector-operator command as the operator for
21040@kbd{V M}, it automatically uses map-by-rows mode if you don't specify
21041otherwise; thus @kbd{V M V A +} is equivalent to @kbd{V M _ V A +}. (If
21042you really want to map-by-elements another mapping command, you can use
21043a triple-nested mapping command: @kbd{V M V M V A +} means to map
21044@kbd{V M V A +} over the rows of the matrix; in turn, @kbd{V A +} is
21045mapped over the elements of each row.)
21046
21047@tindex mapa
21048@tindex mapd
21049Previous versions of Calc had ``map across'' and ``map down'' modes
21050that are now considered obsolete; the old ``map across'' is now simply
21051@kbd{V M V A}, and ``map down'' is now @kbd{V M : V A}. The algebraic
21052functions @code{mapa} and @code{mapd} are still supported, though.
21053Note also that, while the old mapping modes were persistent (once you
21054set the mode, it would apply to later mapping commands until you reset
21055it), the new @kbd{:} and @kbd{_} modifiers apply only to the current
21056mapping command. The default @kbd{V M} always means map-by-elements.
21057
21058@xref{Algebraic Manipulation}, for the @kbd{a M} command, which is like
21059@kbd{V M} but for equations and inequalities instead of vectors.
21060@xref{Storing Variables}, for the @kbd{s m} command which modifies a
21061variable's stored value using a @kbd{V M}-like operator.
21062
21063@node Reducing, Nesting and Fixed Points, Mapping, Reducing and Mapping
21064@subsection Reducing
21065
21066@noindent
65d0154b 21067@kindex v R
4009494e
GM
21068@kindex V R
21069@pindex calc-reduce
21070@tindex reduce
21071The @kbd{V R} (@code{calc-reduce}) [@code{reduce}] command applies a given
21072binary operator across all the elements of a vector. A binary operator is
21073a function such as @code{+} or @code{max} which takes two arguments. For
21074example, reducing @code{+} over a vector computes the sum of the elements
21075of the vector. Reducing @code{-} computes the first element minus each of
21076the remaining elements. Reducing @code{max} computes the maximum element
21077and so on. In general, reducing @code{f} over the vector @samp{[a, b, c, d]}
21078produces @samp{f(f(f(a, b), c), d)}.
21079
65d0154b 21080@kindex I v R
4009494e
GM
21081@kindex I V R
21082@tindex rreduce
21083The @kbd{I V R} [@code{rreduce}] command is similar to @kbd{V R} except
21084that works from right to left through the vector. For example, plain
21085@kbd{V R -} on the vector @samp{[a, b, c, d]} produces @samp{a - b - c - d}
21086but @kbd{I V R -} on the same vector produces @samp{a - (b - (c - d))},
21087or @samp{a - b + c - d}. This ``alternating sum'' occurs frequently
21088in power series expansions.
21089
65d0154b 21090@kindex v U
4009494e
GM
21091@kindex V U
21092@tindex accum
21093The @kbd{V U} (@code{calc-accumulate}) [@code{accum}] command does an
21094accumulation operation. Here Calc does the corresponding reduction
21095operation, but instead of producing only the final result, it produces
21096a vector of all the intermediate results. Accumulating @code{+} over
21097the vector @samp{[a, b, c, d]} produces the vector
21098@samp{[a, a + b, a + b + c, a + b + c + d]}.
21099
65d0154b 21100@kindex I v U
4009494e
GM
21101@kindex I V U
21102@tindex raccum
21103The @kbd{I V U} [@code{raccum}] command does a right-to-left accumulation.
21104For example, @kbd{I V U -} on the vector @samp{[a, b, c, d]} produces the
21105vector @samp{[a - b + c - d, b - c + d, c - d, d]}.
21106
21107@tindex reducea
21108@tindex rreducea
21109@tindex reduced
21110@tindex rreduced
21111As for @kbd{V M}, @kbd{V R} normally reduces a matrix elementwise. For
21112example, given the matrix @expr{[[a, b, c], [d, e, f]]}, @kbd{V R +} will
21113compute @expr{a + b + c + d + e + f}. You can type @kbd{V R _} or
21114@kbd{V R :} to modify this behavior. The @kbd{V R _} [@code{reducea}]
21115command reduces ``across'' the matrix; it reduces each row of the matrix
21116as a vector, then collects the results. Thus @kbd{V R _ +} of this
21117matrix would produce @expr{[a + b + c, d + e + f]}. Similarly, @kbd{V R :}
21118[@code{reduced}] reduces down; @kbd{V R : +} would produce @expr{[a + d,
21119b + e, c + f]}.
21120
21121@tindex reducer
21122@tindex rreducer
21123There is a third ``by rows'' mode for reduction that is occasionally
21124useful; @kbd{V R =} [@code{reducer}] simply reduces the operator over
21125the rows of the matrix themselves. Thus @kbd{V R = +} on the above
21126matrix would get the same result as @kbd{V R : +}, since adding two
21127row vectors is equivalent to adding their elements. But @kbd{V R = *}
21128would multiply the two rows (to get a single number, their dot product),
21129while @kbd{V R : *} would produce a vector of the products of the columns.
21130
21131These three matrix reduction modes work with @kbd{V R} and @kbd{I V R},
21132but they are not currently supported with @kbd{V U} or @kbd{I V U}.
21133
21134@tindex reducec
21135@tindex rreducec
21136The obsolete reduce-by-columns function, @code{reducec}, is still
21137supported but there is no way to get it through the @kbd{V R} command.
21138
21139The commands @kbd{C-x * :} and @kbd{C-x * _} are equivalent to typing
21140@kbd{C-x * r} to grab a rectangle of data into Calc, and then typing
21141@kbd{V R : +} or @kbd{V R _ +}, respectively, to sum the columns or
21142rows of the matrix. @xref{Grabbing From Buffers}.
21143
21144@node Nesting and Fixed Points, Generalized Products, Reducing, Reducing and Mapping
21145@subsection Nesting and Fixed Points
21146
21147@noindent
65d0154b 21148@kindex H v R
4009494e
GM
21149@kindex H V R
21150@tindex nest
21151The @kbd{H V R} [@code{nest}] command applies a function to a given
21152argument repeatedly. It takes two values, @samp{a} and @samp{n}, from
21153the stack, where @samp{n} must be an integer. It then applies the
21154function nested @samp{n} times; if the function is @samp{f} and @samp{n}
21155is 3, the result is @samp{f(f(f(a)))}. The number @samp{n} may be
21156negative if Calc knows an inverse for the function @samp{f}; for
21157example, @samp{nest(sin, a, -2)} returns @samp{arcsin(arcsin(a))}.
21158
65d0154b 21159@kindex H v U
4009494e
GM
21160@kindex H V U
21161@tindex anest
21162The @kbd{H V U} [@code{anest}] command is an accumulating version of
21163@code{nest}: It returns a vector of @samp{n+1} values, e.g.,
21164@samp{[a, f(a), f(f(a)), f(f(f(a)))]}. If @samp{n} is negative and
21165@samp{F} is the inverse of @samp{f}, then the result is of the
21166form @samp{[a, F(a), F(F(a)), F(F(F(a)))]}.
21167
65d0154b 21168@kindex H I v R
4009494e
GM
21169@kindex H I V R
21170@tindex fixp
21171@cindex Fixed points
21172The @kbd{H I V R} [@code{fixp}] command is like @kbd{H V R}, except
21173that it takes only an @samp{a} value from the stack; the function is
21174applied until it reaches a ``fixed point,'' i.e., until the result
21175no longer changes.
21176
65d0154b 21177@kindex H I v U
4009494e
GM
21178@kindex H I V U
21179@tindex afixp
21180The @kbd{H I V U} [@code{afixp}] command is an accumulating @code{fixp}.
21181The first element of the return vector will be the initial value @samp{a};
21182the last element will be the final result that would have been returned
21183by @code{fixp}.
21184
21185For example, 0.739085 is a fixed point of the cosine function (in radians):
21186@samp{cos(0.739085) = 0.739085}. You can find this value by putting, say,
211871.0 on the stack and typing @kbd{H I V U C}. (We use the accumulating
21188version so we can see the intermediate results: @samp{[1, 0.540302, 0.857553,
211890.65329, ...]}. With a precision of six, this command will take 36 steps
21190to converge to 0.739085.)
21191
21192Newton's method for finding roots is a classic example of iteration
21193to a fixed point. To find the square root of five starting with an
21194initial guess, Newton's method would look for a fixed point of the
21195function @samp{(x + 5/x) / 2}. Putting a guess of 1 on the stack
21196and typing @kbd{H I V R ' ($ + 5/$)/2 @key{RET}} quickly yields the result
211972.23607. This is equivalent to using the @kbd{a R} (@code{calc-find-root})
21198command to find a root of the equation @samp{x^2 = 5}.
21199
21200These examples used numbers for @samp{a} values. Calc keeps applying
21201the function until two successive results are equal to within the
21202current precision. For complex numbers, both the real parts and the
21203imaginary parts must be equal to within the current precision. If
21204@samp{a} is a formula (say, a variable name), then the function is
21205applied until two successive results are exactly the same formula.
21206It is up to you to ensure that the function will eventually converge;
21207if it doesn't, you may have to press @kbd{C-g} to stop the Calculator.
21208
21209The algebraic @code{fixp} function takes two optional arguments, @samp{n}
21210and @samp{tol}. The first is the maximum number of steps to be allowed,
21211and must be either an integer or the symbol @samp{inf} (infinity, the
21212default). The second is a convergence tolerance. If a tolerance is
21213specified, all results during the calculation must be numbers, not
21214formulas, and the iteration stops when the magnitude of the difference
21215between two successive results is less than or equal to the tolerance.
21216(This implies that a tolerance of zero iterates until the results are
21217exactly equal.)
21218
21219Putting it all together, @samp{fixp(<(# + A/#)/2>, B, 20, 1e-10)}
21220computes the square root of @samp{A} given the initial guess @samp{B},
21221stopping when the result is correct within the specified tolerance, or
21222when 20 steps have been taken, whichever is sooner.
21223
21224@node Generalized Products, , Nesting and Fixed Points, Reducing and Mapping
21225@subsection Generalized Products
21226
65d0154b 21227@kindex v O
4009494e
GM
21228@kindex V O
21229@pindex calc-outer-product
21230@tindex outer
21231The @kbd{V O} (@code{calc-outer-product}) [@code{outer}] command applies
21232a given binary operator to all possible pairs of elements from two
21233vectors, to produce a matrix. For example, @kbd{V O *} with @samp{[a, b]}
21234and @samp{[x, y, z]} on the stack produces a multiplication table:
21235@samp{[[a x, a y, a z], [b x, b y, b z]]}. Element @var{r},@var{c} of
21236the result matrix is obtained by applying the operator to element @var{r}
21237of the lefthand vector and element @var{c} of the righthand vector.
21238
65d0154b 21239@kindex v I
4009494e
GM
21240@kindex V I
21241@pindex calc-inner-product
21242@tindex inner
21243The @kbd{V I} (@code{calc-inner-product}) [@code{inner}] command computes
21244the generalized inner product of two vectors or matrices, given a
21245``multiplicative'' operator and an ``additive'' operator. These can each
21246actually be any binary operators; if they are @samp{*} and @samp{+},
21247respectively, the result is a standard matrix multiplication. Element
21248@var{r},@var{c} of the result matrix is obtained by mapping the
21249multiplicative operator across row @var{r} of the lefthand matrix and
21250column @var{c} of the righthand matrix, and then reducing with the additive
21251operator. Just as for the standard @kbd{*} command, this can also do a
21252vector-matrix or matrix-vector inner product, or a vector-vector
21253generalized dot product.
21254
21255Since @kbd{V I} requires two operators, it prompts twice. In each case,
21256you can use any of the usual methods for entering the operator. If you
21257use @kbd{$} twice to take both operator formulas from the stack, the
21258first (multiplicative) operator is taken from the top of the stack
21259and the second (additive) operator is taken from second-to-top.
21260
21261@node Vector and Matrix Formats, , Reducing and Mapping, Matrix Functions
21262@section Vector and Matrix Display Formats
21263
21264@noindent
21265Commands for controlling vector and matrix display use the @kbd{v} prefix
21266instead of the usual @kbd{d} prefix. But they are display modes; in
21267particular, they are influenced by the @kbd{I} and @kbd{H} prefix keys
21268in the same way (@pxref{Display Modes}). Matrix display is also
21269influenced by the @kbd{d O} (@code{calc-flat-language}) mode;
21270@pxref{Normal Language Modes}.
21271
65d0154b 21272@kindex v <
4009494e
GM
21273@kindex V <
21274@pindex calc-matrix-left-justify
65d0154b 21275@kindex v =
4009494e
GM
21276@kindex V =
21277@pindex calc-matrix-center-justify
65d0154b 21278@kindex v >
4009494e
GM
21279@kindex V >
21280@pindex calc-matrix-right-justify
21281The commands @kbd{v <} (@code{calc-matrix-left-justify}), @kbd{v >}
21282(@code{calc-matrix-right-justify}), and @w{@kbd{v =}}
21283(@code{calc-matrix-center-justify}) control whether matrix elements
21284are justified to the left, right, or center of their columns.
21285
65d0154b 21286@kindex v [
4009494e
GM
21287@kindex V [
21288@pindex calc-vector-brackets
65d0154b 21289@kindex v @{
4009494e
GM
21290@kindex V @{
21291@pindex calc-vector-braces
65d0154b 21292@kindex v (
4009494e
GM
21293@kindex V (
21294@pindex calc-vector-parens
21295The @kbd{v [} (@code{calc-vector-brackets}) command turns the square
21296brackets that surround vectors and matrices displayed in the stack on
21297and off. The @kbd{v @{} (@code{calc-vector-braces}) and @kbd{v (}
21298(@code{calc-vector-parens}) commands use curly braces or parentheses,
21299respectively, instead of square brackets. For example, @kbd{v @{} might
21300be used in preparation for yanking a matrix into a buffer running
21301Mathematica. (In fact, the Mathematica language mode uses this mode;
21302@pxref{Mathematica Language Mode}.) Note that, regardless of the
21303display mode, either brackets or braces may be used to enter vectors,
21304and parentheses may never be used for this purpose.
21305
21306@kindex V ]
65d0154b
JB
21307@kindex v ]
21308@kindex V )
21309@kindex v )
21310@kindex V @}
21311@kindex v @}
4009494e
GM
21312@pindex calc-matrix-brackets
21313The @kbd{v ]} (@code{calc-matrix-brackets}) command controls the
65d0154b
JB
21314``big'' style display of matrices, for matrices which have more than
21315one row. It prompts for a string of code letters; currently
21316implemented letters are @code{R}, which enables brackets on each row
21317of the matrix; @code{O}, which enables outer brackets in opposite
21318corners of the matrix; and @code{C}, which enables commas or
21319semicolons at the ends of all rows but the last. The default format
21320is @samp{RO}. (Before Calc 2.00, the format was fixed at @samp{ROC}.)
21321Here are some example matrices:
4009494e
GM
21322
21323@example
21324@group
21325[ [ 123, 0, 0 ] [ [ 123, 0, 0 ],
21326 [ 0, 123, 0 ] [ 0, 123, 0 ],
21327 [ 0, 0, 123 ] ] [ 0, 0, 123 ] ]
21328
21329 RO ROC
21330
21331@end group
21332@end example
21333@noindent
21334@example
21335@group
21336 [ 123, 0, 0 [ 123, 0, 0 ;
21337 0, 123, 0 0, 123, 0 ;
21338 0, 0, 123 ] 0, 0, 123 ]
21339
21340 O OC
21341
21342@end group
21343@end example
21344@noindent
21345@example
21346@group
21347 [ 123, 0, 0 ] 123, 0, 0
21348 [ 0, 123, 0 ] 0, 123, 0
21349 [ 0, 0, 123 ] 0, 0, 123
21350
21351 R @r{blank}
21352@end group
21353@end example
21354
21355@noindent
21356Note that of the formats shown here, @samp{RO}, @samp{ROC}, and
21357@samp{OC} are all recognized as matrices during reading, while
21358the others are useful for display only.
21359
65d0154b 21360@kindex v ,
4009494e
GM
21361@kindex V ,
21362@pindex calc-vector-commas
21363The @kbd{v ,} (@code{calc-vector-commas}) command turns commas on and
21364off in vector and matrix display.
21365
21366In vectors of length one, and in all vectors when commas have been
21367turned off, Calc adds extra parentheses around formulas that might
21368otherwise be ambiguous. For example, @samp{[a b]} could be a vector
21369of the one formula @samp{a b}, or it could be a vector of two
21370variables with commas turned off. Calc will display the former
21371case as @samp{[(a b)]}. You can disable these extra parentheses
21372(to make the output less cluttered at the expense of allowing some
21373ambiguity) by adding the letter @code{P} to the control string you
21374give to @kbd{v ]} (as described above).
21375
65d0154b 21376@kindex v .
4009494e
GM
21377@kindex V .
21378@pindex calc-full-vectors
21379The @kbd{v .} (@code{calc-full-vectors}) command turns abbreviated
21380display of long vectors on and off. In this mode, vectors of six
21381or more elements, or matrices of six or more rows or columns, will
21382be displayed in an abbreviated form that displays only the first
21383three elements and the last element: @samp{[a, b, c, ..., z]}.
21384When very large vectors are involved this will substantially
21385improve Calc's display speed.
21386
21387@kindex t .
21388@pindex calc-full-trail-vectors
21389The @kbd{t .} (@code{calc-full-trail-vectors}) command controls a
21390similar mode for recording vectors in the Trail. If you turn on
21391this mode, vectors of six or more elements and matrices of six or
21392more rows or columns will be abbreviated when they are put in the
21393Trail. The @kbd{t y} (@code{calc-trail-yank}) command will be
21394unable to recover those vectors. If you are working with very
21395large vectors, this mode will improve the speed of all operations
21396that involve the trail.
21397
65d0154b 21398@kindex v /
4009494e
GM
21399@kindex V /
21400@pindex calc-break-vectors
21401The @kbd{v /} (@code{calc-break-vectors}) command turns multi-line
21402vector display on and off. Normally, matrices are displayed with one
21403row per line but all other types of vectors are displayed in a single
21404line. This mode causes all vectors, whether matrices or not, to be
21405displayed with a single element per line. Sub-vectors within the
21406vectors will still use the normal linear form.
21407
21408@node Algebra, Units, Matrix Functions, Top
21409@chapter Algebra
21410
21411@noindent
21412This section covers the Calc features that help you work with
21413algebraic formulas. First, the general sub-formula selection
21414mechanism is described; this works in conjunction with any Calc
21415commands. Then, commands for specific algebraic operations are
21416described. Finally, the flexible @dfn{rewrite rule} mechanism
21417is discussed.
21418
21419The algebraic commands use the @kbd{a} key prefix; selection
21420commands use the @kbd{j} (for ``just a letter that wasn't used
21421for anything else'') prefix.
21422
21423@xref{Editing Stack Entries}, to see how to manipulate formulas
21424using regular Emacs editing commands.
21425
21426When doing algebraic work, you may find several of the Calculator's
21427modes to be helpful, including Algebraic Simplification mode (@kbd{m A})
21428or No-Simplification mode (@kbd{m O}),
21429Algebraic entry mode (@kbd{m a}), Fraction mode (@kbd{m f}), and
21430Symbolic mode (@kbd{m s}). @xref{Mode Settings}, for discussions
21431of these modes. You may also wish to select Big display mode (@kbd{d B}).
21432@xref{Normal Language Modes}.
21433
21434@menu
21435* Selecting Subformulas::
21436* Algebraic Manipulation::
21437* Simplifying Formulas::
21438* Polynomials::
21439* Calculus::
21440* Solving Equations::
21441* Numerical Solutions::
21442* Curve Fitting::
21443* Summations::
21444* Logical Operations::
21445* Rewrite Rules::
21446@end menu
21447
21448@node Selecting Subformulas, Algebraic Manipulation, Algebra, Algebra
21449@section Selecting Sub-Formulas
21450
21451@noindent
21452@cindex Selections
21453@cindex Sub-formulas
21454@cindex Parts of formulas
21455When working with an algebraic formula it is often necessary to
21456manipulate a portion of the formula rather than the formula as a
21457whole. Calc allows you to ``select'' a portion of any formula on
21458the stack. Commands which would normally operate on that stack
21459entry will now operate only on the sub-formula, leaving the
21460surrounding part of the stack entry alone.
21461
21462One common non-algebraic use for selection involves vectors. To work
21463on one element of a vector in-place, simply select that element as a
21464``sub-formula'' of the vector.
21465
21466@menu
21467* Making Selections::
21468* Changing Selections::
21469* Displaying Selections::
21470* Operating on Selections::
21471* Rearranging with Selections::
21472@end menu
21473
21474@node Making Selections, Changing Selections, Selecting Subformulas, Selecting Subformulas
21475@subsection Making Selections
21476
21477@noindent
21478@kindex j s
21479@pindex calc-select-here
21480To select a sub-formula, move the Emacs cursor to any character in that
21481sub-formula, and press @w{@kbd{j s}} (@code{calc-select-here}). Calc will
21482highlight the smallest portion of the formula that contains that
21483character. By default the sub-formula is highlighted by blanking out
21484all of the rest of the formula with dots. Selection works in any
21485display mode but is perhaps easiest in Big mode (@kbd{d B}).
21486Suppose you enter the following formula:
21487
21488@smallexample
21489@group
21490 3 ___
21491 (a + b) + V c
214921: ---------------
21493 2 x + 1
21494@end group
21495@end smallexample
21496
21497@noindent
21498(by typing @kbd{' ((a+b)^3 + sqrt(c)) / (2x+1)}). If you move the
21499cursor to the letter @samp{b} and press @w{@kbd{j s}}, the display changes
21500to
21501
21502@smallexample
21503@group
21504 . ...
21505 .. . b. . . .
215061* ...............
21507 . . . .
21508@end group
21509@end smallexample
21510
21511@noindent
21512Every character not part of the sub-formula @samp{b} has been changed
2c695727
JB
21513to a dot. (If the customizable variable
21514@code{calc-highlight-selections-with-faces} is non-nil, then the characters
21515not part of the sub-formula are de-emphasized by using a less
21516noticeable face instead of using dots. @pxref{Displaying Selections}.)
21517The @samp{*} next to the line number is to remind you that
4009494e
GM
21518the formula has a portion of it selected. (In this case, it's very
21519obvious, but it might not always be. If Embedded mode is enabled,
21520the word @samp{Sel} also appears in the mode line because the stack
21521may not be visible. @pxref{Embedded Mode}.)
21522
21523If you had instead placed the cursor on the parenthesis immediately to
21524the right of the @samp{b}, the selection would have been:
21525
21526@smallexample
21527@group
21528 . ...
21529 (a + b) . . .
215301* ...............
21531 . . . .
21532@end group
21533@end smallexample
21534
21535@noindent
21536The portion selected is always large enough to be considered a complete
21537formula all by itself, so selecting the parenthesis selects the whole
21538formula that it encloses. Putting the cursor on the @samp{+} sign
21539would have had the same effect.
21540
21541(Strictly speaking, the Emacs cursor is really the manifestation of
21542the Emacs ``point,'' which is a position @emph{between} two characters
21543in the buffer. So purists would say that Calc selects the smallest
21544sub-formula which contains the character to the right of ``point.'')
21545
21546If you supply a numeric prefix argument @var{n}, the selection is
21547expanded to the @var{n}th enclosing sub-formula. Thus, positioning
21548the cursor on the @samp{b} and typing @kbd{C-u 1 j s} will select
21549@samp{a + b}; typing @kbd{C-u 2 j s} will select @samp{(a + b)^3},
21550and so on.
21551
21552If the cursor is not on any part of the formula, or if you give a
21553numeric prefix that is too large, the entire formula is selected.
21554
21555If the cursor is on the @samp{.} line that marks the top of the stack
21556(i.e., its normal ``rest position''), this command selects the entire
21557formula at stack level 1. Most selection commands similarly operate
21558on the formula at the top of the stack if you haven't positioned the
21559cursor on any stack entry.
21560
21561@kindex j a
21562@pindex calc-select-additional
21563The @kbd{j a} (@code{calc-select-additional}) command enlarges the
21564current selection to encompass the cursor. To select the smallest
21565sub-formula defined by two different points, move to the first and
21566press @kbd{j s}, then move to the other and press @kbd{j a}. This
21567is roughly analogous to using @kbd{C-@@} (@code{set-mark-command}) to
21568select the two ends of a region of text during normal Emacs editing.
21569
21570@kindex j o
21571@pindex calc-select-once
21572The @kbd{j o} (@code{calc-select-once}) command selects a formula in
21573exactly the same way as @kbd{j s}, except that the selection will
21574last only as long as the next command that uses it. For example,
21575@kbd{j o 1 +} is a handy way to add one to the sub-formula indicated
21576by the cursor.
21577
21578(A somewhat more precise definition: The @kbd{j o} command sets a flag
21579such that the next command involving selected stack entries will clear
21580the selections on those stack entries afterwards. All other selection
21581commands except @kbd{j a} and @kbd{j O} clear this flag.)
21582
21583@kindex j S
21584@kindex j O
21585@pindex calc-select-here-maybe
21586@pindex calc-select-once-maybe
21587The @kbd{j S} (@code{calc-select-here-maybe}) and @kbd{j O}
21588(@code{calc-select-once-maybe}) commands are equivalent to @kbd{j s}
21589and @kbd{j o}, respectively, except that if the formula already
21590has a selection they have no effect. This is analogous to the
21591behavior of some commands such as @kbd{j r} (@code{calc-rewrite-selection};
21592@pxref{Selections with Rewrite Rules}) and is mainly intended to be
21593used in keyboard macros that implement your own selection-oriented
21594commands.
21595
21596Selection of sub-formulas normally treats associative terms like
21597@samp{a + b - c + d} and @samp{x * y * z} as single levels of the formula.
21598If you place the cursor anywhere inside @samp{a + b - c + d} except
21599on one of the variable names and use @kbd{j s}, you will select the
21600entire four-term sum.
21601
21602@kindex j b
21603@pindex calc-break-selections
21604The @kbd{j b} (@code{calc-break-selections}) command controls a mode
21605in which the ``deep structure'' of these associative formulas shows
40ba43b4
PE
21606through. Calc actually stores the above formulas as
21607@samp{((a + b) - c) + d} and @samp{x * (y * z)}. (Note that for certain
45b778a6
JB
21608obscure reasons, by default Calc treats multiplication as
21609right-associative.) Once you have enabled @kbd{j b} mode, selecting
21610with the cursor on the @samp{-} sign would only select the @samp{a + b -
21611c} portion, which makes sense when the deep structure of the sum is
21612considered. There is no way to select the @samp{b - c + d} portion;
21613although this might initially look like just as legitimate a sub-formula
21614as @samp{a + b - c}, the deep structure shows that it isn't. The @kbd{d
21615U} command can be used to view the deep structure of any formula
21616(@pxref{Normal Language Modes}).
4009494e
GM
21617
21618When @kbd{j b} mode has not been enabled, the deep structure is
21619generally hidden by the selection commands---what you see is what
21620you get.
21621
21622@kindex j u
21623@pindex calc-unselect
21624The @kbd{j u} (@code{calc-unselect}) command unselects the formula
21625that the cursor is on. If there was no selection in the formula,
21626this command has no effect. With a numeric prefix argument, it
21627unselects the @var{n}th stack element rather than using the cursor
21628position.
21629
21630@kindex j c
21631@pindex calc-clear-selections
21632The @kbd{j c} (@code{calc-clear-selections}) command unselects all
21633stack elements.
21634
21635@node Changing Selections, Displaying Selections, Making Selections, Selecting Subformulas
21636@subsection Changing Selections
21637
21638@noindent
21639@kindex j m
21640@pindex calc-select-more
21641Once you have selected a sub-formula, you can expand it using the
21642@w{@kbd{j m}} (@code{calc-select-more}) command. If @samp{a + b} is
21643selected, pressing @w{@kbd{j m}} repeatedly works as follows:
21644
21645@smallexample
21646@group
21647 3 ... 3 ___ 3 ___
21648 (a + b) . . . (a + b) + V c (a + b) + V c
216491* ............... 1* ............... 1* ---------------
21650 . . . . . . . . 2 x + 1
21651@end group
21652@end smallexample
21653
21654@noindent
21655In the last example, the entire formula is selected. This is roughly
21656the same as having no selection at all, but because there are subtle
21657differences the @samp{*} character is still there on the line number.
21658
21659With a numeric prefix argument @var{n}, @kbd{j m} expands @var{n}
21660times (or until the entire formula is selected). Note that @kbd{j s}
21661with argument @var{n} is equivalent to plain @kbd{j s} followed by
21662@kbd{j m} with argument @var{n}. If @w{@kbd{j m}} is used when there
21663is no current selection, it is equivalent to @w{@kbd{j s}}.
21664
21665Even though @kbd{j m} does not explicitly use the location of the
21666cursor within the formula, it nevertheless uses the cursor to determine
21667which stack element to operate on. As usual, @kbd{j m} when the cursor
21668is not on any stack element operates on the top stack element.
21669
21670@kindex j l
21671@pindex calc-select-less
21672The @kbd{j l} (@code{calc-select-less}) command reduces the current
21673selection around the cursor position. That is, it selects the
21674immediate sub-formula of the current selection which contains the
21675cursor, the opposite of @kbd{j m}. If the cursor is not inside the
21676current selection, the command de-selects the formula.
21677
21678@kindex j 1-9
21679@pindex calc-select-part
21680The @kbd{j 1} through @kbd{j 9} (@code{calc-select-part}) commands
21681select the @var{n}th sub-formula of the current selection. They are
21682like @kbd{j l} (@code{calc-select-less}) except they use counting
21683rather than the cursor position to decide which sub-formula to select.
21684For example, if the current selection is @kbd{a + b + c} or
21685@kbd{f(a, b, c)} or @kbd{[a, b, c]}, then @kbd{j 1} selects @samp{a},
21686@kbd{j 2} selects @samp{b}, and @kbd{j 3} selects @samp{c}; in each of
21687these cases, @kbd{j 4} through @kbd{j 9} would be errors.
21688
21689If there is no current selection, @kbd{j 1} through @kbd{j 9} select
21690the @var{n}th top-level sub-formula. (In other words, they act as if
21691the entire stack entry were selected first.) To select the @var{n}th
21692sub-formula where @var{n} is greater than nine, you must instead invoke
21693@w{@kbd{j 1}} with @var{n} as a numeric prefix argument.
21694
21695@kindex j n
21696@kindex j p
21697@pindex calc-select-next
21698@pindex calc-select-previous
21699The @kbd{j n} (@code{calc-select-next}) and @kbd{j p}
21700(@code{calc-select-previous}) commands change the current selection
21701to the next or previous sub-formula at the same level. For example,
21702if @samp{b} is selected in @w{@samp{2 + a*b*c + x}}, then @kbd{j n}
21703selects @samp{c}. Further @kbd{j n} commands would be in error because,
21704even though there is something to the right of @samp{c} (namely, @samp{x}),
21705it is not at the same level; in this case, it is not a term of the
21706same product as @samp{b} and @samp{c}. However, @kbd{j m} (to select
21707the whole product @samp{a*b*c} as a term of the sum) followed by
21708@w{@kbd{j n}} would successfully select the @samp{x}.
21709
21710Similarly, @kbd{j p} moves the selection from the @samp{b} in this
21711sample formula to the @samp{a}. Both commands accept numeric prefix
21712arguments to move several steps at a time.
21713
21714It is interesting to compare Calc's selection commands with the
21715Emacs Info system's commands for navigating through hierarchically
21716organized documentation. Calc's @kbd{j n} command is completely
21717analogous to Info's @kbd{n} command. Likewise, @kbd{j p} maps to
21718@kbd{p}, @kbd{j 2} maps to @kbd{2}, and Info's @kbd{u} is like @kbd{j m}.
21719(Note that @kbd{j u} stands for @code{calc-unselect}, not ``up''.)
21720The Info @kbd{m} command is somewhat similar to Calc's @kbd{j s} and
21721@kbd{j l}; in each case, you can jump directly to a sub-component
21722of the hierarchy simply by pointing to it with the cursor.
21723
21724@node Displaying Selections, Operating on Selections, Changing Selections, Selecting Subformulas
21725@subsection Displaying Selections
21726
21727@noindent
21728@kindex j d
21729@pindex calc-show-selections
2c695727
JB
21730@vindex calc-highlight-selections-with-faces
21731@vindex calc-selected-face
21732@vindex calc-nonselected-face
4009494e
GM
21733The @kbd{j d} (@code{calc-show-selections}) command controls how
21734selected sub-formulas are displayed. One of the alternatives is
21735illustrated in the above examples; if we press @kbd{j d} we switch
21736to the other style in which the selected portion itself is obscured
21737by @samp{#} signs:
21738
21739@smallexample
21740@group
21741 3 ... # ___
21742 (a + b) . . . ## # ## + V c
217431* ............... 1* ---------------
21744 . . . . 2 x + 1
21745@end group
21746@end smallexample
2c695727
JB
21747If the customizable variable
21748@code{calc-highlight-selections-with-faces} is non-nil, then the
21749non-selected portion of the formula will be de-emphasized by using a
21750less noticeable face (@code{calc-nonselected-face}) instead of dots
21751and the selected sub-formula will be highlighted by using a more
21752noticeable face (@code{calc-selected-face}) instead of @samp{#}
21753signs. (@pxref{Customizing Calc}.)
4009494e
GM
21754
21755@node Operating on Selections, Rearranging with Selections, Displaying Selections, Selecting Subformulas
21756@subsection Operating on Selections
21757
21758@noindent
21759Once a selection is made, all Calc commands that manipulate items
21760on the stack will operate on the selected portions of the items
21761instead. (Note that several stack elements may have selections
21762at once, though there can be only one selection at a time in any
21763given stack element.)
21764
21765@kindex j e
21766@pindex calc-enable-selections
21767The @kbd{j e} (@code{calc-enable-selections}) command disables the
21768effect that selections have on Calc commands. The current selections
21769still exist, but Calc commands operate on whole stack elements anyway.
21770This mode can be identified by the fact that the @samp{*} markers on
21771the line numbers are gone, even though selections are visible. To
21772reactivate the selections, press @kbd{j e} again.
21773
21774To extract a sub-formula as a new formula, simply select the
21775sub-formula and press @key{RET}. This normally duplicates the top
21776stack element; here it duplicates only the selected portion of that
21777element.
21778
21779To replace a sub-formula with something different, you can enter the
21780new value onto the stack and press @key{TAB}. This normally exchanges
21781the top two stack elements; here it swaps the value you entered into
21782the selected portion of the formula, returning the old selected
21783portion to the top of the stack.
21784
21785@smallexample
21786@group
21787 3 ... ... ___
21788 (a + b) . . . 17 x y . . . 17 x y + V c
217892* ............... 2* ............. 2: -------------
21790 . . . . . . . . 2 x + 1
21791
21792 3 3
217931: 17 x y 1: (a + b) 1: (a + b)
21794@end group
21795@end smallexample
21796
21797In this example we select a sub-formula of our original example,
21798enter a new formula, @key{TAB} it into place, then deselect to see
21799the complete, edited formula.
21800
21801If you want to swap whole formulas around even though they contain
21802selections, just use @kbd{j e} before and after.
21803
21804@kindex j '
21805@pindex calc-enter-selection
21806The @kbd{j '} (@code{calc-enter-selection}) command is another way
21807to replace a selected sub-formula. This command does an algebraic
21808entry just like the regular @kbd{'} key. When you press @key{RET},
21809the formula you type replaces the original selection. You can use
21810the @samp{$} symbol in the formula to refer to the original
21811selection. If there is no selection in the formula under the cursor,
21812the cursor is used to make a temporary selection for the purposes of
21813the command. Thus, to change a term of a formula, all you have to
21814do is move the Emacs cursor to that term and press @kbd{j '}.
21815
21816@kindex j `
21817@pindex calc-edit-selection
21818The @kbd{j `} (@code{calc-edit-selection}) command is a similar
21819analogue of the @kbd{`} (@code{calc-edit}) command. It edits the
21820selected sub-formula in a separate buffer. If there is no
21821selection, it edits the sub-formula indicated by the cursor.
21822
21823To delete a sub-formula, press @key{DEL}. This generally replaces
21824the sub-formula with the constant zero, but in a few suitable contexts
21825it uses the constant one instead. The @key{DEL} key automatically
21826deselects and re-simplifies the entire formula afterwards. Thus:
21827
21828@smallexample
21829@group
21830 ###
21831 17 x y + # # 17 x y 17 # y 17 y
218321* ------------- 1: ------- 1* ------- 1: -------
21833 2 x + 1 2 x + 1 2 x + 1 2 x + 1
21834@end group
21835@end smallexample
21836
21837In this example, we first delete the @samp{sqrt(c)} term; Calc
21838accomplishes this by replacing @samp{sqrt(c)} with zero and
21839resimplifying. We then delete the @kbd{x} in the numerator;
21840since this is part of a product, Calc replaces it with @samp{1}
21841and resimplifies.
21842
21843If you select an element of a vector and press @key{DEL}, that
21844element is deleted from the vector. If you delete one side of
21845an equation or inequality, only the opposite side remains.
21846
21847@kindex j @key{DEL}
21848@pindex calc-del-selection
21849The @kbd{j @key{DEL}} (@code{calc-del-selection}) command is like
21850@key{DEL} but with the auto-selecting behavior of @kbd{j '} and
21851@kbd{j `}. It deletes the selected portion of the formula
21852indicated by the cursor, or, in the absence of a selection, it
21853deletes the sub-formula indicated by the cursor position.
21854
21855@kindex j @key{RET}
21856@pindex calc-grab-selection
21857(There is also an auto-selecting @kbd{j @key{RET}} (@code{calc-copy-selection})
21858command.)
21859
21860Normal arithmetic operations also apply to sub-formulas. Here we
21861select the denominator, press @kbd{5 -} to subtract five from the
21862denominator, press @kbd{n} to negate the denominator, then
21863press @kbd{Q} to take the square root.
21864
21865@smallexample
21866@group
21867 .. . .. . .. . .. .
218681* ....... 1* ....... 1* ....... 1* ..........
21869 2 x + 1 2 x - 4 4 - 2 x _________
21870 V 4 - 2 x
21871@end group
21872@end smallexample
21873
21874Certain types of operations on selections are not allowed. For
21875example, for an arithmetic function like @kbd{-} no more than one of
21876the arguments may be a selected sub-formula. (As the above example
21877shows, the result of the subtraction is spliced back into the argument
21878which had the selection; if there were more than one selection involved,
21879this would not be well-defined.) If you try to subtract two selections,
21880the command will abort with an error message.
21881
21882Operations on sub-formulas sometimes leave the formula as a whole
21883in an ``un-natural'' state. Consider negating the @samp{2 x} term
21884of our sample formula by selecting it and pressing @kbd{n}
21885(@code{calc-change-sign}).
21886
21887@smallexample
21888@group
21889 .. . .. .
218901* .......... 1* ...........
21891 ......... ..........
21892 . . . 2 x . . . -2 x
21893@end group
21894@end smallexample
21895
21896Unselecting the sub-formula reveals that the minus sign, which would
c80e3b4a 21897normally have canceled out with the subtraction automatically, has
4009494e
GM
21898not been able to do so because the subtraction was not part of the
21899selected portion. Pressing @kbd{=} (@code{calc-evaluate}) or doing
21900any other mathematical operation on the whole formula will cause it
21901to be simplified.
21902
21903@smallexample
21904@group
21905 17 y 17 y
219061: ----------- 1: ----------
21907 __________ _________
21908 V 4 - -2 x V 4 + 2 x
21909@end group
21910@end smallexample
21911
21912@node Rearranging with Selections, , Operating on Selections, Selecting Subformulas
21913@subsection Rearranging Formulas using Selections
21914
21915@noindent
21916@kindex j R
21917@pindex calc-commute-right
21918The @kbd{j R} (@code{calc-commute-right}) command moves the selected
21919sub-formula to the right in its surrounding formula. Generally the
21920selection is one term of a sum or product; the sum or product is
21921rearranged according to the commutative laws of algebra.
21922
21923As with @kbd{j '} and @kbd{j @key{DEL}}, the term under the cursor is used
21924if there is no selection in the current formula. All commands described
21925in this section share this property. In this example, we place the
21926cursor on the @samp{a} and type @kbd{j R}, then repeat.
21927
21928@smallexample
219291: a + b - c 1: b + a - c 1: b - c + a
21930@end smallexample
21931
21932@noindent
21933Note that in the final step above, the @samp{a} is switched with
21934the @samp{c} but the signs are adjusted accordingly. When moving
21935terms of sums and products, @kbd{j R} will never change the
21936mathematical meaning of the formula.
21937
21938The selected term may also be an element of a vector or an argument
21939of a function. The term is exchanged with the one to its right.
21940In this case, the ``meaning'' of the vector or function may of
21941course be drastically changed.
21942
21943@smallexample
219441: [a, b, c] 1: [b, a, c] 1: [b, c, a]
21945
219461: f(a, b, c) 1: f(b, a, c) 1: f(b, c, a)
21947@end smallexample
21948
21949@kindex j L
21950@pindex calc-commute-left
21951The @kbd{j L} (@code{calc-commute-left}) command is like @kbd{j R}
21952except that it swaps the selected term with the one to its left.
21953
21954With numeric prefix arguments, these commands move the selected
21955term several steps at a time. It is an error to try to move a
21956term left or right past the end of its enclosing formula.
21957With numeric prefix arguments of zero, these commands move the
21958selected term as far as possible in the given direction.
21959
21960@kindex j D
21961@pindex calc-sel-distribute
21962The @kbd{j D} (@code{calc-sel-distribute}) command mixes the selected
21963sum or product into the surrounding formula using the distributive
21964law. For example, in @samp{a * (b - c)} with the @samp{b - c}
21965selected, the result is @samp{a b - a c}. This also distributes
21966products or quotients into surrounding powers, and can also do
21967transformations like @samp{exp(a + b)} to @samp{exp(a) exp(b)},
21968where @samp{a + b} is the selected term, and @samp{ln(a ^ b)}
21969to @samp{ln(a) b}, where @samp{a ^ b} is the selected term.
21970
21971For multiple-term sums or products, @kbd{j D} takes off one term
21972at a time: @samp{a * (b + c - d)} goes to @samp{a * (c - d) + a b}
21973with the @samp{c - d} selected so that you can type @kbd{j D}
21974repeatedly to expand completely. The @kbd{j D} command allows a
21975numeric prefix argument which specifies the maximum number of
21976times to expand at once; the default is one time only.
21977
21978@vindex DistribRules
21979The @kbd{j D} command is implemented using rewrite rules.
21980@xref{Selections with Rewrite Rules}. The rules are stored in
21981the Calc variable @code{DistribRules}. A convenient way to view
21982these rules is to use @kbd{s e} (@code{calc-edit-variable}) which
21983displays and edits the stored value of a variable. Press @kbd{C-c C-c}
21984to return from editing mode; be careful not to make any actual changes
21985or else you will affect the behavior of future @kbd{j D} commands!
21986
21987To extend @kbd{j D} to handle new cases, just edit @code{DistribRules}
21988as described above. You can then use the @kbd{s p} command to save
21989this variable's value permanently for future Calc sessions.
21990@xref{Operations on Variables}.
21991
21992@kindex j M
21993@pindex calc-sel-merge
21994@vindex MergeRules
21995The @kbd{j M} (@code{calc-sel-merge}) command is the complement
21996of @kbd{j D}; given @samp{a b - a c} with either @samp{a b} or
21997@samp{a c} selected, the result is @samp{a * (b - c)}. Once
21998again, @kbd{j M} can also merge calls to functions like @code{exp}
21999and @code{ln}; examine the variable @code{MergeRules} to see all
22000the relevant rules.
22001
22002@kindex j C
22003@pindex calc-sel-commute
22004@vindex CommuteRules
22005The @kbd{j C} (@code{calc-sel-commute}) command swaps the arguments
22006of the selected sum, product, or equation. It always behaves as
22007if @kbd{j b} mode were in effect, i.e., the sum @samp{a + b + c} is
22008treated as the nested sums @samp{(a + b) + c} by this command.
22009If you put the cursor on the first @samp{+}, the result is
22010@samp{(b + a) + c}; if you put the cursor on the second @samp{+}, the
22011result is @samp{c + (a + b)} (which the default simplifications
22012will rearrange to @samp{(c + a) + b}). The relevant rules are stored
22013in the variable @code{CommuteRules}.
22014
22015You may need to turn default simplifications off (with the @kbd{m O}
22016command) in order to get the full benefit of @kbd{j C}. For example,
22017commuting @samp{a - b} produces @samp{-b + a}, but the default
22018simplifications will ``simplify'' this right back to @samp{a - b} if
22019you don't turn them off. The same is true of some of the other
22020manipulations described in this section.
22021
22022@kindex j N
22023@pindex calc-sel-negate
22024@vindex NegateRules
22025The @kbd{j N} (@code{calc-sel-negate}) command replaces the selected
22026term with the negative of that term, then adjusts the surrounding
22027formula in order to preserve the meaning. For example, given
22028@samp{exp(a - b)} where @samp{a - b} is selected, the result is
22029@samp{1 / exp(b - a)}. By contrast, selecting a term and using the
22030regular @kbd{n} (@code{calc-change-sign}) command negates the
22031term without adjusting the surroundings, thus changing the meaning
22032of the formula as a whole. The rules variable is @code{NegateRules}.
22033
22034@kindex j &
22035@pindex calc-sel-invert
22036@vindex InvertRules
22037The @kbd{j &} (@code{calc-sel-invert}) command is similar to @kbd{j N}
22038except it takes the reciprocal of the selected term. For example,
22039given @samp{a - ln(b)} with @samp{b} selected, the result is
22040@samp{a + ln(1/b)}. The rules variable is @code{InvertRules}.
22041
22042@kindex j E
22043@pindex calc-sel-jump-equals
22044@vindex JumpRules
22045The @kbd{j E} (@code{calc-sel-jump-equals}) command moves the
22046selected term from one side of an equation to the other. Given
22047@samp{a + b = c + d} with @samp{c} selected, the result is
22048@samp{a + b - c = d}. This command also works if the selected
22049term is part of a @samp{*}, @samp{/}, or @samp{^} formula. The
22050relevant rules variable is @code{JumpRules}.
22051
22052@kindex j I
22053@kindex H j I
22054@pindex calc-sel-isolate
22055The @kbd{j I} (@code{calc-sel-isolate}) command isolates the
22056selected term on its side of an equation. It uses the @kbd{a S}
22057(@code{calc-solve-for}) command to solve the equation, and the
22058Hyperbolic flag affects it in the same way. @xref{Solving Equations}.
22059When it applies, @kbd{j I} is often easier to use than @kbd{j E}.
22060It understands more rules of algebra, and works for inequalities
22061as well as equations.
22062
22063@kindex j *
22064@kindex j /
22065@pindex calc-sel-mult-both-sides
22066@pindex calc-sel-div-both-sides
22067The @kbd{j *} (@code{calc-sel-mult-both-sides}) command prompts for a
22068formula using algebraic entry, then multiplies both sides of the
d2bd74ff
JB
22069selected quotient or equation by that formula. It performs the
22070default algebraic simplifications before re-forming the
4009494e 22071quotient or equation. You can suppress this simplification by
5fafc247 22072providing a prefix argument: @kbd{C-u j *}. There is also a @kbd{j /}
4009494e
GM
22073(@code{calc-sel-div-both-sides}) which is similar to @kbd{j *} but
22074dividing instead of multiplying by the factor you enter.
22075
5fafc247
JB
22076If the selection is a quotient with numerator 1, then Calc's default
22077simplifications would normally cancel the new factors. To prevent
22078this, when the @kbd{j *} command is used on a selection whose numerator is
220791 or -1, the denominator is expanded at the top level using the
22080distributive law (as if using the @kbd{C-u 1 a x} command). Suppose the
22081formula on the stack is @samp{1 / (a + 1)} and you wish to multiplying the
22082top and bottom by @samp{a - 1}. Calc's default simplifications would
22083normally change the result @samp{(a - 1) /(a + 1) (a - 1)} back
22084to the original form by cancellation; when @kbd{j *} is used, Calc
22085expands the denominator to @samp{a (a - 1) + a - 1} to prevent this.
22086
22087If you wish the @kbd{j *} command to completely expand the denominator
22088of a quotient you can call it with a zero prefix: @kbd{C-u 0 j *}. For
22089example, if the formula on the stack is @samp{1 / (sqrt(a) + 1)}, you may
22090wish to eliminate the square root in the denominator by multiplying
22091the top and bottom by @samp{sqrt(a) - 1}. If you did this simply by using
40ba43b4 22092a simple @kbd{j *} command, you would get
5fafc247
JB
22093@samp{(sqrt(a)-1)/ (sqrt(a) (sqrt(a) - 1) + sqrt(a) - 1)}. Instead,
22094you would probably want to use @kbd{C-u 0 j *}, which would expand the
22095bottom and give you the desired result @samp{(sqrt(a)-1)/(a-1)}. More
22096generally, if @kbd{j *} is called with an argument of a positive
22097integer @var{n}, then the denominator of the expression will be
22098expanded @var{n} times (as if with the @kbd{C-u @var{n} a x} command).
4009494e
GM
22099
22100If the selection is an inequality, @kbd{j *} and @kbd{j /} will
22101accept any factor, but will warn unless they can prove the factor
22102is either positive or negative. (In the latter case the direction
22103of the inequality will be switched appropriately.) @xref{Declarations},
22104for ways to inform Calc that a given variable is positive or
22105negative. If Calc can't tell for sure what the sign of the factor
22106will be, it will assume it is positive and display a warning
22107message.
22108
22109For selections that are not quotients, equations, or inequalities,
22110these commands pull out a multiplicative factor: They divide (or
22111multiply) by the entered formula, simplify, then multiply (or divide)
22112back by the formula.
22113
22114@kindex j +
22115@kindex j -
22116@pindex calc-sel-add-both-sides
22117@pindex calc-sel-sub-both-sides
22118The @kbd{j +} (@code{calc-sel-add-both-sides}) and @kbd{j -}
22119(@code{calc-sel-sub-both-sides}) commands analogously add to or
22120subtract from both sides of an equation or inequality. For other
22121types of selections, they extract an additive factor. A numeric
22122prefix argument suppresses simplification of the intermediate
22123results.
22124
22125@kindex j U
22126@pindex calc-sel-unpack
22127The @kbd{j U} (@code{calc-sel-unpack}) command replaces the
22128selected function call with its argument. For example, given
22129@samp{a + sin(x^2)} with @samp{sin(x^2)} selected, the result
22130is @samp{a + x^2}. (The @samp{x^2} will remain selected; if you
22131wanted to change the @code{sin} to @code{cos}, just press @kbd{C}
22132now to take the cosine of the selected part.)
22133
22134@kindex j v
22135@pindex calc-sel-evaluate
22136The @kbd{j v} (@code{calc-sel-evaluate}) command performs the
1dcac243 22137basic simplifications on the selected sub-formula.
d2bd74ff
JB
22138These simplifications would normally be done automatically
22139on all results, but may have been partially inhibited by
4009494e
GM
22140previous selection-related operations, or turned off altogether
22141by the @kbd{m O} command. This command is just an auto-selecting
22142version of the @w{@kbd{a v}} command (@pxref{Algebraic Manipulation}).
22143
22144With a numeric prefix argument of 2, @kbd{C-u 2 j v} applies
d2bd74ff 22145the default algebraic simplifications to the selected
4009494e
GM
22146sub-formula. With a prefix argument of 3 or more, e.g., @kbd{C-u j v}
22147applies the @kbd{a e} (@code{calc-simplify-extended}) command.
22148@xref{Simplifying Formulas}. With a negative prefix argument
22149it simplifies at the top level only, just as with @kbd{a v}.
22150Here the ``top'' level refers to the top level of the selected
22151sub-formula.
22152
22153@kindex j "
22154@pindex calc-sel-expand-formula
22155The @kbd{j "} (@code{calc-sel-expand-formula}) command is to @kbd{a "}
22156(@pxref{Algebraic Manipulation}) what @kbd{j v} is to @kbd{a v}.
22157
22158You can use the @kbd{j r} (@code{calc-rewrite-selection}) command
22159to define other algebraic operations on sub-formulas. @xref{Rewrite Rules}.
22160
22161@node Algebraic Manipulation, Simplifying Formulas, Selecting Subformulas, Algebra
22162@section Algebraic Manipulation
22163
22164@noindent
22165The commands in this section perform general-purpose algebraic
22166manipulations. They work on the whole formula at the top of the
22167stack (unless, of course, you have made a selection in that
22168formula).
22169
22170Many algebra commands prompt for a variable name or formula. If you
22171answer the prompt with a blank line, the variable or formula is taken
22172from top-of-stack, and the normal argument for the command is taken
22173from the second-to-top stack level.
22174
22175@kindex a v
22176@pindex calc-alg-evaluate
22177The @kbd{a v} (@code{calc-alg-evaluate}) command performs the normal
22178default simplifications on a formula; for example, @samp{a - -b} is
22179changed to @samp{a + b}. These simplifications are normally done
22180automatically on all Calc results, so this command is useful only if
22181you have turned default simplifications off with an @kbd{m O}
22182command. @xref{Simplification Modes}.
22183
22184It is often more convenient to type @kbd{=}, which is like @kbd{a v}
22185but which also substitutes stored values for variables in the formula.
22186Use @kbd{a v} if you want the variables to ignore their stored values.
22187
22188If you give a numeric prefix argument of 2 to @kbd{a v}, it simplifies
8e7046c3
JB
22189using Calc's algebraic simplifications; @pxref{Simplifying Formulas}.
22190If you give a numeric prefix of 3 or more, it uses Extended
22191Simplification mode (@kbd{a e}).
4009494e
GM
22192
22193If you give a negative prefix argument @mathit{-1}, @mathit{-2}, or @mathit{-3},
22194it simplifies in the corresponding mode but only works on the top-level
22195function call of the formula. For example, @samp{(2 + 3) * (2 + 3)} will
22196simplify to @samp{(2 + 3)^2}, without simplifying the sub-formulas
22197@samp{2 + 3}. As another example, typing @kbd{V R +} to sum the vector
22198@samp{[1, 2, 3, 4]} produces the formula @samp{reduce(add, [1, 2, 3, 4])}
22199in No-Simplify mode. Using @kbd{a v} will evaluate this all the way to
2220010; using @kbd{C-u - a v} will evaluate it only to @samp{1 + 2 + 3 + 4}.
22201(@xref{Reducing and Mapping}.)
22202
22203@tindex evalv
22204@tindex evalvn
22205The @kbd{=} command corresponds to the @code{evalv} function, and
22206the related @kbd{N} command, which is like @kbd{=} but temporarily
22207disables Symbolic mode (@kbd{m s}) during the evaluation, corresponds
22208to the @code{evalvn} function. (These commands interpret their prefix
22209arguments differently than @kbd{a v}; @kbd{=} treats the prefix as
22210the number of stack elements to evaluate at once, and @kbd{N} treats
22211it as a temporary different working precision.)
22212
22213The @code{evalvn} function can take an alternate working precision
22214as an optional second argument. This argument can be either an
22215integer, to set the precision absolutely, or a vector containing
22216a single integer, to adjust the precision relative to the current
22217precision. Note that @code{evalvn} with a larger than current
22218precision will do the calculation at this higher precision, but the
22219result will as usual be rounded back down to the current precision
22220afterward. For example, @samp{evalvn(pi - 3.1415)} at a precision
22221of 12 will return @samp{9.265359e-5}; @samp{evalvn(pi - 3.1415, 30)}
22222will return @samp{9.26535897932e-5} (computing a 25-digit result which
22223is then rounded down to 12); and @samp{evalvn(pi - 3.1415, [-2])}
22224will return @samp{9.2654e-5}.
22225
22226@kindex a "
22227@pindex calc-expand-formula
22228The @kbd{a "} (@code{calc-expand-formula}) command expands functions
22229into their defining formulas wherever possible. For example,
22230@samp{deg(x^2)} is changed to @samp{180 x^2 / pi}. Most functions,
22231like @code{sin} and @code{gcd}, are not defined by simple formulas
22232and so are unaffected by this command. One important class of
22233functions which @emph{can} be expanded is the user-defined functions
22234created by the @kbd{Z F} command. @xref{Algebraic Definitions}.
22235Other functions which @kbd{a "} can expand include the probability
22236distribution functions, most of the financial functions, and the
22237hyperbolic and inverse hyperbolic functions. A numeric prefix argument
22238affects @kbd{a "} in the same way as it does @kbd{a v}: A positive
22239argument expands all functions in the formula and then simplifies in
22240various ways; a negative argument expands and simplifies only the
22241top-level function call.
22242
22243@kindex a M
22244@pindex calc-map-equation
22245@tindex mapeq
22246The @kbd{a M} (@code{calc-map-equation}) [@code{mapeq}] command applies
22247a given function or operator to one or more equations. It is analogous
22248to @kbd{V M}, which operates on vectors instead of equations.
22249@pxref{Reducing and Mapping}. For example, @kbd{a M S} changes
22250@samp{x = y+1} to @samp{sin(x) = sin(y+1)}, and @kbd{a M +} with
22251@samp{x = y+1} and @expr{6} on the stack produces @samp{x+6 = y+7}.
22252With two equations on the stack, @kbd{a M +} would add the lefthand
22253sides together and the righthand sides together to get the two
22254respective sides of a new equation.
22255
22256Mapping also works on inequalities. Mapping two similar inequalities
22257produces another inequality of the same type. Mapping an inequality
22258with an equation produces an inequality of the same type. Mapping a
22259@samp{<=} with a @samp{<} or @samp{!=} (not-equal) produces a @samp{<}.
22260If inequalities with opposite direction (e.g., @samp{<} and @samp{>})
22261are mapped, the direction of the second inequality is reversed to
22262match the first: Using @kbd{a M +} on @samp{a < b} and @samp{a > 2}
22263reverses the latter to get @samp{2 < a}, which then allows the
8e7046c3
JB
22264combination @samp{a + 2 < b + a}, which the algebraic simplifications
22265can reduce to @samp{2 < b}.
4009494e
GM
22266
22267Using @kbd{a M *}, @kbd{a M /}, @kbd{a M n}, or @kbd{a M &} to negate
22268or invert an inequality will reverse the direction of the inequality.
22269Other adjustments to inequalities are @emph{not} done automatically;
22270@kbd{a M S} will change @w{@samp{x < y}} to @samp{sin(x) < sin(y)} even
22271though this is not true for all values of the variables.
22272
22273@kindex H a M
22274@tindex mapeqp
22275With the Hyperbolic flag, @kbd{H a M} [@code{mapeqp}] does a plain
22276mapping operation without reversing the direction of any inequalities.
22277Thus, @kbd{H a M &} would change @kbd{x > 2} to @kbd{1/x > 0.5}.
22278(This change is mathematically incorrect, but perhaps you were
22279fixing an inequality which was already incorrect.)
22280
22281@kindex I a M
22282@tindex mapeqr
22283With the Inverse flag, @kbd{I a M} [@code{mapeqr}] always reverses
22284the direction of the inequality. You might use @kbd{I a M C} to
22285change @samp{x < y} to @samp{cos(x) > cos(y)} if you know you are
22286working with small positive angles.
22287
22288@kindex a b
22289@pindex calc-substitute
22290@tindex subst
22291The @kbd{a b} (@code{calc-substitute}) [@code{subst}] command substitutes
22292all occurrences
22293of some variable or sub-expression of an expression with a new
22294sub-expression. For example, substituting @samp{sin(x)} with @samp{cos(y)}
22295in @samp{2 sin(x)^2 + x sin(x) + sin(2 x)} produces
22296@samp{2 cos(y)^2 + x cos(y) + @w{sin(2 x)}}.
22297Note that this is a purely structural substitution; the lone @samp{x} and
22298the @samp{sin(2 x)} stayed the same because they did not look like
22299@samp{sin(x)}. @xref{Rewrite Rules}, for a more general method for
22300doing substitutions.
22301
22302The @kbd{a b} command normally prompts for two formulas, the old
22303one and the new one. If you enter a blank line for the first
22304prompt, all three arguments are taken from the stack (new, then old,
22305then target expression). If you type an old formula but then enter a
22306blank line for the new one, the new formula is taken from top-of-stack
22307and the target from second-to-top. If you answer both prompts, the
22308target is taken from top-of-stack as usual.
22309
22310Note that @kbd{a b} has no understanding of commutativity or
22311associativity. The pattern @samp{x+y} will not match the formula
22312@samp{y+x}. Also, @samp{y+z} will not match inside the formula @samp{x+y+z}
22313because the @samp{+} operator is left-associative, so the ``deep
22314structure'' of that formula is @samp{(x+y) + z}. Use @kbd{d U}
22315(@code{calc-unformatted-language}) mode to see the true structure of
22316a formula. The rewrite rule mechanism, discussed later, does not have
22317these limitations.
22318
22319As an algebraic function, @code{subst} takes three arguments:
22320Target expression, old, new. Note that @code{subst} is always
22321evaluated immediately, even if its arguments are variables, so if
22322you wish to put a call to @code{subst} onto the stack you must
22323turn the default simplifications off first (with @kbd{m O}).
22324
22325@node Simplifying Formulas, Polynomials, Algebraic Manipulation, Algebra
22326@section Simplifying Formulas
22327
22328@noindent
22329@kindex a s
0ff2d6c2
JB
22330@kindex I a s
22331@kindex H a s
4009494e
GM
22332@pindex calc-simplify
22333@tindex simplify
d2bd74ff
JB
22334
22335The sections below describe all the various kinds of
4009494e
GM
22336simplifications Calc provides in full detail. None of Calc's
22337simplification commands are designed to pull rabbits out of hats;
22338they simply apply certain specific rules to put formulas into
22339less redundant or more pleasing forms. Serious algebra in Calc
22340must be done manually, usually with a combination of selections
22341and rewrite rules. @xref{Rearranging with Selections}.
22342@xref{Rewrite Rules}.
22343
22344@xref{Simplification Modes}, for commands to control what level of
8e7046c3
JB
22345simplification occurs automatically. Normally the algebraic
22346simplifications described below occur. If you have turned on a
22347simplification mode which does not do these algebraic simplifications,
22348you can still apply them to a formula with the @kbd{a s}
22349(@code{calc-simplify}) [@code{simplify}] command.
4009494e 22350
0ff2d6c2
JB
22351There are some simplifications that, while sometimes useful, are never
22352done automatically. For example, the @kbd{I} prefix can be given to
22353@kbd{a s}; the @kbd{I a s} command will change any trigonometric
22354function to the appropriate combination of @samp{sin}s and @samp{cos}s
22355before simplifying. This can be useful in simplifying even mildly
8e7046c3
JB
22356complicated trigonometric expressions. For example, while the algebraic
22357simplifications can reduce @samp{sin(x) csc(x)} to @samp{1}, they will not
22358simplify @samp{sin(x)^2 csc(x)}. The command @kbd{I a s} can be used to
0ff2d6c2 22359simplify this latter expression; it will transform @samp{sin(x)^2
744256cf
JB
22360csc(x)} into @samp{sin(x)}. However, @kbd{I a s} will also perform
22361some ``simplifications'' which may not be desired; for example, it
22362will transform @samp{tan(x)^2} into @samp{sin(x)^2 / cos(x)^2}. The
22363Hyperbolic prefix @kbd{H} can be used similarly; the @kbd{H a s} will
0ff2d6c2
JB
22364replace any hyperbolic functions in the formula with the appropriate
22365combinations of @samp{sinh}s and @samp{cosh}s before simplifying.
22366
22367
4009494e 22368@menu
8e7046c3 22369* Basic Simplifications::
4009494e
GM
22370* Algebraic Simplifications::
22371* Unsafe Simplifications::
22372* Simplification of Units::
22373@end menu
22374
8e7046c3
JB
22375@node Basic Simplifications, Algebraic Simplifications, Simplifying Formulas, Simplifying Formulas
22376@subsection Basic Simplifications
4009494e
GM
22377
22378@noindent
8e7046c3
JB
22379@cindex Basic simplifications
22380This section describes basic simplifications which Calc performs in many
22381situations. For example, both binary simplifications and algebraic
22382simplifications begin by performing these basic simplifications. You
22383can type @kbd{m I} to restrict the simplifications done on the stack to
22384these simplifications.
4009494e 22385
d2bd74ff 22386The most basic simplification is the evaluation of functions.
4009494e
GM
22387For example, @expr{2 + 3} is evaluated to @expr{5}, and @expr{@tfn{sqrt}(9)}
22388is evaluated to @expr{3}. Evaluation does not occur if the arguments
22389to a function are somehow of the wrong type @expr{@tfn{tan}([2,3,4])}),
40ba43b4 22390range (@expr{@tfn{tan}(90)}), or number (@expr{@tfn{tan}(3,5)}),
4009494e
GM
22391or if the function name is not recognized (@expr{@tfn{f}(5)}), or if
22392Symbolic mode (@pxref{Symbolic Mode}) prevents evaluation
22393(@expr{@tfn{sqrt}(2)}).
22394
22395Calc simplifies (evaluates) the arguments to a function before it
22396simplifies the function itself. Thus @expr{@tfn{sqrt}(5+4)} is
22397simplified to @expr{@tfn{sqrt}(9)} before the @code{sqrt} function
22398itself is applied. There are very few exceptions to this rule:
22399@code{quote}, @code{lambda}, and @code{condition} (the @code{::}
22400operator) do not evaluate their arguments, @code{if} (the @code{? :}
22401operator) does not evaluate all of its arguments, and @code{evalto}
22402does not evaluate its lefthand argument.
22403
8e7046c3 22404Most commands apply at least these basic simplifications to all
d2bd74ff
JB
22405arguments they take from the stack, perform a particular operation,
22406then simplify the result before pushing it back on the stack. In the
22407common special case of regular arithmetic commands like @kbd{+} and
22408@kbd{Q} [@code{sqrt}], the arguments are simply popped from the stack
22409and collected into a suitable function call, which is then simplified
22410(the arguments being simplified first as part of the process, as
22411described above).
22412
8e7046c3 22413Even the basic set of simplifications are too numerous to describe
d2bd74ff 22414completely here, but this section will describe the ones that apply to the
4009494e
GM
22415major arithmetic operators. This list will be rather technical in
22416nature, and will probably be interesting to you only if you are
22417a serious user of Calc's algebra facilities.
22418
22419@tex
22420\bigskip
22421@end tex
22422
22423As well as the simplifications described here, if you have stored
22424any rewrite rules in the variable @code{EvalRules} then these rules
1dcac243 22425will also be applied before any of the basic simplifications.
4009494e
GM
22426@xref{Automatic Rewrites}, for details.
22427
22428@tex
22429\bigskip
22430@end tex
22431
1dcac243 22432And now, on with the basic simplifications:
4009494e
GM
22433
22434Arithmetic operators like @kbd{+} and @kbd{*} always take two
22435arguments in Calc's internal form. Sums and products of three or
22436more terms are arranged by the associative law of algebra into
22437a left-associative form for sums, @expr{((a + b) + c) + d}, and
40ba43b4 22438(by default) a right-associative form for products,
45b778a6
JB
22439@expr{a * (b * (c * d))}. Formulas like @expr{(a + b) + (c + d)} are
22440rearranged to left-associative form, though this rarely matters since
22441Calc's algebra commands are designed to hide the inner structure of sums
22442and products as much as possible. Sums and products in their proper
22443associative form will be written without parentheses in the examples
22444below.
4009494e
GM
22445
22446Sums and products are @emph{not} rearranged according to the
22447commutative law (@expr{a + b} to @expr{b + a}) except in a few
22448special cases described below. Some algebra programs always
22449rearrange terms into a canonical order, which enables them to
22450see that @expr{a b + b a} can be simplified to @expr{2 a b}.
8e7046c3
JB
22451If you are using Basic Simplification mode, Calc assumes you have put
22452the terms into the order you want and generally leaves that order alone,
22453with the consequence that formulas like the above will only be
22454simplified if you explicitly give the @kbd{a s} command.
22455@xref{Algebraic Simplifications}.
4009494e
GM
22456
22457Differences @expr{a - b} are treated like sums @expr{a + (-b)}
22458for purposes of simplification; one of the default simplifications
22459is to rewrite @expr{a + (-b)} or @expr{(-b) + a}, where @expr{-b}
22460represents a ``negative-looking'' term, into @expr{a - b} form.
22461``Negative-looking'' means negative numbers, negated formulas like
22462@expr{-x}, and products or quotients in which either term is
22463negative-looking.
22464
22465Other simplifications involving negation are @expr{-(-x)} to @expr{x};
22466@expr{-(a b)} or @expr{-(a/b)} where either @expr{a} or @expr{b} is
22467negative-looking, simplified by negating that term, or else where
22468@expr{a} or @expr{b} is any number, by negating that number;
22469@expr{-(a + b)} to @expr{-a - b}, and @expr{-(b - a)} to @expr{a - b}.
22470(This, and rewriting @expr{(-b) + a} to @expr{a - b}, are the only
22471cases where the order of terms in a sum is changed by the default
22472simplifications.)
22473
22474The distributive law is used to simplify sums in some cases:
22475@expr{a x + b x} to @expr{(a + b) x}, where @expr{a} represents
22476a number or an implicit 1 or @mathit{-1} (as in @expr{x} or @expr{-x})
22477and similarly for @expr{b}. Use the @kbd{a c}, @w{@kbd{a f}}, or
22478@kbd{j M} commands to merge sums with non-numeric coefficients
22479using the distributive law.
22480
22481The distributive law is only used for sums of two terms, or
22482for adjacent terms in a larger sum. Thus @expr{a + b + b + c}
22483is simplified to @expr{a + 2 b + c}, but @expr{a + b + c + b}
22484is not simplified. The reason is that comparing all terms of a
22485sum with one another would require time proportional to the
8e7046c3
JB
22486square of the number of terms; Calc omits potentially slow
22487operations like this in basic simplification mode.
4009494e
GM
22488
22489Finally, @expr{a + 0} and @expr{0 + a} are simplified to @expr{a}.
22490A consequence of the above rules is that @expr{0 - a} is simplified
22491to @expr{-a}.
22492
22493@tex
22494\bigskip
22495@end tex
22496
22497The products @expr{1 a} and @expr{a 1} are simplified to @expr{a};
22498@expr{(-1) a} and @expr{a (-1)} are simplified to @expr{-a};
22499@expr{0 a} and @expr{a 0} are simplified to @expr{0}, except that
22500in Matrix mode where @expr{a} is not provably scalar the result
22501is the generic zero matrix @samp{idn(0)}, and that if @expr{a} is
22502infinite the result is @samp{nan}.
22503
22504Also, @expr{(-a) b} and @expr{a (-b)} are simplified to @expr{-(a b)},
22505where this occurs for negated formulas but not for regular negative
22506numbers.
22507
22508Products are commuted only to move numbers to the front:
22509@expr{a b 2} is commuted to @expr{2 a b}.
22510
22511The product @expr{a (b + c)} is distributed over the sum only if
22512@expr{a} and at least one of @expr{b} and @expr{c} are numbers:
22513@expr{2 (x + 3)} goes to @expr{2 x + 6}. The formula
22514@expr{(-a) (b - c)}, where @expr{-a} is a negative number, is
22515rewritten to @expr{a (c - b)}.
22516
22517The distributive law of products and powers is used for adjacent
40ba43b4 22518terms of the product: @expr{x^a x^b} goes to
4009494e
GM
22519@texline @math{x^{a+b}}
22520@infoline @expr{x^(a+b)}
22521where @expr{a} is a number, or an implicit 1 (as in @expr{x}),
22522or the implicit one-half of @expr{@tfn{sqrt}(x)}, and similarly for
22523@expr{b}. The result is written using @samp{sqrt} or @samp{1/sqrt}
22524if the sum of the powers is @expr{1/2} or @expr{-1/2}, respectively.
22525If the sum of the powers is zero, the product is simplified to
22526@expr{1} or to @samp{idn(1)} if Matrix mode is enabled.
22527
22528The product of a negative power times anything but another negative
40ba43b4 22529power is changed to use division:
4009494e 22530@texline @math{x^{-2} y}
40ba43b4 22531@infoline @expr{x^(-2) y}
4009494e
GM
22532goes to @expr{y / x^2} unless Matrix mode is
22533in effect and neither @expr{x} nor @expr{y} are scalar (in which
22534case it is considered unsafe to rearrange the order of the terms).
22535
22536Finally, @expr{a (b/c)} is rewritten to @expr{(a b)/c}, and also
22537@expr{(a/b) c} is changed to @expr{(a c)/b} unless in Matrix mode.
22538
22539@tex
22540\bigskip
22541@end tex
22542
22543Simplifications for quotients are analogous to those for products.
22544The quotient @expr{0 / x} is simplified to @expr{0}, with the same
22545exceptions that were noted for @expr{0 x}. Likewise, @expr{x / 1}
22546and @expr{x / (-1)} are simplified to @expr{x} and @expr{-x},
22547respectively.
22548
22549The quotient @expr{x / 0} is left unsimplified or changed to an
22550infinite quantity, as directed by the current infinite mode.
22551@xref{Infinite Mode}.
22552
40ba43b4 22553The expression
4009494e 22554@texline @math{a / b^{-c}}
40ba43b4 22555@infoline @expr{a / b^(-c)}
4009494e 22556is changed to @expr{a b^c}, where @expr{-c} is any negative-looking
40ba43b4 22557power. Also, @expr{1 / b^c} is changed to
4009494e 22558@texline @math{b^{-c}}
40ba43b4 22559@infoline @expr{b^(-c)}
4009494e
GM
22560for any power @expr{c}.
22561
22562Also, @expr{(-a) / b} and @expr{a / (-b)} go to @expr{-(a/b)};
22563@expr{(a/b) / c} goes to @expr{a / (b c)}; and @expr{a / (b/c)}
22564goes to @expr{(a c) / b} unless Matrix mode prevents this
22565rearrangement. Similarly, @expr{a / (b:c)} is simplified to
22566@expr{(c:b) a} for any fraction @expr{b:c}.
22567
22568The distributive law is applied to @expr{(a + b) / c} only if
22569@expr{c} and at least one of @expr{a} and @expr{b} are numbers.
22570Quotients of powers and square roots are distributed just as
22571described for multiplication.
22572
22573Quotients of products cancel only in the leading terms of the
22574numerator and denominator. In other words, @expr{a x b / a y b}
c80e3b4a 22575is canceled to @expr{x b / y b} but not to @expr{x / y}. Once
4009494e
GM
22576again this is because full cancellation can be slow; use @kbd{a s}
22577to cancel all terms of the quotient.
22578
22579Quotients of negative-looking values are simplified according
22580to @expr{(-a) / (-b)} to @expr{a / b}, @expr{(-a) / (b - c)}
22581to @expr{a / (c - b)}, and @expr{(a - b) / (-c)} to @expr{(b - a) / c}.
22582
22583@tex
22584\bigskip
22585@end tex
22586
22587The formula @expr{x^0} is simplified to @expr{1}, or to @samp{idn(1)}
22588in Matrix mode. The formula @expr{0^x} is simplified to @expr{0}
22589unless @expr{x} is a negative number, complex number or zero.
22590If @expr{x} is negative, complex or @expr{0.0}, @expr{0^x} is an
22591infinity or an unsimplified formula according to the current infinite
22592mode. The expression @expr{0^0} is simplified to @expr{1}.
22593
22594Powers of products or quotients @expr{(a b)^c}, @expr{(a/b)^c}
22595are distributed to @expr{a^c b^c}, @expr{a^c / b^c} only if @expr{c}
22596is an integer, or if either @expr{a} or @expr{b} are nonnegative
22597real numbers. Powers of powers @expr{(a^b)^c} are simplified to
22598@texline @math{a^{b c}}
40ba43b4 22599@infoline @expr{a^(b c)}
4009494e
GM
22600only when @expr{c} is an integer and @expr{b c} also
22601evaluates to an integer. Without these restrictions these simplifications
22602would not be safe because of problems with principal values.
40ba43b4 22603(In other words,
4009494e 22604@texline @math{((-3)^{1/2})^2}
40ba43b4 22605@infoline @expr{((-3)^1:2)^2}
4009494e
GM
22606is safe to simplify, but
22607@texline @math{((-3)^2)^{1/2}}
40ba43b4 22608@infoline @expr{((-3)^2)^1:2}
4009494e
GM
22609is not.) @xref{Declarations}, for ways to inform Calc that your
22610variables satisfy these requirements.
22611
22612As a special case of this rule, @expr{@tfn{sqrt}(x)^n} is simplified to
22613@texline @math{x^{n/2}}
40ba43b4 22614@infoline @expr{x^(n/2)}
4009494e
GM
22615only for even integers @expr{n}.
22616
22617If @expr{a} is known to be real, @expr{b} is an even integer, and
22618@expr{c} is a half- or quarter-integer, then @expr{(a^b)^c} is
22619simplified to @expr{@tfn{abs}(a^(b c))}.
22620
22621Also, @expr{(-a)^b} is simplified to @expr{a^b} if @expr{b} is an
22622even integer, or to @expr{-(a^b)} if @expr{b} is an odd integer,
22623for any negative-looking expression @expr{-a}.
22624
22625Square roots @expr{@tfn{sqrt}(x)} generally act like one-half powers
22626@texline @math{x^{1:2}}
40ba43b4 22627@infoline @expr{x^1:2}
4009494e
GM
22628for the purposes of the above-listed simplifications.
22629
40ba43b4 22630Also, note that
4009494e 22631@texline @math{1 / x^{1:2}}
40ba43b4
PE
22632@infoline @expr{1 / x^1:2}
22633is changed to
4009494e
GM
22634@texline @math{x^{-1:2}},
22635@infoline @expr{x^(-1:2)},
22636but @expr{1 / @tfn{sqrt}(x)} is left alone.
22637
22638@tex
22639\bigskip
22640@end tex
22641
22642Generic identity matrices (@pxref{Matrix Mode}) are simplified by the
22643following rules: @expr{@tfn{idn}(a) + b} to @expr{a + b} if @expr{b}
22644is provably scalar, or expanded out if @expr{b} is a matrix;
40ba43b4
PE
22645@expr{@tfn{idn}(a) + @tfn{idn}(b)} to @expr{@tfn{idn}(a + b)};
22646@expr{-@tfn{idn}(a)} to @expr{@tfn{idn}(-a)}; @expr{a @tfn{idn}(b)} to
22647@expr{@tfn{idn}(a b)} if @expr{a} is provably scalar, or to @expr{a b}
4009494e
GM
22648if @expr{a} is provably non-scalar; @expr{@tfn{idn}(a) @tfn{idn}(b)} to
22649@expr{@tfn{idn}(a b)}; analogous simplifications for quotients involving
22650@code{idn}; and @expr{@tfn{idn}(a)^n} to @expr{@tfn{idn}(a^n)} where
22651@expr{n} is an integer.
22652
22653@tex
22654\bigskip
22655@end tex
22656
22657The @code{floor} function and other integer truncation functions
22658vanish if the argument is provably integer-valued, so that
22659@expr{@tfn{floor}(@tfn{round}(x))} simplifies to @expr{@tfn{round}(x)}.
22660Also, combinations of @code{float}, @code{floor} and its friends,
22661and @code{ffloor} and its friends, are simplified in appropriate
22662ways. @xref{Integer Truncation}.
22663
22664The expression @expr{@tfn{abs}(-x)} changes to @expr{@tfn{abs}(x)}.
22665The expression @expr{@tfn{abs}(@tfn{abs}(x))} changes to
22666@expr{@tfn{abs}(x)}; in fact, @expr{@tfn{abs}(x)} changes to @expr{x} or
22667@expr{-x} if @expr{x} is provably nonnegative or nonpositive
40ba43b4 22668(@pxref{Declarations}).
4009494e
GM
22669
22670While most functions do not recognize the variable @code{i} as an
22671imaginary number, the @code{arg} function does handle the two cases
22672@expr{@tfn{arg}(@tfn{i})} and @expr{@tfn{arg}(-@tfn{i})} just for convenience.
22673
22674The expression @expr{@tfn{conj}(@tfn{conj}(x))} simplifies to @expr{x}.
22675Various other expressions involving @code{conj}, @code{re}, and
22676@code{im} are simplified, especially if some of the arguments are
22677provably real or involve the constant @code{i}. For example,
40ba43b4 22678@expr{@tfn{conj}(a + b i)} is changed to
4009494e
GM
22679@expr{@tfn{conj}(a) - @tfn{conj}(b) i}, or to @expr{a - b i} if @expr{a}
22680and @expr{b} are known to be real.
22681
22682Functions like @code{sin} and @code{arctan} generally don't have
22683any default simplifications beyond simply evaluating the functions
8e7046c3
JB
22684for suitable numeric arguments and infinity. The algebraic
22685simplifications described in the next section do provide some
22686simplifications for these functions, though.
4009494e
GM
22687
22688One important simplification that does occur is that
22689@expr{@tfn{ln}(@tfn{e})} is simplified to 1, and @expr{@tfn{ln}(@tfn{e}^x)} is
22690simplified to @expr{x} for any @expr{x}. This occurs even if you have
22691stored a different value in the Calc variable @samp{e}; but this would
22692be a bad idea in any case if you were also using natural logarithms!
22693
22694Among the logical functions, @tfn{!(@var{a} <= @var{b})} changes to
22695@tfn{@var{a} > @var{b}} and so on. Equations and inequalities where both sides
22696are either negative-looking or zero are simplified by negating both sides
22697and reversing the inequality. While it might seem reasonable to simplify
22698@expr{!!x} to @expr{x}, this would not be valid in general because
22699@expr{!!2} is 1, not 2.
22700
8e7046c3 22701Most other Calc functions have few if any basic simplifications
4009494e
GM
22702defined, aside of course from evaluation when the arguments are
22703suitable numbers.
22704
8e7046c3 22705@node Algebraic Simplifications, Unsafe Simplifications, Basic Simplifications, Simplifying Formulas
4009494e
GM
22706@subsection Algebraic Simplifications
22707
22708@noindent
22709@cindex Algebraic simplifications
d2bd74ff 22710@kindex a s
8e7046c3 22711@kindex m A
4009494e 22712This section describes all simplifications that are performed by
8e7046c3
JB
22713the algebraic simplification mode, which is the default simplification
22714mode. If you have switched to a different simplification mode, you can
22715switch back with the @kbd{m A} command. Even in other simplification
22716modes, the @kbd{a s} command will use these algebraic simplifications to
22717simplify the formula.
4009494e
GM
22718
22719There is a variable, @code{AlgSimpRules}, in which you can put rewrites
d2bd74ff 22720to be applied. Its use is analogous to @code{EvalRules},
4009494e
GM
22721but without the special restrictions. Basically, the simplifier does
22722@samp{@w{a r} AlgSimpRules} with an infinite repeat count on the whole
22723expression being simplified, then it traverses the expression applying
22724the built-in rules described below. If the result is different from
8e7046c3 22725the original expression, the process repeats with the basic
4009494e
GM
22726simplifications (including @code{EvalRules}), then @code{AlgSimpRules},
22727then the built-in simplifications, and so on.
22728
22729@tex
22730\bigskip
22731@end tex
22732
22733Sums are simplified in two ways. Constant terms are commuted to the
22734end of the sum, so that @expr{a + 2 + b} changes to @expr{a + b + 2}.
22735The only exception is that a constant will not be commuted away
22736from the first position of a difference, i.e., @expr{2 - x} is not
22737commuted to @expr{-x + 2}.
22738
22739Also, terms of sums are combined by the distributive law, as in
22740@expr{x + y + 2 x} to @expr{y + 3 x}. This always occurs for
8e7046c3
JB
22741adjacent terms, but Calc's algebraic simplifications compare all pairs
22742of terms including non-adjacent ones.
4009494e
GM
22743
22744@tex
22745\bigskip
22746@end tex
22747
22748Products are sorted into a canonical order using the commutative
22749law. For example, @expr{b c a} is commuted to @expr{a b c}.
1dcac243 22750This allows easier comparison of products; for example, the basic
4009494e 22751simplifications will not change @expr{x y + y x} to @expr{2 x y},
d2bd74ff
JB
22752but the algebraic simplifications; it first rewrites the sum to
22753@expr{x y + x y} which can then be recognized as a sum of identical
22754terms.
4009494e
GM
22755
22756The canonical ordering used to sort terms of products has the
22757property that real-valued numbers, interval forms and infinities
22758come first, and are sorted into increasing order. The @kbd{V S}
22759command uses the same ordering when sorting a vector.
22760
22761Sorting of terms of products is inhibited when Matrix mode is
22762turned on; in this case, Calc will never exchange the order of
22763two terms unless it knows at least one of the terms is a scalar.
22764
22765Products of powers are distributed by comparing all pairs of
22766terms, using the same method that the default simplifications
22767use for adjacent terms of products.
22768
22769Even though sums are not sorted, the commutative law is still
22770taken into account when terms of a product are being compared.
22771Thus @expr{(x + y) (y + x)} will be simplified to @expr{(x + y)^2}.
22772A subtle point is that @expr{(x - y) (y - x)} will @emph{not}
22773be simplified to @expr{-(x - y)^2}; Calc does not notice that
22774one term can be written as a constant times the other, even if
22775that constant is @mathit{-1}.
22776
22777A fraction times any expression, @expr{(a:b) x}, is changed to
22778a quotient involving integers: @expr{a x / b}. This is not
22779done for floating-point numbers like @expr{0.5}, however. This
22780is one reason why you may find it convenient to turn Fraction mode
22781on while doing algebra; @pxref{Fraction Mode}.
22782
22783@tex
22784\bigskip
22785@end tex
22786
22787Quotients are simplified by comparing all terms in the numerator
22788with all terms in the denominator for possible cancellation using
22789the distributive law. For example, @expr{a x^2 b / c x^3 d} will
22790cancel @expr{x^2} from the top and bottom to get @expr{a b / c x d}.
22791(The terms in the denominator will then be rearranged to @expr{c d x}
22792as described above.) If there is any common integer or fractional
c80e3b4a 22793factor in the numerator and denominator, it is canceled out;
4009494e
GM
22794for example, @expr{(4 x + 6) / 8 x} simplifies to @expr{(2 x + 3) / 4 x}.
22795
d2bd74ff
JB
22796Non-constant common factors are not found even by algebraic
22797simplifications. To cancel the factor @expr{a} in
22798@expr{(a x + a) / a^2} you could first use @kbd{j M} on the product
22799@expr{a x} to Merge the numerator to @expr{a (1+x)}, which can then be
22800simplified successfully.
4009494e
GM
22801
22802@tex
22803\bigskip
22804@end tex
22805
22806Integer powers of the variable @code{i} are simplified according
22807to the identity @expr{i^2 = -1}. If you store a new value other
22808than the complex number @expr{(0,1)} in @code{i}, this simplification
1dcac243 22809will no longer occur. This is not done by the basic
d2bd74ff
JB
22810simplifications; in case someone (unwisely) wants to use the name
22811@code{i} for a variable unrelated to complex numbers, they can use
1dcac243 22812basic simplification mode.
4009494e
GM
22813
22814Square roots of integer or rational arguments are simplified in
22815several ways. (Note that these will be left unevaluated only in
22816Symbolic mode.) First, square integer or rational factors are
22817pulled out so that @expr{@tfn{sqrt}(8)} is rewritten as
22818@texline @math{2\,@tfn{sqrt}(2)}.
40ba43b4 22819@infoline @expr{2 sqrt(2)}.
4009494e
GM
22820Conceptually speaking this implies factoring the argument into primes
22821and moving pairs of primes out of the square root, but for reasons of
22822efficiency Calc only looks for primes up to 29.
22823
22824Square roots in the denominator of a quotient are moved to the
22825numerator: @expr{1 / @tfn{sqrt}(3)} changes to @expr{@tfn{sqrt}(3) / 3}.
22826The same effect occurs for the square root of a fraction:
22827@expr{@tfn{sqrt}(2:3)} changes to @expr{@tfn{sqrt}(6) / 3}.
22828
22829@tex
22830\bigskip
22831@end tex
22832
22833The @code{%} (modulo) operator is simplified in several ways
22834when the modulus @expr{M} is a positive real number. First, if
22835the argument is of the form @expr{x + n} for some real number
22836@expr{n}, then @expr{n} is itself reduced modulo @expr{M}. For
22837example, @samp{(x - 23) % 10} is simplified to @samp{(x + 7) % 10}.
22838
22839If the argument is multiplied by a constant, and this constant
22840has a common integer divisor with the modulus, then this factor is
c80e3b4a 22841canceled out. For example, @samp{12 x % 15} is changed to
4009494e
GM
22842@samp{3 (4 x % 5)} by factoring out 3. Also, @samp{(12 x + 1) % 15}
22843is changed to @samp{3 ((4 x + 1:3) % 5)}. While these forms may
22844not seem ``simpler,'' they allow Calc to discover useful information
22845about modulo forms in the presence of declarations.
22846
22847If the modulus is 1, then Calc can use @code{int} declarations to
22848evaluate the expression. For example, the idiom @samp{x % 2} is
22849often used to check whether a number is odd or even. As described
22850above, @w{@samp{2 n % 2}} and @samp{(2 n + 1) % 2} are simplified to
22851@samp{2 (n % 1)} and @samp{2 ((n + 1:2) % 1)}, respectively; Calc
22852can simplify these to 0 and 1 (respectively) if @code{n} has been
22853declared to be an integer.
22854
22855@tex
22856\bigskip
22857@end tex
22858
22859Trigonometric functions are simplified in several ways. Whenever a
22860products of two trigonometric functions can be replaced by a single
22861function, the replacement is made; for example,
40ba43b4 22862@expr{@tfn{tan}(x) @tfn{cos}(x)} is simplified to @expr{@tfn{sin}(x)}.
4009494e
GM
22863Reciprocals of trigonometric functions are replaced by their reciprocal
22864function; for example, @expr{1/@tfn{sec}(x)} is simplified to
22865@expr{@tfn{cos}(x)}. The corresponding simplifications for the
22866hyperbolic functions are also handled.
22867
22868Trigonometric functions of their inverse functions are
22869simplified. The expression @expr{@tfn{sin}(@tfn{arcsin}(x))} is
40ba43b4 22870simplified to @expr{x}, and similarly for @code{cos} and @code{tan}.
4009494e
GM
22871Trigonometric functions of inverses of different trigonometric
22872functions can also be simplified, as in @expr{@tfn{sin}(@tfn{arccos}(x))}
22873to @expr{@tfn{sqrt}(1 - x^2)}.
22874
22875If the argument to @code{sin} is negative-looking, it is simplified to
22876@expr{-@tfn{sin}(x)}, and similarly for @code{cos} and @code{tan}.
22877Finally, certain special values of the argument are recognized;
22878@pxref{Trigonometric and Hyperbolic Functions}.
22879
22880Hyperbolic functions of their inverses and of negative-looking
22881arguments are also handled, as are exponentials of inverse
22882hyperbolic functions.
22883
22884No simplifications for inverse trigonometric and hyperbolic
22885functions are known, except for negative arguments of @code{arcsin},
22886@code{arctan}, @code{arcsinh}, and @code{arctanh}. Note that
22887@expr{@tfn{arcsin}(@tfn{sin}(x))} can @emph{not} safely change to
40ba43b4 22888@expr{x}, since this only correct within an integer multiple of
4009494e 22889@texline @math{2 \pi}
40ba43b4 22890@infoline @expr{2 pi}
4009494e
GM
22891radians or 360 degrees. However, @expr{@tfn{arcsinh}(@tfn{sinh}(x))} is
22892simplified to @expr{x} if @expr{x} is known to be real.
22893
22894Several simplifications that apply to logarithms and exponentials
40ba43b4 22895are that @expr{@tfn{exp}(@tfn{ln}(x))},
4009494e 22896@texline @tfn{e}@math{^{\ln(x)}},
40ba43b4 22897@infoline @expr{e^@tfn{ln}(x)},
4009494e
GM
22898and
22899@texline @math{10^{{\rm log10}(x)}}
40ba43b4 22900@infoline @expr{10^@tfn{log10}(x)}
4009494e
GM
22901all reduce to @expr{x}. Also, @expr{@tfn{ln}(@tfn{exp}(x))}, etc., can
22902reduce to @expr{x} if @expr{x} is provably real. The form
22903@expr{@tfn{exp}(x)^y} is simplified to @expr{@tfn{exp}(x y)}. If @expr{x}
40ba43b4
PE
22904is a suitable multiple of
22905@texline @math{\pi i}
4009494e
GM
22906@infoline @expr{pi i}
22907(as described above for the trigonometric functions), then
22908@expr{@tfn{exp}(x)} or @expr{e^x} will be expanded. Finally,
22909@expr{@tfn{ln}(x)} is simplified to a form involving @code{pi} and
22910@code{i} where @expr{x} is provably negative, positive imaginary, or
40ba43b4 22911negative imaginary.
4009494e
GM
22912
22913The error functions @code{erf} and @code{erfc} are simplified when
22914their arguments are negative-looking or are calls to the @code{conj}
22915function.
22916
22917@tex
22918\bigskip
22919@end tex
22920
c80e3b4a 22921Equations and inequalities are simplified by canceling factors
4009494e 22922of products, quotients, or sums on both sides. Inequalities
c80e3b4a 22923change sign if a negative multiplicative factor is canceled.
4009494e 22924Non-constant multiplicative factors as in @expr{a b = a c} are
c80e3b4a 22925canceled from equations only if they are provably nonzero (generally
4009494e 22926because they were declared so; @pxref{Declarations}). Factors
c80e3b4a 22927are canceled from inequalities only if they are nonzero and their
4009494e
GM
22928sign is known.
22929
22930Simplification also replaces an equation or inequality with
229311 or 0 (``true'' or ``false'') if it can through the use of
22932declarations. If @expr{x} is declared to be an integer greater
22933than 5, then @expr{x < 3}, @expr{x = 3}, and @expr{x = 7.5} are
22934all simplified to 0, but @expr{x > 3} is simplified to 1.
22935By a similar analysis, @expr{abs(x) >= 0} is simplified to 1,
22936as is @expr{x^2 >= 0} if @expr{x} is known to be real.
22937
22938@node Unsafe Simplifications, Simplification of Units, Algebraic Simplifications, Simplifying Formulas
22939@subsection ``Unsafe'' Simplifications
22940
22941@noindent
22942@cindex Unsafe simplifications
22943@cindex Extended simplification
22944@kindex a e
8e7046c3 22945@kindex m E
4009494e
GM
22946@pindex calc-simplify-extended
22947@ignore
22948@mindex esimpl@idots
22949@end ignore
22950@tindex esimplify
8e7046c3
JB
22951Calc is capable of performing some simplifications which may sometimes
22952be desired but which are not ``safe'' in all cases. The @kbd{a e}
22953(@code{calc-simplify-extended}) [@code{esimplify}] command
22954applies the algebraic simplifications as well as these extended, or
22955``unsafe'', simplifications. Use this only if you know the values in
22956your formula lie in the restricted ranges for which these
22957simplifications are valid. You can use Extended Simplification mode
22958(@kbd{m E}) to have these simplifications done automatically.
22959
22960The symbolic integrator uses these extended simplifications; one effect
22961of this is that the integrator's results must be used with caution.
22962Where an integral table will often attach conditions like ``for positive
22963@expr{a} only,'' Calc (like most other symbolic integration programs)
22964will simply produce an unqualified result.
4009494e
GM
22965
22966Because @kbd{a e}'s simplifications are unsafe, it is sometimes better
22967to type @kbd{C-u -3 a v}, which does extended simplification only
22968on the top level of the formula without affecting the sub-formulas.
22969In fact, @kbd{C-u -3 j v} allows you to target extended simplification
22970to any specific part of a formula.
22971
8e7046c3
JB
22972The variable @code{ExtSimpRules} contains rewrites to be applied when
22973the extended simplifications are used. These are applied in addition to
4009494e
GM
22974@code{EvalRules} and @code{AlgSimpRules}. (The @kbd{a r AlgSimpRules}
22975step described above is simply followed by an @kbd{a r ExtSimpRules} step.)
22976
8e7046c3 22977Following is a complete list of the ``unsafe'' simplifications.
4009494e
GM
22978
22979@tex
22980\bigskip
22981@end tex
22982
22983Inverse trigonometric or hyperbolic functions, called with their
8e7046c3
JB
22984corresponding non-inverse functions as arguments, are simplified.
22985For example, @expr{@tfn{arcsin}(@tfn{sin}(x))} changes
4009494e
GM
22986to @expr{x}. Also, @expr{@tfn{arcsin}(@tfn{cos}(x))} and
22987@expr{@tfn{arccos}(@tfn{sin}(x))} both change to @expr{@tfn{pi}/2 - x}.
22988These simplifications are unsafe because they are valid only for
22989values of @expr{x} in a certain range; outside that range, values
22990are folded down to the 360-degree range that the inverse trigonometric
22991functions always produce.
22992
40ba43b4 22993Powers of powers @expr{(x^a)^b} are simplified to
4009494e
GM
22994@texline @math{x^{a b}}
22995@infoline @expr{x^(a b)}
22996for all @expr{a} and @expr{b}. These results will be valid only
40ba43b4 22997in a restricted range of @expr{x}; for example, in
4009494e
GM
22998@texline @math{(x^2)^{1:2}}
22999@infoline @expr{(x^2)^1:2}
23000the powers cancel to get @expr{x}, which is valid for positive values
23001of @expr{x} but not for negative or complex values.
23002
23003Similarly, @expr{@tfn{sqrt}(x^a)} and @expr{@tfn{sqrt}(x)^a} are both
40ba43b4 23004simplified (possibly unsafely) to
4009494e
GM
23005@texline @math{x^{a/2}}.
23006@infoline @expr{x^(a/2)}.
23007
23008Forms like @expr{@tfn{sqrt}(1 - sin(x)^2)} are simplified to, e.g.,
23009@expr{@tfn{cos}(x)}. Calc has identities of this sort for @code{sin},
23010@code{cos}, @code{tan}, @code{sinh}, and @code{cosh}.
23011
23012Arguments of square roots are partially factored to look for
23013squared terms that can be extracted. For example,
40ba43b4 23014@expr{@tfn{sqrt}(a^2 b^3 + a^3 b^2)} simplifies to
4009494e
GM
23015@expr{a b @tfn{sqrt}(a+b)}.
23016
23017The simplifications of @expr{@tfn{ln}(@tfn{exp}(x))},
23018@expr{@tfn{ln}(@tfn{e}^x)}, and @expr{@tfn{log10}(10^x)} to @expr{x} are also
23019unsafe because of problems with principal values (although these
23020simplifications are safe if @expr{x} is known to be real).
23021
c80e3b4a 23022Common factors are canceled from products on both sides of an
4009494e 23023equation, even if those factors may be zero: @expr{a x / b x}
c80e3b4a 23024to @expr{a / b}. Such factors are never canceled from
8e7046c3
JB
23025inequalities: Even the extended simplifications are not bold enough to
23026reduce @expr{a x < b x} to @expr{a < b} (or @expr{a > b}, depending
4009494e
GM
23027on whether you believe @expr{x} is positive or negative).
23028The @kbd{a M /} command can be used to divide a factor out of
23029both sides of an inequality.
23030
23031@node Simplification of Units, , Unsafe Simplifications, Simplifying Formulas
23032@subsection Simplification of Units
23033
23034@noindent
8e7046c3
JB
23035The simplifications described in this section (as well as the algebraic
23036simplifications) are applied when units need to be simplified. They can
23037be applied using the @kbd{u s} (@code{calc-simplify-units}) command, or
23038will be done automatically in Units Simplification mode (@kbd{m U}).
23039@xref{Basic Operations on Units}.
4009494e
GM
23040
23041The variable @code{UnitSimpRules} contains rewrites to be applied by
8e7046c3 23042units simplifications. These are applied in addition to @code{EvalRules}
4009494e
GM
23043and @code{AlgSimpRules}.
23044
23045Scalar mode is automatically put into effect when simplifying units.
23046@xref{Matrix Mode}.
23047
23048Sums @expr{a + b} involving units are simplified by extracting the
23049units of @expr{a} as if by the @kbd{u x} command (call the result
23050@expr{u_a}), then simplifying the expression @expr{b / u_a}
23051using @kbd{u b} and @kbd{u s}. If the result has units then the sum
23052is inconsistent and is left alone. Otherwise, it is rewritten
23053in terms of the units @expr{u_a}.
23054
23055If units auto-ranging mode is enabled, products or quotients in
23056which the first argument is a number which is out of range for the
23057leading unit are modified accordingly.
23058
c80e3b4a 23059When canceling and combining units in products and quotients,
4009494e
GM
23060Calc accounts for unit names that differ only in the prefix letter.
23061For example, @samp{2 km m} is simplified to @samp{2000 m^2}.
23062However, compatible but different units like @code{ft} and @code{in}
23063are not combined in this way.
23064
23065Quotients @expr{a / b} are simplified in three additional ways. First,
23066if @expr{b} is a number or a product beginning with a number, Calc
23067computes the reciprocal of this number and moves it to the numerator.
23068
23069Second, for each pair of unit names from the numerator and denominator
23070of a quotient, if the units are compatible (e.g., they are both
23071units of area) then they are replaced by the ratio between those
23072units. For example, in @samp{3 s in N / kg cm} the units
23073@samp{in / cm} will be replaced by @expr{2.54}.
23074
23075Third, if the units in the quotient exactly cancel out, so that
23076a @kbd{u b} command on the quotient would produce a dimensionless
23077number for an answer, then the quotient simplifies to that number.
23078
23079For powers and square roots, the ``unsafe'' simplifications
23080@expr{(a b)^c} to @expr{a^c b^c}, @expr{(a/b)^c} to @expr{a^c / b^c},
40ba43b4 23081and @expr{(a^b)^c} to
4009494e 23082@texline @math{a^{b c}}
40ba43b4 23083@infoline @expr{a^(b c)}
4009494e
GM
23084are done if the powers are real numbers. (These are safe in the context
23085of units because all numbers involved can reasonably be assumed to be
23086real.)
23087
23088Also, if a unit name is raised to a fractional power, and the
23089base units in that unit name all occur to powers which are a
23090multiple of the denominator of the power, then the unit name
23091is expanded out into its base units, which can then be simplified
23092according to the previous paragraph. For example, @samp{acre^1.5}
23093is simplified by noting that @expr{1.5 = 3:2}, that @samp{acre}
23094is defined in terms of @samp{m^2}, and that the 2 in the power of
23095@code{m} is a multiple of 2 in @expr{3:2}. Thus, @code{acre^1.5} is
40ba43b4 23096replaced by approximately
4009494e 23097@texline @math{(4046 m^2)^{1.5}}
40ba43b4
PE
23098@infoline @expr{(4046 m^2)^1.5},
23099which is then changed to
4009494e 23100@texline @math{4046^{1.5} \, (m^2)^{1.5}},
40ba43b4 23101@infoline @expr{4046^1.5 (m^2)^1.5},
4009494e
GM
23102then to @expr{257440 m^3}.
23103
23104The functions @code{float}, @code{frac}, @code{clean}, @code{abs},
23105as well as @code{floor} and the other integer truncation functions,
23106applied to unit names or products or quotients involving units, are
23107simplified. For example, @samp{round(1.6 in)} is changed to
23108@samp{round(1.6) round(in)}; the lefthand term evaluates to 2,
23109and the righthand term simplifies to @code{in}.
23110
23111The functions @code{sin}, @code{cos}, and @code{tan} with arguments
23112that have angular units like @code{rad} or @code{arcmin} are
23113simplified by converting to base units (radians), then evaluating
23114with the angular mode temporarily set to radians.
23115
23116@node Polynomials, Calculus, Simplifying Formulas, Algebra
23117@section Polynomials
23118
23119A @dfn{polynomial} is a sum of terms which are coefficients times
23120various powers of a ``base'' variable. For example, @expr{2 x^2 + 3 x - 4}
23121is a polynomial in @expr{x}. Some formulas can be considered
23122polynomials in several different variables: @expr{1 + 2 x + 3 y + 4 x y^2}
23123is a polynomial in both @expr{x} and @expr{y}. Polynomial coefficients
23124are often numbers, but they may in general be any formulas not
23125involving the base variable.
23126
23127@kindex a f
23128@pindex calc-factor
23129@tindex factor
23130The @kbd{a f} (@code{calc-factor}) [@code{factor}] command factors a
23131polynomial into a product of terms. For example, the polynomial
23132@expr{x^3 + 2 x^2 + x} is factored into @samp{x*(x+1)^2}. As another
23133example, @expr{a c + b d + b c + a d} is factored into the product
23134@expr{(a + b) (c + d)}.
23135
23136Calc currently has three algorithms for factoring. Formulas which are
23137linear in several variables, such as the second example above, are
23138merged according to the distributive law. Formulas which are
23139polynomials in a single variable, with constant integer or fractional
23140coefficients, are factored into irreducible linear and/or quadratic
23141terms. The first example above factors into three linear terms
23142(@expr{x}, @expr{x+1}, and @expr{x+1} again). Finally, formulas
23143which do not fit the above criteria are handled by the algebraic
23144rewrite mechanism.
23145
23146Calc's polynomial factorization algorithm works by using the general
23147root-finding command (@w{@kbd{a P}}) to solve for the roots of the
23148polynomial. It then looks for roots which are rational numbers
23149or complex-conjugate pairs, and converts these into linear and
23150quadratic terms, respectively. Because it uses floating-point
23151arithmetic, it may be unable to find terms that involve large
23152integers (whose number of digits approaches the current precision).
23153Also, irreducible factors of degree higher than quadratic are not
23154found, and polynomials in more than one variable are not treated.
23155(A more robust factorization algorithm may be included in a future
23156version of Calc.)
23157
23158@vindex FactorRules
23159@ignore
23160@starindex
23161@end ignore
23162@tindex thecoefs
23163@ignore
23164@starindex
23165@end ignore
23166@ignore
23167@mindex @idots
23168@end ignore
23169@tindex thefactors
23170The rewrite-based factorization method uses rules stored in the variable
23171@code{FactorRules}. @xref{Rewrite Rules}, for a discussion of the
23172operation of rewrite rules. The default @code{FactorRules} are able
23173to factor quadratic forms symbolically into two linear terms,
23174@expr{(a x + b) (c x + d)}. You can edit these rules to include other
23175cases if you wish. To use the rules, Calc builds the formula
23176@samp{thecoefs(x, [a, b, c, ...])} where @code{x} is the polynomial
23177base variable and @code{a}, @code{b}, etc., are polynomial coefficients
23178(which may be numbers or formulas). The constant term is written first,
23179i.e., in the @code{a} position. When the rules complete, they should have
23180changed the formula into the form @samp{thefactors(x, [f1, f2, f3, ...])}
23181where each @code{fi} should be a factored term, e.g., @samp{x - ai}.
23182Calc then multiplies these terms together to get the complete
23183factored form of the polynomial. If the rules do not change the
23184@code{thecoefs} call to a @code{thefactors} call, @kbd{a f} leaves the
23185polynomial alone on the assumption that it is unfactorable. (Note that
23186the function names @code{thecoefs} and @code{thefactors} are used only
23187as placeholders; there are no actual Calc functions by those names.)
23188
23189@kindex H a f
23190@tindex factors
23191The @kbd{H a f} [@code{factors}] command also factors a polynomial,
23192but it returns a list of factors instead of an expression which is the
23193product of the factors. Each factor is represented by a sub-vector
23194of the factor, and the power with which it appears. For example,
23195@expr{x^5 + x^4 - 33 x^3 + 63 x^2} factors to @expr{(x + 7) x^2 (x - 3)^2}
23196in @kbd{a f}, or to @expr{[ [x, 2], [x+7, 1], [x-3, 2] ]} in @kbd{H a f}.
23197If there is an overall numeric factor, it always comes first in the list.
23198The functions @code{factor} and @code{factors} allow a second argument
23199when written in algebraic form; @samp{factor(x,v)} factors @expr{x} with
23200respect to the specific variable @expr{v}. The default is to factor with
23201respect to all the variables that appear in @expr{x}.
23202
23203@kindex a c
23204@pindex calc-collect
23205@tindex collect
23206The @kbd{a c} (@code{calc-collect}) [@code{collect}] command rearranges a
23207formula as a
23208polynomial in a given variable, ordered in decreasing powers of that
23209variable. For example, given @expr{1 + 2 x + 3 y + 4 x y^2} on
23210the stack, @kbd{a c x} would produce @expr{(2 + 4 y^2) x + (1 + 3 y)},
23211and @kbd{a c y} would produce @expr{(4 x) y^2 + 3 y + (1 + 2 x)}.
23212The polynomial will be expanded out using the distributive law as
23213necessary: Collecting @expr{x} in @expr{(x - 1)^3} produces
23214@expr{x^3 - 3 x^2 + 3 x - 1}. Terms not involving @expr{x} will
23215not be expanded.
23216
23217The ``variable'' you specify at the prompt can actually be any
23218expression: @kbd{a c ln(x+1)} will collect together all terms multiplied
23219by @samp{ln(x+1)} or integer powers thereof. If @samp{x} also appears
23220in the formula in a context other than @samp{ln(x+1)}, @kbd{a c} will
23221treat those occurrences as unrelated to @samp{ln(x+1)}, i.e., as constants.
23222
23223@kindex a x
23224@pindex calc-expand
23225@tindex expand
23226The @kbd{a x} (@code{calc-expand}) [@code{expand}] command expands an
23227expression by applying the distributive law everywhere. It applies to
23228products, quotients, and powers involving sums. By default, it fully
23229distributes all parts of the expression. With a numeric prefix argument,
23230the distributive law is applied only the specified number of times, then
23231the partially expanded expression is left on the stack.
23232
23233The @kbd{a x} and @kbd{j D} commands are somewhat redundant. Use
23234@kbd{a x} if you want to expand all products of sums in your formula.
23235Use @kbd{j D} if you want to expand a particular specified term of
23236the formula. There is an exactly analogous correspondence between
23237@kbd{a f} and @kbd{j M}. (The @kbd{j D} and @kbd{j M} commands
23238also know many other kinds of expansions, such as
23239@samp{exp(a + b) = exp(a) exp(b)}, which @kbd{a x} and @kbd{a f}
23240do not do.)
23241
23242Calc's automatic simplifications will sometimes reverse a partial
23243expansion. For example, the first step in expanding @expr{(x+1)^3} is
23244to write @expr{(x+1) (x+1)^2}. If @kbd{a x} stops there and tries
23245to put this formula onto the stack, though, Calc will automatically
23246simplify it back to @expr{(x+1)^3} form. The solution is to turn
23247simplification off first (@pxref{Simplification Modes}), or to run
23248@kbd{a x} without a numeric prefix argument so that it expands all
23249the way in one step.
23250
23251@kindex a a
23252@pindex calc-apart
23253@tindex apart
23254The @kbd{a a} (@code{calc-apart}) [@code{apart}] command expands a
23255rational function by partial fractions. A rational function is the
23256quotient of two polynomials; @code{apart} pulls this apart into a
23257sum of rational functions with simple denominators. In algebraic
23258notation, the @code{apart} function allows a second argument that
23259specifies which variable to use as the ``base''; by default, Calc
23260chooses the base variable automatically.
23261
23262@kindex a n
23263@pindex calc-normalize-rat
23264@tindex nrat
23265The @kbd{a n} (@code{calc-normalize-rat}) [@code{nrat}] command
23266attempts to arrange a formula into a quotient of two polynomials.
23267For example, given @expr{1 + (a + b/c) / d}, the result would be
23268@expr{(b + a c + c d) / c d}. The quotient is reduced, so that
23269@kbd{a n} will simplify @expr{(x^2 + 2x + 1) / (x^2 - 1)} by dividing
23270out the common factor @expr{x + 1}, yielding @expr{(x + 1) / (x - 1)}.
23271
23272@kindex a \
23273@pindex calc-poly-div
23274@tindex pdiv
23275The @kbd{a \} (@code{calc-poly-div}) [@code{pdiv}] command divides
23276two polynomials @expr{u} and @expr{v}, yielding a new polynomial
23277@expr{q}. If several variables occur in the inputs, the inputs are
23278considered multivariate polynomials. (Calc divides by the variable
23279with the largest power in @expr{u} first, or, in the case of equal
23280powers, chooses the variables in alphabetical order.) For example,
23281dividing @expr{x^2 + 3 x + 2} by @expr{x + 2} yields @expr{x + 1}.
23282The remainder from the division, if any, is reported at the bottom
23283of the screen and is also placed in the Trail along with the quotient.
23284
23285Using @code{pdiv} in algebraic notation, you can specify the particular
23286variable to be used as the base: @code{pdiv(@var{a},@var{b},@var{x})}.
23287If @code{pdiv} is given only two arguments (as is always the case with
23288the @kbd{a \} command), then it does a multivariate division as outlined
23289above.
23290
23291@kindex a %
23292@pindex calc-poly-rem
23293@tindex prem
23294The @kbd{a %} (@code{calc-poly-rem}) [@code{prem}] command divides
23295two polynomials and keeps the remainder @expr{r}. The quotient
23296@expr{q} is discarded. For any formulas @expr{a} and @expr{b}, the
23297results of @kbd{a \} and @kbd{a %} satisfy @expr{a = q b + r}.
23298(This is analogous to plain @kbd{\} and @kbd{%}, which compute the
23299integer quotient and remainder from dividing two numbers.)
23300
23301@kindex a /
23302@kindex H a /
23303@pindex calc-poly-div-rem
23304@tindex pdivrem
23305@tindex pdivide
23306The @kbd{a /} (@code{calc-poly-div-rem}) [@code{pdivrem}] command
23307divides two polynomials and reports both the quotient and the
23308remainder as a vector @expr{[q, r]}. The @kbd{H a /} [@code{pdivide}]
23309command divides two polynomials and constructs the formula
23310@expr{q + r/b} on the stack. (Naturally if the remainder is zero,
23311this will immediately simplify to @expr{q}.)
23312
23313@kindex a g
23314@pindex calc-poly-gcd
23315@tindex pgcd
23316The @kbd{a g} (@code{calc-poly-gcd}) [@code{pgcd}] command computes
23317the greatest common divisor of two polynomials. (The GCD actually
23318is unique only to within a constant multiplier; Calc attempts to
23319choose a GCD which will be unsurprising.) For example, the @kbd{a n}
23320command uses @kbd{a g} to take the GCD of the numerator and denominator
23321of a quotient, then divides each by the result using @kbd{a \}. (The
23322definition of GCD ensures that this division can take place without
23323leaving a remainder.)
23324
23325While the polynomials used in operations like @kbd{a /} and @kbd{a g}
23326often have integer coefficients, this is not required. Calc can also
23327deal with polynomials over the rationals or floating-point reals.
23328Polynomials with modulo-form coefficients are also useful in many
23329applications; if you enter @samp{(x^2 + 3 x - 1) mod 5}, Calc
23330automatically transforms this into a polynomial over the field of
23331integers mod 5: @samp{(1 mod 5) x^2 + (3 mod 5) x + (4 mod 5)}.
23332
23333Congratulations and thanks go to Ove Ewerlid
23334(@code{ewerlid@@mizar.DoCS.UU.SE}), who contributed many of the
23335polynomial routines used in the above commands.
23336
23337@xref{Decomposing Polynomials}, for several useful functions for
23338extracting the individual coefficients of a polynomial.
23339
23340@node Calculus, Solving Equations, Polynomials, Algebra
23341@section Calculus
23342
23343@noindent
23344The following calculus commands do not automatically simplify their
23345inputs or outputs using @code{calc-simplify}. You may find it helps
23346to do this by hand by typing @kbd{a s} or @kbd{a e}. It may also help
23347to use @kbd{a x} and/or @kbd{a c} to arrange a result in the most
23348readable way.
23349
23350@menu
23351* Differentiation::
23352* Integration::
23353* Customizing the Integrator::
23354* Numerical Integration::
23355* Taylor Series::
23356@end menu
23357
23358@node Differentiation, Integration, Calculus, Calculus
23359@subsection Differentiation
23360
23361@noindent
23362@kindex a d
23363@kindex H a d
23364@pindex calc-derivative
23365@tindex deriv
23366@tindex tderiv
23367The @kbd{a d} (@code{calc-derivative}) [@code{deriv}] command computes
23368the derivative of the expression on the top of the stack with respect to
23369some variable, which it will prompt you to enter. Normally, variables
23370in the formula other than the specified differentiation variable are
23371considered constant, i.e., @samp{deriv(y,x)} is reduced to zero. With
23372the Hyperbolic flag, the @code{tderiv} (total derivative) operation is used
23373instead, in which derivatives of variables are not reduced to zero
23374unless those variables are known to be ``constant,'' i.e., independent
23375of any other variables. (The built-in special variables like @code{pi}
23376are considered constant, as are variables that have been declared
23377@code{const}; @pxref{Declarations}.)
23378
23379With a numeric prefix argument @var{n}, this command computes the
23380@var{n}th derivative.
23381
23382When working with trigonometric functions, it is best to switch to
23383Radians mode first (with @w{@kbd{m r}}). The derivative of @samp{sin(x)}
23384in degrees is @samp{(pi/180) cos(x)}, probably not the expected
23385answer!
23386
23387If you use the @code{deriv} function directly in an algebraic formula,
23388you can write @samp{deriv(f,x,x0)} which represents the derivative
40ba43b4 23389of @expr{f} with respect to @expr{x}, evaluated at the point
4009494e
GM
23390@texline @math{x=x_0}.
23391@infoline @expr{x=x0}.
23392
23393If the formula being differentiated contains functions which Calc does
23394not know, the derivatives of those functions are produced by adding
23395primes (apostrophe characters). For example, @samp{deriv(f(2x), x)}
23396produces @samp{2 f'(2 x)}, where the function @code{f'} represents the
23397derivative of @code{f}.
23398
23399For functions you have defined with the @kbd{Z F} command, Calc expands
23400the functions according to their defining formulas unless you have
23401also defined @code{f'} suitably. For example, suppose we define
23402@samp{sinc(x) = sin(x)/x} using @kbd{Z F}. If we then differentiate
23403the formula @samp{sinc(2 x)}, the formula will be expanded to
23404@samp{sin(2 x) / (2 x)} and differentiated. However, if we also
23405define @samp{sinc'(x) = dsinc(x)}, say, then Calc will write the
23406result as @samp{2 dsinc(2 x)}. @xref{Algebraic Definitions}.
23407
23408For multi-argument functions @samp{f(x,y,z)}, the derivative with respect
23409to the first argument is written @samp{f'(x,y,z)}; derivatives with
23410respect to the other arguments are @samp{f'2(x,y,z)} and @samp{f'3(x,y,z)}.
23411Various higher-order derivatives can be formed in the obvious way, e.g.,
23412@samp{f'@var{}'(x)} (the second derivative of @code{f}) or
23413@samp{f'@var{}'2'3(x,y,z)} (@code{f} differentiated with respect to each
23414argument once).
23415
23416@node Integration, Customizing the Integrator, Differentiation, Calculus
23417@subsection Integration
23418
23419@noindent
23420@kindex a i
23421@pindex calc-integral
23422@tindex integ
23423The @kbd{a i} (@code{calc-integral}) [@code{integ}] command computes the
23424indefinite integral of the expression on the top of the stack with
23425respect to a prompted-for variable. The integrator is not guaranteed to
23426work for all integrable functions, but it is able to integrate several
23427large classes of formulas. In particular, any polynomial or rational
23428function (a polynomial divided by a polynomial) is acceptable.
40ba43b4 23429(Rational functions don't have to be in explicit quotient form, however;
4009494e
GM
23430@texline @math{x/(1+x^{-2})}
23431@infoline @expr{x/(1+x^-2)}
23432is not strictly a quotient of polynomials, but it is equivalent to
23433@expr{x^3/(x^2+1)}, which is.) Also, square roots of terms involving
23434@expr{x} and @expr{x^2} may appear in rational functions being
23435integrated. Finally, rational functions involving trigonometric or
23436hyperbolic functions can be integrated.
23437
23438With an argument (@kbd{C-u a i}), this command will compute the definite
23439integral of the expression on top of the stack. In this case, the
23440command will again prompt for an integration variable, then prompt for a
23441lower limit and an upper limit.
23442
23443@ifnottex
23444If you use the @code{integ} function directly in an algebraic formula,
23445you can also write @samp{integ(f,x,v)} which expresses the resulting
23446indefinite integral in terms of variable @code{v} instead of @code{x}.
23447With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
23448integral from @code{a} to @code{b}.
23449@end ifnottex
23450@tex
23451If you use the @code{integ} function directly in an algebraic formula,
23452you can also write @samp{integ(f,x,v)} which expresses the resulting
23453indefinite integral in terms of variable @code{v} instead of @code{x}.
23454With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
23455integral $\int_a^b f(x) \, dx$.
23456@end tex
23457
23458Please note that the current implementation of Calc's integrator sometimes
23459produces results that are significantly more complex than they need to
40ba43b4 23460be. For example, the integral Calc finds for
4009494e
GM
23461@texline @math{1/(x+\sqrt{x^2+1})}
23462@infoline @expr{1/(x+sqrt(x^2+1))}
23463is several times more complicated than the answer Mathematica
23464returns for the same input, although the two forms are numerically
23465equivalent. Also, any indefinite integral should be considered to have
23466an arbitrary constant of integration added to it, although Calc does not
23467write an explicit constant of integration in its result. For example,
40ba43b4 23468Calc's solution for
4009494e 23469@texline @math{1/(1+\tan x)}
40ba43b4 23470@infoline @expr{1/(1+tan(x))}
4009494e 23471differs from the solution given in the @emph{CRC Math Tables} by a
40ba43b4 23472constant factor of
4009494e
GM
23473@texline @math{\pi i / 2}
23474@infoline @expr{pi i / 2},
23475due to a different choice of constant of integration.
23476
23477The Calculator remembers all the integrals it has done. If conditions
23478change in a way that would invalidate the old integrals, say, a switch
23479from Degrees to Radians mode, then they will be thrown out. If you
23480suspect this is not happening when it should, use the
23481@code{calc-flush-caches} command; @pxref{Caches}.
23482
23483@vindex IntegLimit
23484Calc normally will pursue integration by substitution or integration by
23485parts up to 3 nested times before abandoning an approach as fruitless.
23486If the integrator is taking too long, you can lower this limit by storing
23487a number (like 2) in the variable @code{IntegLimit}. (The @kbd{s I}
23488command is a convenient way to edit @code{IntegLimit}.) If this variable
23489has no stored value or does not contain a nonnegative integer, a limit
23490of 3 is used. The lower this limit is, the greater the chance that Calc
23491will be unable to integrate a function it could otherwise handle. Raising
23492this limit allows the Calculator to solve more integrals, though the time
23493it takes may grow exponentially. You can monitor the integrator's actions
23494by creating an Emacs buffer called @code{*Trace*}. If such a buffer
23495exists, the @kbd{a i} command will write a log of its actions there.
23496
23497If you want to manipulate integrals in a purely symbolic way, you can
23498set the integration nesting limit to 0 to prevent all but fast
23499table-lookup solutions of integrals. You might then wish to define
23500rewrite rules for integration by parts, various kinds of substitutions,
23501and so on. @xref{Rewrite Rules}.
23502
23503@node Customizing the Integrator, Numerical Integration, Integration, Calculus
23504@subsection Customizing the Integrator
23505
23506@noindent
23507@vindex IntegRules
23508Calc has two built-in rewrite rules called @code{IntegRules} and
23509@code{IntegAfterRules} which you can edit to define new integration
23510methods. @xref{Rewrite Rules}. At each step of the integration process,
23511Calc wraps the current integrand in a call to the fictitious function
23512@samp{integtry(@var{expr},@var{var})}, where @var{expr} is the
23513integrand and @var{var} is the integration variable. If your rules
23514rewrite this to be a plain formula (not a call to @code{integtry}), then
23515Calc will use this formula as the integral of @var{expr}. For example,
23516the rule @samp{integtry(mysin(x),x) := -mycos(x)} would define a rule to
23517integrate a function @code{mysin} that acts like the sine function.
23518Then, putting @samp{4 mysin(2y+1)} on the stack and typing @kbd{a i y}
23519will produce the integral @samp{-2 mycos(2y+1)}. Note that Calc has
23520automatically made various transformations on the integral to allow it
23521to use your rule; integral tables generally give rules for
23522@samp{mysin(a x + b)}, but you don't need to use this much generality
23523in your @code{IntegRules}.
23524
23525@cindex Exponential integral Ei(x)
23526@ignore
23527@starindex
23528@end ignore
23529@tindex Ei
23530As a more serious example, the expression @samp{exp(x)/x} cannot be
23531integrated in terms of the standard functions, so the ``exponential
40ba43b4 23532integral'' function
4009494e 23533@texline @math{{\rm Ei}(x)}
40ba43b4 23534@infoline @expr{Ei(x)}
4009494e
GM
23535was invented to describe it.
23536We can get Calc to do this integral in terms of a made-up @code{Ei}
23537function by adding the rule @samp{[integtry(exp(x)/x, x) := Ei(x)]}
23538to @code{IntegRules}. Now entering @samp{exp(2x)/x} on the stack
23539and typing @kbd{a i x} yields @samp{Ei(2 x)}. This new rule will
23540work with Calc's various built-in integration methods (such as
23541integration by substitution) to solve a variety of other problems
23542involving @code{Ei}: For example, now Calc will also be able to
23543integrate @samp{exp(exp(x))} and @samp{ln(ln(x))} (to get @samp{Ei(exp(x))}
23544and @samp{x ln(ln(x)) - Ei(ln(x))}, respectively).
23545
23546Your rule may do further integration by calling @code{integ}. For
23547example, @samp{integtry(twice(u),x) := twice(integ(u))} allows Calc
23548to integrate @samp{twice(sin(x))} to get @samp{twice(-cos(x))}.
23549Note that @code{integ} was called with only one argument. This notation
23550is allowed only within @code{IntegRules}; it means ``integrate this
23551with respect to the same integration variable.'' If Calc is unable
23552to integrate @code{u}, the integration that invoked @code{IntegRules}
23553also fails. Thus integrating @samp{twice(f(x))} fails, returning the
23554unevaluated integral @samp{integ(twice(f(x)), x)}. It is still valid
23555to call @code{integ} with two or more arguments, however; in this case,
23556if @code{u} is not integrable, @code{twice} itself will still be
23557integrated: If the above rule is changed to @samp{... := twice(integ(u,x))},
23558then integrating @samp{twice(f(x))} will yield @samp{twice(integ(f(x),x))}.
23559
23560If a rule instead produces the formula @samp{integsubst(@var{sexpr},
23561@var{svar})}, either replacing the top-level @code{integtry} call or
23562nested anywhere inside the expression, then Calc will apply the
23563substitution @samp{@var{u} = @var{sexpr}(@var{svar})} to try to
23564integrate the original @var{expr}. For example, the rule
23565@samp{sqrt(a) := integsubst(sqrt(x),x)} says that if Calc ever finds
23566a square root in the integrand, it should attempt the substitution
23567@samp{u = sqrt(x)}. (This particular rule is unnecessary because
23568Calc always tries ``obvious'' substitutions where @var{sexpr} actually
23569appears in the integrand.) The variable @var{svar} may be the same
23570as the @var{var} that appeared in the call to @code{integtry}, but
23571it need not be.
23572
23573When integrating according to an @code{integsubst}, Calc uses the
23574equation solver to find the inverse of @var{sexpr} (if the integrand
23575refers to @var{var} anywhere except in subexpressions that exactly
23576match @var{sexpr}). It uses the differentiator to find the derivative
23577of @var{sexpr} and/or its inverse (it has two methods that use one
23578derivative or the other). You can also specify these items by adding
23579extra arguments to the @code{integsubst} your rules construct; the
23580general form is @samp{integsubst(@var{sexpr}, @var{svar}, @var{sinv},
23581@var{sprime})}, where @var{sinv} is the inverse of @var{sexpr} (still
23582written as a function of @var{svar}), and @var{sprime} is the
23583derivative of @var{sexpr} with respect to @var{svar}. If you don't
23584specify these things, and Calc is not able to work them out on its
23585own with the information it knows, then your substitution rule will
23586work only in very specific, simple cases.
23587
23588Calc applies @code{IntegRules} as if by @kbd{C-u 1 a r IntegRules};
23589in other words, Calc stops rewriting as soon as any rule in your rule
23590set succeeds. (If it weren't for this, the @samp{integsubst(sqrt(x),x)}
23591example above would keep on adding layers of @code{integsubst} calls
23592forever!)
23593
23594@vindex IntegSimpRules
23595Another set of rules, stored in @code{IntegSimpRules}, are applied
8e7046c3
JB
23596every time the integrator uses algebraic simplifications to simplify an
23597intermediate result. For example, putting the rule
23598@samp{twice(x) := 2 x} into @code{IntegSimpRules} would tell Calc to
23599convert the @code{twice} function into a form it knows whenever
23600integration is attempted.
4009494e
GM
23601
23602One more way to influence the integrator is to define a function with
23603the @kbd{Z F} command (@pxref{Algebraic Definitions}). Calc's
23604integrator automatically expands such functions according to their
23605defining formulas, even if you originally asked for the function to
23606be left unevaluated for symbolic arguments. (Certain other Calc
23607systems, such as the differentiator and the equation solver, also
23608do this.)
23609
23610@vindex IntegAfterRules
23611Sometimes Calc is able to find a solution to your integral, but it
23612expresses the result in a way that is unnecessarily complicated. If
23613this happens, you can either use @code{integsubst} as described
23614above to try to hint at a more direct path to the desired result, or
23615you can use @code{IntegAfterRules}. This is an extra rule set that
23616runs after the main integrator returns its result; basically, Calc does
23617an @kbd{a r IntegAfterRules} on the result before showing it to you.
8e7046c3
JB
23618(It also does algebraic simplifications, without @code{IntegSimpRules},
23619after that to further simplify the result.) For example, Calc's integrator
4009494e
GM
23620sometimes produces expressions of the form @samp{ln(1+x) - ln(1-x)};
23621the default @code{IntegAfterRules} rewrite this into the more readable
23622form @samp{2 arctanh(x)}. Note that, unlike @code{IntegRules},
23623@code{IntegSimpRules} and @code{IntegAfterRules} are applied any number
23624of times until no further changes are possible. Rewriting by
23625@code{IntegAfterRules} occurs only after the main integrator has
23626finished, not at every step as for @code{IntegRules} and
23627@code{IntegSimpRules}.
23628
23629@node Numerical Integration, Taylor Series, Customizing the Integrator, Calculus
23630@subsection Numerical Integration
23631
23632@noindent
23633@kindex a I
23634@pindex calc-num-integral
23635@tindex ninteg
23636If you want a purely numerical answer to an integration problem, you can
23637use the @kbd{a I} (@code{calc-num-integral}) [@code{ninteg}] command. This
23638command prompts for an integration variable, a lower limit, and an
23639upper limit. Except for the integration variable, all other variables
23640that appear in the integrand formula must have stored values. (A stored
23641value, if any, for the integration variable itself is ignored.)
23642
23643Numerical integration works by evaluating your formula at many points in
23644the specified interval. Calc uses an ``open Romberg'' method; this means
23645that it does not evaluate the formula actually at the endpoints (so that
23646it is safe to integrate @samp{sin(x)/x} from zero, for example). Also,
23647the Romberg method works especially well when the function being
23648integrated is fairly smooth. If the function is not smooth, Calc will
23649have to evaluate it at quite a few points before it can accurately
23650determine the value of the integral.
23651
23652Integration is much faster when the current precision is small. It is
23653best to set the precision to the smallest acceptable number of digits
23654before you use @kbd{a I}. If Calc appears to be taking too long, press
23655@kbd{C-g} to halt it and try a lower precision. If Calc still appears
23656to need hundreds of evaluations, check to make sure your function is
23657well-behaved in the specified interval.
23658
23659It is possible for the lower integration limit to be @samp{-inf} (minus
23660infinity). Likewise, the upper limit may be plus infinity. Calc
23661internally transforms the integral into an equivalent one with finite
23662limits. However, integration to or across singularities is not supported:
23663The integral of @samp{1/sqrt(x)} from 0 to 1 exists (it can be found
23664by Calc's symbolic integrator, for example), but @kbd{a I} will fail
23665because the integrand goes to infinity at one of the endpoints.
23666
23667@node Taylor Series, , Numerical Integration, Calculus
23668@subsection Taylor Series
23669
23670@noindent
23671@kindex a t
23672@pindex calc-taylor
23673@tindex taylor
23674The @kbd{a t} (@code{calc-taylor}) [@code{taylor}] command computes a
23675power series expansion or Taylor series of a function. You specify the
23676variable and the desired number of terms. You may give an expression of
23677the form @samp{@var{var} = @var{a}} or @samp{@var{var} - @var{a}} instead
23678of just a variable to produce a Taylor expansion about the point @var{a}.
23679You may specify the number of terms with a numeric prefix argument;
23680otherwise the command will prompt you for the number of terms. Note that
23681many series expansions have coefficients of zero for some terms, so you
23682may appear to get fewer terms than you asked for.
23683
23684If the @kbd{a i} command is unable to find a symbolic integral for a
23685function, you can get an approximation by integrating the function's
23686Taylor series.
23687
23688@node Solving Equations, Numerical Solutions, Calculus, Algebra
23689@section Solving Equations
23690
23691@noindent
23692@kindex a S
23693@pindex calc-solve-for
23694@tindex solve
23695@cindex Equations, solving
23696@cindex Solving equations
23697The @kbd{a S} (@code{calc-solve-for}) [@code{solve}] command rearranges
23698an equation to solve for a specific variable. An equation is an
23699expression of the form @expr{L = R}. For example, the command @kbd{a S x}
23700will rearrange @expr{y = 3x + 6} to the form, @expr{x = y/3 - 2}. If the
23701input is not an equation, it is treated like an equation of the
23702form @expr{X = 0}.
23703
23704This command also works for inequalities, as in @expr{y < 3x + 6}.
23705Some inequalities cannot be solved where the analogous equation could
40ba43b4 23706be; for example, solving
4009494e 23707@texline @math{a < b \, c}
40ba43b4 23708@infoline @expr{a < b c}
4009494e
GM
23709for @expr{b} is impossible
23710without knowing the sign of @expr{c}. In this case, @kbd{a S} will
40ba43b4 23711produce the result
4009494e 23712@texline @math{b \mathbin{\hbox{\code{!=}}} a/c}
40ba43b4 23713@infoline @expr{b != a/c}
4009494e 23714(using the not-equal-to operator) to signify that the direction of the
40ba43b4 23715inequality is now unknown. The inequality
4009494e 23716@texline @math{a \le b \, c}
40ba43b4 23717@infoline @expr{a <= b c}
4009494e
GM
23718is not even partially solved. @xref{Declarations}, for a way to tell
23719Calc that the signs of the variables in a formula are in fact known.
23720
23721Two useful commands for working with the result of @kbd{a S} are
23722@kbd{a .} (@pxref{Logical Operations}), which converts @expr{x = y/3 - 2}
23723to @expr{y/3 - 2}, and @kbd{s l} (@pxref{Let Command}) which evaluates
23724another formula with @expr{x} set equal to @expr{y/3 - 2}.
23725
23726@menu
23727* Multiple Solutions::
23728* Solving Systems of Equations::
23729* Decomposing Polynomials::
23730@end menu
23731
23732@node Multiple Solutions, Solving Systems of Equations, Solving Equations, Solving Equations
23733@subsection Multiple Solutions
23734
23735@noindent
23736@kindex H a S
23737@tindex fsolve
23738Some equations have more than one solution. The Hyperbolic flag
23739(@code{H a S}) [@code{fsolve}] tells the solver to report the fully
23740general family of solutions. It will invent variables @code{n1},
23741@code{n2}, @dots{}, which represent independent arbitrary integers, and
23742@code{s1}, @code{s2}, @dots{}, which represent independent arbitrary
23743signs (either @mathit{+1} or @mathit{-1}). If you don't use the Hyperbolic
23744flag, Calc will use zero in place of all arbitrary integers, and plus
23745one in place of all arbitrary signs. Note that variables like @code{n1}
23746and @code{s1} are not given any special interpretation in Calc except by
23747the equation solver itself. As usual, you can use the @w{@kbd{s l}}
23748(@code{calc-let}) command to obtain solutions for various actual values
23749of these variables.
23750
23751For example, @kbd{' x^2 = y @key{RET} H a S x @key{RET}} solves to
23752get @samp{x = s1 sqrt(y)}, indicating that the two solutions to the
23753equation are @samp{sqrt(y)} and @samp{-sqrt(y)}. Another way to
23754think about it is that the square-root operation is really a
23755two-valued function; since every Calc function must return a
23756single result, @code{sqrt} chooses to return the positive result.
23757Then @kbd{H a S} doctors this result using @code{s1} to indicate
23758the full set of possible values of the mathematical square-root.
23759
23760There is a similar phenomenon going the other direction: Suppose
23761we solve @samp{sqrt(y) = x} for @code{y}. Calc squares both sides
23762to get @samp{y = x^2}. This is correct, except that it introduces
23763some dubious solutions. Consider solving @samp{sqrt(y) = -3}:
23764Calc will report @expr{y = 9} as a valid solution, which is true
23765in the mathematical sense of square-root, but false (there is no
23766solution) for the actual Calc positive-valued @code{sqrt}. This
23767happens for both @kbd{a S} and @kbd{H a S}.
23768
23769@cindex @code{GenCount} variable
23770@vindex GenCount
23771@ignore
23772@starindex
23773@end ignore
23774@tindex an
23775@ignore
23776@starindex
23777@end ignore
23778@tindex as
23779If you store a positive integer in the Calc variable @code{GenCount},
23780then Calc will generate formulas of the form @samp{as(@var{n})} for
23781arbitrary signs, and @samp{an(@var{n})} for arbitrary integers,
23782where @var{n} represents successive values taken by incrementing
23783@code{GenCount} by one. While the normal arbitrary sign and
23784integer symbols start over at @code{s1} and @code{n1} with each
23785new Calc command, the @code{GenCount} approach will give each
23786arbitrary value a name that is unique throughout the entire Calc
23787session. Also, the arbitrary values are function calls instead
23788of variables, which is advantageous in some cases. For example,
23789you can make a rewrite rule that recognizes all arbitrary signs
23790using a pattern like @samp{as(n)}. The @kbd{s l} command only works
23791on variables, but you can use the @kbd{a b} (@code{calc-substitute})
23792command to substitute actual values for function calls like @samp{as(3)}.
23793
23794The @kbd{s G} (@code{calc-edit-GenCount}) command is a convenient
23795way to create or edit this variable. Press @kbd{C-c C-c} to finish.
23796
23797If you have not stored a value in @code{GenCount}, or if the value
23798in that variable is not a positive integer, the regular
23799@code{s1}/@code{n1} notation is used.
23800
23801@kindex I a S
23802@kindex H I a S
23803@tindex finv
23804@tindex ffinv
23805With the Inverse flag, @kbd{I a S} [@code{finv}] treats the expression
23806on top of the stack as a function of the specified variable and solves
23807to find the inverse function, written in terms of the same variable.
23808For example, @kbd{I a S x} inverts @expr{2x + 6} to @expr{x/2 - 3}.
23809You can use both Inverse and Hyperbolic [@code{ffinv}] to obtain a
23810fully general inverse, as described above.
23811
23812@kindex a P
23813@pindex calc-poly-roots
23814@tindex roots
23815Some equations, specifically polynomials, have a known, finite number
23816of solutions. The @kbd{a P} (@code{calc-poly-roots}) [@code{roots}]
23817command uses @kbd{H a S} to solve an equation in general form, then, for
23818all arbitrary-sign variables like @code{s1}, and all arbitrary-integer
23819variables like @code{n1} for which @code{n1} only usefully varies over
23820a finite range, it expands these variables out to all their possible
23821values. The results are collected into a vector, which is returned.
23822For example, @samp{roots(x^4 = 1, x)} returns the four solutions
23823@samp{[1, -1, (0, 1), (0, -1)]}. Generally an @var{n}th degree
23824polynomial will always have @var{n} roots on the complex plane.
23825(If you have given a @code{real} declaration for the solution
23826variable, then only the real-valued solutions, if any, will be
23827reported; @pxref{Declarations}.)
23828
23829Note that because @kbd{a P} uses @kbd{H a S}, it is able to deliver
23830symbolic solutions if the polynomial has symbolic coefficients. Also
23831note that Calc's solver is not able to get exact symbolic solutions
23832to all polynomials. Polynomials containing powers up to @expr{x^4}
23833can always be solved exactly; polynomials of higher degree sometimes
23834can be: @expr{x^6 + x^3 + 1} is converted to @expr{(x^3)^2 + (x^3) + 1},
23835which can be solved for @expr{x^3} using the quadratic equation, and then
23836for @expr{x} by taking cube roots. But in many cases, like
23837@expr{x^6 + x + 1}, Calc does not know how to rewrite the polynomial
23838into a form it can solve. The @kbd{a P} command can still deliver a
23839list of numerical roots, however, provided that Symbolic mode (@kbd{m s})
23840is not turned on. (If you work with Symbolic mode on, recall that the
23841@kbd{N} (@code{calc-eval-num}) key is a handy way to reevaluate the
23842formula on the stack with Symbolic mode temporarily off.) Naturally,
23843@kbd{a P} can only provide numerical roots if the polynomial coefficients
23844are all numbers (real or complex).
23845
23846@node Solving Systems of Equations, Decomposing Polynomials, Multiple Solutions, Solving Equations
23847@subsection Solving Systems of Equations
23848
23849@noindent
23850@cindex Systems of equations, symbolic
23851You can also use the commands described above to solve systems of
23852simultaneous equations. Just create a vector of equations, then
23853specify a vector of variables for which to solve. (You can omit
23854the surrounding brackets when entering the vector of variables
23855at the prompt.)
23856
23857For example, putting @samp{[x + y = a, x - y = b]} on the stack
23858and typing @kbd{a S x,y @key{RET}} produces the vector of solutions
23859@samp{[x = a - (a-b)/2, y = (a-b)/2]}. The result vector will
23860have the same length as the variables vector, and the variables
23861will be listed in the same order there. Note that the solutions
23862are not always simplified as far as possible; the solution for
23863@expr{x} here could be improved by an application of the @kbd{a n}
23864command.
23865
23866Calc's algorithm works by trying to eliminate one variable at a
23867time by solving one of the equations for that variable and then
23868substituting into the other equations. Calc will try all the
23869possibilities, but you can speed things up by noting that Calc
23870first tries to eliminate the first variable with the first
23871equation, then the second variable with the second equation,
23872and so on. It also helps to put the simpler (e.g., more linear)
23873equations toward the front of the list. Calc's algorithm will
23874solve any system of linear equations, and also many kinds of
23875nonlinear systems.
23876
23877@ignore
23878@starindex
23879@end ignore
23880@tindex elim
23881Normally there will be as many variables as equations. If you
23882give fewer variables than equations (an ``over-determined'' system
23883of equations), Calc will find a partial solution. For example,
23884typing @kbd{a S y @key{RET}} with the above system of equations
23885would produce @samp{[y = a - x]}. There are now several ways to
23886express this solution in terms of the original variables; Calc uses
23887the first one that it finds. You can control the choice by adding
23888variable specifiers of the form @samp{elim(@var{v})} to the
23889variables list. This says that @var{v} should be eliminated from
23890the equations; the variable will not appear at all in the solution.
23891For example, typing @kbd{a S y,elim(x)} would yield
23892@samp{[y = a - (b+a)/2]}.
23893
23894If the variables list contains only @code{elim} specifiers,
23895Calc simply eliminates those variables from the equations
23896and then returns the resulting set of equations. For example,
23897@kbd{a S elim(x)} produces @samp{[a - 2 y = b]}. Every variable
23898eliminated will reduce the number of equations in the system
23899by one.
23900
23901Again, @kbd{a S} gives you one solution to the system of
23902equations. If there are several solutions, you can use @kbd{H a S}
23903to get a general family of solutions, or, if there is a finite
23904number of solutions, you can use @kbd{a P} to get a list. (In
23905the latter case, the result will take the form of a matrix where
23906the rows are different solutions and the columns correspond to the
23907variables you requested.)
23908
23909Another way to deal with certain kinds of overdetermined systems of
23910equations is the @kbd{a F} command, which does least-squares fitting
23911to satisfy the equations. @xref{Curve Fitting}.
23912
23913@node Decomposing Polynomials, , Solving Systems of Equations, Solving Equations
23914@subsection Decomposing Polynomials
23915
23916@noindent
23917@ignore
23918@starindex
23919@end ignore
23920@tindex poly
23921The @code{poly} function takes a polynomial and a variable as
23922arguments, and returns a vector of polynomial coefficients (constant
23923coefficient first). For example, @samp{poly(x^3 + 2 x, x)} returns
23924@expr{[0, 2, 0, 1]}. If the input is not a polynomial in @expr{x},
23925the call to @code{poly} is left in symbolic form. If the input does
23926not involve the variable @expr{x}, the input is returned in a list
23927of length one, representing a polynomial with only a constant
23928coefficient. The call @samp{poly(x, x)} returns the vector @expr{[0, 1]}.
23929The last element of the returned vector is guaranteed to be nonzero;
23930note that @samp{poly(0, x)} returns the empty vector @expr{[]}.
23931Note also that @expr{x} may actually be any formula; for example,
23932@samp{poly(sin(x)^2 - sin(x) + 3, sin(x))} returns @expr{[3, -1, 1]}.
23933
23934@cindex Coefficients of polynomial
23935@cindex Degree of polynomial
23936To get the @expr{x^k} coefficient of polynomial @expr{p}, use
23937@samp{poly(p, x)_(k+1)}. To get the degree of polynomial @expr{p},
23938use @samp{vlen(poly(p, x)) - 1}. For example, @samp{poly((x+1)^4, x)}
23939returns @samp{[1, 4, 6, 4, 1]}, so @samp{poly((x+1)^4, x)_(2+1)}
23940gives the @expr{x^2} coefficient of this polynomial, 6.
23941
23942@ignore
23943@starindex
23944@end ignore
23945@tindex gpoly
23946One important feature of the solver is its ability to recognize
23947formulas which are ``essentially'' polynomials. This ability is
23948made available to the user through the @code{gpoly} function, which
23949is used just like @code{poly}: @samp{gpoly(@var{expr}, @var{var})}.
23950If @var{expr} is a polynomial in some term which includes @var{var}, then
23951this function will return a vector @samp{[@var{x}, @var{c}, @var{a}]}
23952where @var{x} is the term that depends on @var{var}, @var{c} is a
23953vector of polynomial coefficients (like the one returned by @code{poly}),
23954and @var{a} is a multiplier which is usually 1. Basically,
23955@samp{@var{expr} = @var{a}*(@var{c}_1 + @var{c}_2 @var{x} +
23956@var{c}_3 @var{x}^2 + ...)}. The last element of @var{c} is
23957guaranteed to be non-zero, and @var{c} will not equal @samp{[1]}
23958(i.e., the trivial decomposition @var{expr} = @var{x} is not
23959considered a polynomial). One side effect is that @samp{gpoly(x, x)}
23960and @samp{gpoly(6, x)}, both of which might be expected to recognize
23961their arguments as polynomials, will not because the decomposition
23962is considered trivial.
23963
23964For example, @samp{gpoly((x-2)^2, x)} returns @samp{[x, [4, -4, 1], 1]},
23965since the expanded form of this polynomial is @expr{4 - 4 x + x^2}.
23966
23967The term @var{x} may itself be a polynomial in @var{var}. This is
23968done to reduce the size of the @var{c} vector. For example,
23969@samp{gpoly(x^4 + x^2 - 1, x)} returns @samp{[x^2, [-1, 1, 1], 1]},
23970since a quadratic polynomial in @expr{x^2} is easier to solve than
23971a quartic polynomial in @expr{x}.
23972
23973A few more examples of the kinds of polynomials @code{gpoly} can
23974discover:
23975
23976@smallexample
23977sin(x) - 1 [sin(x), [-1, 1], 1]
23978x + 1/x - 1 [x, [1, -1, 1], 1/x]
23979x + 1/x [x^2, [1, 1], 1/x]
23980x^3 + 2 x [x^2, [2, 1], x]
23981x + x^2:3 + sqrt(x) [x^1:6, [1, 1, 0, 1], x^1:2]
23982x^(2a) + 2 x^a + 5 [x^a, [5, 2, 1], 1]
23983(exp(-x) + exp(x)) / 2 [e^(2 x), [0.5, 0.5], e^-x]
23984@end smallexample
23985
23986The @code{poly} and @code{gpoly} functions accept a third integer argument
23987which specifies the largest degree of polynomial that is acceptable.
23988If this is @expr{n}, then only @var{c} vectors of length @expr{n+1}
23989or less will be returned. Otherwise, the @code{poly} or @code{gpoly}
23990call will remain in symbolic form. For example, the equation solver
23991can handle quartics and smaller polynomials, so it calls
23992@samp{gpoly(@var{expr}, @var{var}, 4)} to discover whether @var{expr}
23993can be treated by its linear, quadratic, cubic, or quartic formulas.
23994
23995@ignore
23996@starindex
23997@end ignore
23998@tindex pdeg
23999The @code{pdeg} function computes the degree of a polynomial;
24000@samp{pdeg(p,x)} is the highest power of @code{x} that appears in
24001@code{p}. This is the same as @samp{vlen(poly(p,x))-1}, but is
24002much more efficient. If @code{p} is constant with respect to @code{x},
24003then @samp{pdeg(p,x) = 0}. If @code{p} is not a polynomial in @code{x}
24004(e.g., @samp{pdeg(2 cos(x), x)}, the function remains unevaluated.
24005It is possible to omit the second argument @code{x}, in which case
24006@samp{pdeg(p)} returns the highest total degree of any term of the
24007polynomial, counting all variables that appear in @code{p}. Note
24008that @code{pdeg(c) = pdeg(c,x) = 0} for any nonzero constant @code{c};
24009the degree of the constant zero is considered to be @code{-inf}
24010(minus infinity).
24011
24012@ignore
24013@starindex
24014@end ignore
24015@tindex plead
24016The @code{plead} function finds the leading term of a polynomial.
24017Thus @samp{plead(p,x)} is equivalent to @samp{poly(p,x)_vlen(poly(p,x))},
24018though again more efficient. In particular, @samp{plead((2x+1)^10, x)}
24019returns 1024 without expanding out the list of coefficients. The
24020value of @code{plead(p,x)} will be zero only if @expr{p = 0}.
24021
24022@ignore
24023@starindex
24024@end ignore
24025@tindex pcont
24026The @code{pcont} function finds the @dfn{content} of a polynomial. This
24027is the greatest common divisor of all the coefficients of the polynomial.
24028With two arguments, @code{pcont(p,x)} effectively uses @samp{poly(p,x)}
24029to get a list of coefficients, then uses @code{pgcd} (the polynomial
24030GCD function) to combine these into an answer. For example,
24031@samp{pcont(4 x y^2 + 6 x^2 y, x)} is @samp{2 y}. The content is
24032basically the ``biggest'' polynomial that can be divided into @code{p}
24033exactly. The sign of the content is the same as the sign of the leading
24034coefficient.
24035
24036With only one argument, @samp{pcont(p)} computes the numerical
24037content of the polynomial, i.e., the @code{gcd} of the numerical
24038coefficients of all the terms in the formula. Note that @code{gcd}
24039is defined on rational numbers as well as integers; it computes
24040the @code{gcd} of the numerators and the @code{lcm} of the
24041denominators. Thus @samp{pcont(4:3 x y^2 + 6 x^2 y)} returns 2:3.
24042Dividing the polynomial by this number will clear all the
24043denominators, as well as dividing by any common content in the
24044numerators. The numerical content of a polynomial is negative only
24045if all the coefficients in the polynomial are negative.
24046
24047@ignore
24048@starindex
24049@end ignore
24050@tindex pprim
24051The @code{pprim} function finds the @dfn{primitive part} of a
24052polynomial, which is simply the polynomial divided (using @code{pdiv}
24053if necessary) by its content. If the input polynomial has rational
24054coefficients, the result will have integer coefficients in simplest
24055terms.
24056
24057@node Numerical Solutions, Curve Fitting, Solving Equations, Algebra
24058@section Numerical Solutions
24059
24060@noindent
24061Not all equations can be solved symbolically. The commands in this
24062section use numerical algorithms that can find a solution to a specific
24063instance of an equation to any desired accuracy. Note that the
24064numerical commands are slower than their algebraic cousins; it is a
24065good idea to try @kbd{a S} before resorting to these commands.
24066
24067(@xref{Curve Fitting}, for some other, more specialized, operations
24068on numerical data.)
24069
24070@menu
24071* Root Finding::
24072* Minimization::
24073* Numerical Systems of Equations::
24074@end menu
24075
24076@node Root Finding, Minimization, Numerical Solutions, Numerical Solutions
24077@subsection Root Finding
24078
24079@noindent
24080@kindex a R
24081@pindex calc-find-root
24082@tindex root
24083@cindex Newton's method
24084@cindex Roots of equations
24085@cindex Numerical root-finding
24086The @kbd{a R} (@code{calc-find-root}) [@code{root}] command finds a
24087numerical solution (or @dfn{root}) of an equation. (This command treats
24088inequalities the same as equations. If the input is any other kind
24089of formula, it is interpreted as an equation of the form @expr{X = 0}.)
24090
24091The @kbd{a R} command requires an initial guess on the top of the
24092stack, and a formula in the second-to-top position. It prompts for a
24093solution variable, which must appear in the formula. All other variables
24094that appear in the formula must have assigned values, i.e., when
24095a value is assigned to the solution variable and the formula is
24096evaluated with @kbd{=}, it should evaluate to a number. Any assigned
24097value for the solution variable itself is ignored and unaffected by
24098this command.
24099
24100When the command completes, the initial guess is replaced on the stack
24101by a vector of two numbers: The value of the solution variable that
24102solves the equation, and the difference between the lefthand and
24103righthand sides of the equation at that value. Ordinarily, the second
24104number will be zero or very nearly zero. (Note that Calc uses a
24105slightly higher precision while finding the root, and thus the second
24106number may be slightly different from the value you would compute from
24107the equation yourself.)
24108
24109The @kbd{v h} (@code{calc-head}) command is a handy way to extract
24110the first element of the result vector, discarding the error term.
24111
24112The initial guess can be a real number, in which case Calc searches
24113for a real solution near that number, or a complex number, in which
24114case Calc searches the whole complex plane near that number for a
24115solution, or it can be an interval form which restricts the search
24116to real numbers inside that interval.
24117
24118Calc tries to use @kbd{a d} to take the derivative of the equation.
24119If this succeeds, it uses Newton's method. If the equation is not
24120differentiable Calc uses a bisection method. (If Newton's method
24121appears to be going astray, Calc switches over to bisection if it
24122can, or otherwise gives up. In this case it may help to try again
24123with a slightly different initial guess.) If the initial guess is a
24124complex number, the function must be differentiable.
24125
24126If the formula (or the difference between the sides of an equation)
24127is negative at one end of the interval you specify and positive at
24128the other end, the root finder is guaranteed to find a root.
24129Otherwise, Calc subdivides the interval into small parts looking for
24130positive and negative values to bracket the root. When your guess is
24131an interval, Calc will not look outside that interval for a root.
24132
24133@kindex H a R
24134@tindex wroot
24135The @kbd{H a R} [@code{wroot}] command is similar to @kbd{a R}, except
24136that if the initial guess is an interval for which the function has
24137the same sign at both ends, then rather than subdividing the interval
24138Calc attempts to widen it to enclose a root. Use this mode if
24139you are not sure if the function has a root in your interval.
24140
24141If the function is not differentiable, and you give a simple number
24142instead of an interval as your initial guess, Calc uses this widening
24143process even if you did not type the Hyperbolic flag. (If the function
24144@emph{is} differentiable, Calc uses Newton's method which does not
24145require a bounding interval in order to work.)
24146
24147If Calc leaves the @code{root} or @code{wroot} function in symbolic
24148form on the stack, it will normally display an explanation for why
24149no root was found. If you miss this explanation, press @kbd{w}
24150(@code{calc-why}) to get it back.
24151
24152@node Minimization, Numerical Systems of Equations, Root Finding, Numerical Solutions
24153@subsection Minimization
24154
24155@noindent
24156@kindex a N
24157@kindex H a N
24158@kindex a X
24159@kindex H a X
24160@pindex calc-find-minimum
24161@pindex calc-find-maximum
24162@tindex minimize
24163@tindex maximize
24164@cindex Minimization, numerical
24165The @kbd{a N} (@code{calc-find-minimum}) [@code{minimize}] command
24166finds a minimum value for a formula. It is very similar in operation
24167to @kbd{a R} (@code{calc-find-root}): You give the formula and an initial
24168guess on the stack, and are prompted for the name of a variable. The guess
24169may be either a number near the desired minimum, or an interval enclosing
24170the desired minimum. The function returns a vector containing the
24171value of the variable which minimizes the formula's value, along
24172with the minimum value itself.
24173
24174Note that this command looks for a @emph{local} minimum. Many functions
40ba43b4 24175have more than one minimum; some, like
4009494e 24176@texline @math{x \sin x},
40ba43b4 24177@infoline @expr{x sin(x)},
4009494e 24178have infinitely many. In fact, there is no easy way to define the
40ba43b4 24179``global'' minimum of
4009494e 24180@texline @math{x \sin x}
40ba43b4 24181@infoline @expr{x sin(x)}
4009494e
GM
24182but Calc can still locate any particular local minimum
24183for you. Calc basically goes downhill from the initial guess until it
24184finds a point at which the function's value is greater both to the left
24185and to the right. Calc does not use derivatives when minimizing a function.
24186
24187If your initial guess is an interval and it looks like the minimum
24188occurs at one or the other endpoint of the interval, Calc will return
24189that endpoint only if that endpoint is closed; thus, minimizing @expr{17 x}
24190over @expr{[2..3]} will return @expr{[2, 38]}, but minimizing over
24191@expr{(2..3]} would report no minimum found. In general, you should
24192use closed intervals to find literally the minimum value in that
24193range of @expr{x}, or open intervals to find the local minimum, if
24194any, that happens to lie in that range.
24195
24196Most functions are smooth and flat near their minimum values. Because
24197of this flatness, if the current precision is, say, 12 digits, the
24198variable can only be determined meaningfully to about six digits. Thus
24199you should set the precision to twice as many digits as you need in your
24200answer.
24201
24202@ignore
24203@mindex wmin@idots
24204@end ignore
24205@tindex wminimize
24206@ignore
24207@mindex wmax@idots
24208@end ignore
24209@tindex wmaximize
24210The @kbd{H a N} [@code{wminimize}] command, analogously to @kbd{H a R},
24211expands the guess interval to enclose a minimum rather than requiring
24212that the minimum lie inside the interval you supply.
24213
24214The @kbd{a X} (@code{calc-find-maximum}) [@code{maximize}] and
24215@kbd{H a X} [@code{wmaximize}] commands effectively minimize the
24216negative of the formula you supply.
24217
24218The formula must evaluate to a real number at all points inside the
24219interval (or near the initial guess if the guess is a number). If
24220the initial guess is a complex number the variable will be minimized
24221over the complex numbers; if it is real or an interval it will
24222be minimized over the reals.
24223
24224@node Numerical Systems of Equations, , Minimization, Numerical Solutions
24225@subsection Systems of Equations
24226
24227@noindent
24228@cindex Systems of equations, numerical
24229The @kbd{a R} command can also solve systems of equations. In this
24230case, the equation should instead be a vector of equations, the
24231guess should instead be a vector of numbers (intervals are not
24232supported), and the variable should be a vector of variables. You
24233can omit the brackets while entering the list of variables. Each
24234equation must be differentiable by each variable for this mode to
24235work. The result will be a vector of two vectors: The variable
24236values that solved the system of equations, and the differences
24237between the sides of the equations with those variable values.
24238There must be the same number of equations as variables. Since
24239only plain numbers are allowed as guesses, the Hyperbolic flag has
24240no effect when solving a system of equations.
24241
24242It is also possible to minimize over many variables with @kbd{a N}
24243(or maximize with @kbd{a X}). Once again the variable name should
24244be replaced by a vector of variables, and the initial guess should
24245be an equal-sized vector of initial guesses. But, unlike the case of
24246multidimensional @kbd{a R}, the formula being minimized should
24247still be a single formula, @emph{not} a vector. Beware that
24248multidimensional minimization is currently @emph{very} slow.
24249
24250@node Curve Fitting, Summations, Numerical Solutions, Algebra
24251@section Curve Fitting
24252
24253@noindent
24254The @kbd{a F} command fits a set of data to a @dfn{model formula},
24255such as @expr{y = m x + b} where @expr{m} and @expr{b} are parameters
24256to be determined. For a typical set of measured data there will be
24257no single @expr{m} and @expr{b} that exactly fit the data; in this
24258case, Calc chooses values of the parameters that provide the closest
24259possible fit. The model formula can be entered in various ways after
40ba43b4 24260the key sequence @kbd{a F} is pressed.
4009494e
GM
24261
24262If the letter @kbd{P} is pressed after @kbd{a F} but before the model
24263description is entered, the data as well as the model formula will be
24264plotted after the formula is determined. This will be indicated by a
24265``P'' in the minibuffer after the help message.
24266
24267@menu
24268* Linear Fits::
24269* Polynomial and Multilinear Fits::
24270* Error Estimates for Fits::
24271* Standard Nonlinear Models::
24272* Curve Fitting Details::
24273* Interpolation::
24274@end menu
24275
24276@node Linear Fits, Polynomial and Multilinear Fits, Curve Fitting, Curve Fitting
24277@subsection Linear Fits
24278
24279@noindent
24280@kindex a F
24281@pindex calc-curve-fit
24282@tindex fit
24283@cindex Linear regression
24284@cindex Least-squares fits
24285The @kbd{a F} (@code{calc-curve-fit}) [@code{fit}] command attempts
24286to fit a set of data (@expr{x} and @expr{y} vectors of numbers) to a
24287straight line, polynomial, or other function of @expr{x}. For the
24288moment we will consider only the case of fitting to a line, and we
24289will ignore the issue of whether or not the model was in fact a good
24290fit for the data.
24291
24292In a standard linear least-squares fit, we have a set of @expr{(x,y)}
24293data points that we wish to fit to the model @expr{y = m x + b}
24294by adjusting the parameters @expr{m} and @expr{b} to make the @expr{y}
24295values calculated from the formula be as close as possible to the actual
24296@expr{y} values in the data set. (In a polynomial fit, the model is
24297instead, say, @expr{y = a x^3 + b x^2 + c x + d}. In a multilinear fit,
24298we have data points of the form @expr{(x_1,x_2,x_3,y)} and our model is
24299@expr{y = a x_1 + b x_2 + c x_3 + d}. These will be discussed later.)
24300
24301In the model formula, variables like @expr{x} and @expr{x_2} are called
24302the @dfn{independent variables}, and @expr{y} is the @dfn{dependent
24303variable}. Variables like @expr{m}, @expr{a}, and @expr{b} are called
24304the @dfn{parameters} of the model.
24305
24306The @kbd{a F} command takes the data set to be fitted from the stack.
24307By default, it expects the data in the form of a matrix. For example,
40ba43b4 24308for a linear or polynomial fit, this would be a
4009494e
GM
24309@texline @math{2\times N}
24310@infoline 2xN
24311matrix where the first row is a list of @expr{x} values and the second
24312row has the corresponding @expr{y} values. For the multilinear fit
24313shown above, the matrix would have four rows (@expr{x_1}, @expr{x_2},
24314@expr{x_3}, and @expr{y}, respectively).
24315
40ba43b4 24316If you happen to have an
4009494e
GM
24317@texline @math{N\times2}
24318@infoline Nx2
40ba43b4 24319matrix instead of a
4009494e
GM
24320@texline @math{2\times N}
24321@infoline 2xN
24322matrix, just press @kbd{v t} first to transpose the matrix.
24323
24324After you type @kbd{a F}, Calc prompts you to select a model. For a
24325linear fit, press the digit @kbd{1}.
24326
24327Calc then prompts for you to name the variables. By default it chooses
24328high letters like @expr{x} and @expr{y} for independent variables and
24329low letters like @expr{a} and @expr{b} for parameters. (The dependent
24330variable doesn't need a name.) The two kinds of variables are separated
24331by a semicolon. Since you generally care more about the names of the
24332independent variables than of the parameters, Calc also allows you to
24333name only those and let the parameters use default names.
24334
24335For example, suppose the data matrix
24336
24337@ifnottex
24338@example
24339@group
24340[ [ 1, 2, 3, 4, 5 ]
24341 [ 5, 7, 9, 11, 13 ] ]
24342@end group
24343@end example
24344@end ifnottex
24345@tex
4009494e
GM
24346\beforedisplay
24347$$ \pmatrix{ 1 & 2 & 3 & 4 & 5 \cr
24348 5 & 7 & 9 & 11 & 13 }
24349$$
24350\afterdisplay
24351@end tex
24352
24353@noindent
24354is on the stack and we wish to do a simple linear fit. Type
24355@kbd{a F}, then @kbd{1} for the model, then @key{RET} to use
24356the default names. The result will be the formula @expr{3. + 2. x}
24357on the stack. Calc has created the model expression @kbd{a + b x},
24358then found the optimal values of @expr{a} and @expr{b} to fit the
24359data. (In this case, it was able to find an exact fit.) Calc then
24360substituted those values for @expr{a} and @expr{b} in the model
24361formula.
24362
24363The @kbd{a F} command puts two entries in the trail. One is, as
24364always, a copy of the result that went to the stack; the other is
24365a vector of the actual parameter values, written as equations:
24366@expr{[a = 3, b = 2]}, in case you'd rather read them in a list
24367than pick them out of the formula. (You can type @kbd{t y}
24368to move this vector to the stack; see @ref{Trail Commands}.
24369
24370Specifying a different independent variable name will affect the
24371resulting formula: @kbd{a F 1 k @key{RET}} produces @kbd{3 + 2 k}.
24372Changing the parameter names (say, @kbd{a F 1 k;b,m @key{RET}}) will affect
24373the equations that go into the trail.
24374
24375@tex
24376\bigskip
24377@end tex
24378
24379To see what happens when the fit is not exact, we could change
24380the number 13 in the data matrix to 14 and try the fit again.
24381The result is:
24382
24383@example
243842.6 + 2.2 x
24385@end example
24386
24387Evaluating this formula, say with @kbd{v x 5 @key{RET} @key{TAB} V M $ @key{RET}}, shows
24388a reasonably close match to the y-values in the data.
24389
24390@example
24391[4.8, 7., 9.2, 11.4, 13.6]
24392@end example
24393
24394Since there is no line which passes through all the @var{n} data points,
24395Calc has chosen a line that best approximates the data points using
24396the method of least squares. The idea is to define the @dfn{chi-square}
24397error measure
24398
24399@ifnottex
24400@example
24401chi^2 = sum((y_i - (a + b x_i))^2, i, 1, N)
24402@end example
24403@end ifnottex
24404@tex
4009494e
GM
24405\beforedisplay
24406$$ \chi^2 = \sum_{i=1}^N (y_i - (a + b x_i))^2 $$
24407\afterdisplay
24408@end tex
24409
24410@noindent
24411which is clearly zero if @expr{a + b x} exactly fits all data points,
24412and increases as various @expr{a + b x_i} values fail to match the
24413corresponding @expr{y_i} values. There are several reasons why the
40ba43b4 24414summand is squared, one of them being to ensure that
4009494e
GM
24415@texline @math{\chi^2 \ge 0}.
24416@infoline @expr{chi^2 >= 0}.
24417Least-squares fitting simply chooses the values of @expr{a} and @expr{b}
40ba43b4 24418for which the error
4009494e 24419@texline @math{\chi^2}
40ba43b4 24420@infoline @expr{chi^2}
4009494e
GM
24421is as small as possible.
24422
24423Other kinds of models do the same thing but with a different model
24424formula in place of @expr{a + b x_i}.
24425
24426@tex
24427\bigskip
24428@end tex
24429
24430A numeric prefix argument causes the @kbd{a F} command to take the
24431data in some other form than one big matrix. A positive argument @var{n}
24432will take @var{N} items from the stack, corresponding to the @var{n} rows
24433of a data matrix. In the linear case, @var{n} must be 2 since there
24434is always one independent variable and one dependent variable.
24435
24436A prefix of zero or plain @kbd{C-u} is a compromise; Calc takes two
24437items from the stack, an @var{n}-row matrix of @expr{x} values, and a
24438vector of @expr{y} values. If there is only one independent variable,
24439the @expr{x} values can be either a one-row matrix or a plain vector,
24440in which case the @kbd{C-u} prefix is the same as a @w{@kbd{C-u 2}} prefix.
24441
24442@node Polynomial and Multilinear Fits, Error Estimates for Fits, Linear Fits, Curve Fitting
24443@subsection Polynomial and Multilinear Fits
24444
24445@noindent
24446To fit the data to higher-order polynomials, just type one of the
24447digits @kbd{2} through @kbd{9} when prompted for a model. For example,
24448we could fit the original data matrix from the previous section
24449(with 13, not 14) to a parabola instead of a line by typing
24450@kbd{a F 2 @key{RET}}.
24451
24452@example
244532.00000000001 x - 1.5e-12 x^2 + 2.99999999999
24454@end example
24455
24456Note that since the constant and linear terms are enough to fit the
24457data exactly, it's no surprise that Calc chose a tiny contribution
24458for @expr{x^2}. (The fact that it's not exactly zero is due only
24459to roundoff error. Since our data are exact integers, we could get
24460an exact answer by typing @kbd{m f} first to get Fraction mode.
24461Then the @expr{x^2} term would vanish altogether. Usually, though,
24462the data being fitted will be approximate floats so Fraction mode
24463won't help.)
24464
24465Doing the @kbd{a F 2} fit on the data set with 14 instead of 13
24466gives a much larger @expr{x^2} contribution, as Calc bends the
24467line slightly to improve the fit.
24468
24469@example
244700.142857142855 x^2 + 1.34285714287 x + 3.59999999998
24471@end example
24472
24473An important result from the theory of polynomial fitting is that it
24474is always possible to fit @var{n} data points exactly using a polynomial
24475of degree @mathit{@var{n}-1}, sometimes called an @dfn{interpolating polynomial}.
24476Using the modified (14) data matrix, a model number of 4 gives
24477a polynomial that exactly matches all five data points:
24478
24479@example
244800.04167 x^4 - 0.4167 x^3 + 1.458 x^2 - 0.08333 x + 4.
24481@end example
24482
24483The actual coefficients we get with a precision of 12, like
24484@expr{0.0416666663588}, clearly suffer from loss of precision.
24485It is a good idea to increase the working precision to several
24486digits beyond what you need when you do a fitting operation.
24487Or, if your data are exact, use Fraction mode to get exact
24488results.
24489
24490You can type @kbd{i} instead of a digit at the model prompt to fit
24491the data exactly to a polynomial. This just counts the number of
24492columns of the data matrix to choose the degree of the polynomial
24493automatically.
24494
24495Fitting data ``exactly'' to high-degree polynomials is not always
24496a good idea, though. High-degree polynomials have a tendency to
24497wiggle uncontrollably in between the fitting data points. Also,
24498if the exact-fit polynomial is going to be used to interpolate or
24499extrapolate the data, it is numerically better to use the @kbd{a p}
24500command described below. @xref{Interpolation}.
24501
24502@tex
24503\bigskip
24504@end tex
24505
24506Another generalization of the linear model is to assume the
24507@expr{y} values are a sum of linear contributions from several
24508@expr{x} values. This is a @dfn{multilinear} fit, and it is also
24509selected by the @kbd{1} digit key. (Calc decides whether the fit
24510is linear or multilinear by counting the rows in the data matrix.)
24511
24512Given the data matrix,
24513
24514@example
24515@group
24516[ [ 1, 2, 3, 4, 5 ]
24517 [ 7, 2, 3, 5, 2 ]
24518 [ 14.5, 15, 18.5, 22.5, 24 ] ]
24519@end group
24520@end example
24521
24522@noindent
24523the command @kbd{a F 1 @key{RET}} will call the first row @expr{x} and the
24524second row @expr{y}, and will fit the values in the third row to the
24525model @expr{a + b x + c y}.
24526
24527@example
245288. + 3. x + 0.5 y
24529@end example
24530
24531Calc can do multilinear fits with any number of independent variables
24532(i.e., with any number of data rows).
24533
24534@tex
24535\bigskip
24536@end tex
24537
24538Yet another variation is @dfn{homogeneous} linear models, in which
24539the constant term is known to be zero. In the linear case, this
24540means the model formula is simply @expr{a x}; in the multilinear
24541case, the model might be @expr{a x + b y + c z}; and in the polynomial
24542case, the model could be @expr{a x + b x^2 + c x^3}. You can get
24543a homogeneous linear or multilinear model by pressing the letter
24544@kbd{h} followed by a regular model key, like @kbd{1} or @kbd{2}.
24545This will be indicated by an ``h'' in the minibuffer after the help
24546message.
24547
24548It is certainly possible to have other constrained linear models,
24549like @expr{2.3 + a x} or @expr{a - 4 x}. While there is no single
24550key to select models like these, a later section shows how to enter
24551any desired model by hand. In the first case, for example, you
24552would enter @kbd{a F ' 2.3 + a x}.
24553
24554Another class of models that will work but must be entered by hand
24555are multinomial fits, e.g., @expr{a + b x + c y + d x^2 + e y^2 + f x y}.
24556
24557@node Error Estimates for Fits, Standard Nonlinear Models, Polynomial and Multilinear Fits, Curve Fitting
24558@subsection Error Estimates for Fits
24559
24560@noindent
24561@kindex H a F
24562@tindex efit
24563With the Hyperbolic flag, @kbd{H a F} [@code{efit}] performs the same
24564fitting operation as @kbd{a F}, but reports the coefficients as error
24565forms instead of plain numbers. Fitting our two data matrices (first
24566with 13, then with 14) to a line with @kbd{H a F} gives the results,
24567
24568@example
245693. + 2. x
245702.6 +/- 0.382970843103 + 2.2 +/- 0.115470053838 x
24571@end example
24572
24573In the first case the estimated errors are zero because the linear
24574fit is perfect. In the second case, the errors are nonzero but
24575moderately small, because the data are still very close to linear.
24576
24577It is also possible for the @emph{input} to a fitting operation to
24578contain error forms. The data values must either all include errors
24579or all be plain numbers. Error forms can go anywhere but generally
24580go on the numbers in the last row of the data matrix. If the last
24581row contains error forms
40ba43b4
PE
24582@texline `@var{y_i}@w{ @tfn{+/-} }@math{\sigma_i}',
24583@infoline `@var{y_i}@w{ @tfn{+/-} }@var{sigma_i}',
24584then the
4009494e
GM
24585@texline @math{\chi^2}
24586@infoline @expr{chi^2}
24587statistic is now,
24588
24589@ifnottex
24590@example
24591chi^2 = sum(((y_i - (a + b x_i)) / sigma_i)^2, i, 1, N)
24592@end example
24593@end ifnottex
24594@tex
4009494e
GM
24595\beforedisplay
24596$$ \chi^2 = \sum_{i=1}^N \left(y_i - (a + b x_i) \over \sigma_i\right)^2 $$
24597\afterdisplay
24598@end tex
24599
24600@noindent
24601so that data points with larger error estimates contribute less to
24602the fitting operation.
24603
24604If there are error forms on other rows of the data matrix, all the
24605errors for a given data point are combined; the square root of the
40ba43b4 24606sum of the squares of the errors forms the
4009494e 24607@texline @math{\sigma_i}
40ba43b4 24608@infoline @expr{sigma_i}
4009494e
GM
24609used for the data point.
24610
24611Both @kbd{a F} and @kbd{H a F} can accept error forms in the input
24612matrix, although if you are concerned about error analysis you will
24613probably use @kbd{H a F} so that the output also contains error
24614estimates.
24615
40ba43b4 24616If the input contains error forms but all the
4009494e 24617@texline @math{\sigma_i}
40ba43b4 24618@infoline @expr{sigma_i}
4009494e 24619values are the same, it is easy to see that the resulting fitted model
40ba43b4 24620will be the same as if the input did not have error forms at all
4009494e
GM
24621@texline (@math{\chi^2}
24622@infoline (@expr{chi^2}
40ba43b4 24623is simply scaled uniformly by
4009494e 24624@texline @math{1 / \sigma^2},
40ba43b4 24625@infoline @expr{1 / sigma^2},
4009494e
GM
24626which doesn't affect where it has a minimum). But there @emph{will} be
24627a difference in the estimated errors of the coefficients reported by
40ba43b4 24628@kbd{H a F}.
4009494e
GM
24629
24630Consult any text on statistical modeling of data for a discussion
24631of where these error estimates come from and how they should be
24632interpreted.
24633
24634@tex
24635\bigskip
24636@end tex
24637
24638@kindex I a F
24639@tindex xfit
24640With the Inverse flag, @kbd{I a F} [@code{xfit}] produces even more
24641information. The result is a vector of six items:
24642
24643@enumerate
24644@item
24645The model formula with error forms for its coefficients or
24646parameters. This is the result that @kbd{H a F} would have
24647produced.
24648
24649@item
24650A vector of ``raw'' parameter values for the model. These are the
24651polynomial coefficients or other parameters as plain numbers, in the
24652same order as the parameters appeared in the final prompt of the
24653@kbd{I a F} command. For polynomials of degree @expr{d}, this vector
24654will have length @expr{M = d+1} with the constant term first.
24655
24656@item
24657The covariance matrix @expr{C} computed from the fit. This is
24658an @var{m}x@var{m} symmetric matrix; the diagonal elements
24659@texline @math{C_{jj}}
40ba43b4
PE
24660@infoline @expr{C_j_j}
24661are the variances
4009494e 24662@texline @math{\sigma_j^2}
40ba43b4 24663@infoline @expr{sigma_j^2}
4009494e 24664of the parameters. The other elements are covariances
40ba43b4
PE
24665@texline @math{\sigma_{ij}^2}
24666@infoline @expr{sigma_i_j^2}
4009494e 24667that describe the correlation between pairs of parameters. (A related
40ba43b4 24668set of numbers, the @dfn{linear correlation coefficients}
4009494e
GM
24669@texline @math{r_{ij}},
24670@infoline @expr{r_i_j},
40ba43b4 24671are defined as
4009494e
GM
24672@texline @math{\sigma_{ij}^2 / \sigma_i \, \sigma_j}.)
24673@infoline @expr{sigma_i_j^2 / sigma_i sigma_j}.)
24674
24675@item
24676A vector of @expr{M} ``parameter filter'' functions whose
24677meanings are described below. If no filters are necessary this
24678will instead be an empty vector; this is always the case for the
24679polynomial and multilinear fits described so far.
24680
24681@item
40ba43b4 24682The value of
4009494e 24683@texline @math{\chi^2}
40ba43b4 24684@infoline @expr{chi^2}
4009494e
GM
24685for the fit, calculated by the formulas shown above. This gives a
24686measure of the quality of the fit; statisticians consider
24687@texline @math{\chi^2 \approx N - M}
40ba43b4 24688@infoline @expr{chi^2 = N - M}
4009494e
GM
24689to indicate a moderately good fit (where again @expr{N} is the number of
24690data points and @expr{M} is the number of parameters).
24691
24692@item
24693A measure of goodness of fit expressed as a probability @expr{Q}.
24694This is computed from the @code{utpc} probability distribution
40ba43b4 24695function using
4009494e 24696@texline @math{\chi^2}
40ba43b4 24697@infoline @expr{chi^2}
4009494e
GM
24698with @expr{N - M} degrees of freedom. A
24699value of 0.5 implies a good fit; some texts recommend that often
24700@expr{Q = 0.1} or even 0.001 can signify an acceptable fit. In
40ba43b4 24701particular,
4009494e 24702@texline @math{\chi^2}
40ba43b4 24703@infoline @expr{chi^2}
4009494e
GM
24704statistics assume the errors in your inputs
24705follow a normal (Gaussian) distribution; if they don't, you may
24706have to accept smaller values of @expr{Q}.
24707
24708The @expr{Q} value is computed only if the input included error
24709estimates. Otherwise, Calc will report the symbol @code{nan}
40ba43b4 24710for @expr{Q}. The reason is that in this case the
4009494e
GM
24711@texline @math{\chi^2}
24712@infoline @expr{chi^2}
24713value has effectively been used to estimate the original errors
24714in the input, and thus there is no redundant information left
24715over to use for a confidence test.
24716@end enumerate
24717
24718@node Standard Nonlinear Models, Curve Fitting Details, Error Estimates for Fits, Curve Fitting
24719@subsection Standard Nonlinear Models
24720
24721@noindent
24722The @kbd{a F} command also accepts other kinds of models besides
24723lines and polynomials. Some common models have quick single-key
24724abbreviations; others must be entered by hand as algebraic formulas.
24725
24726Here is a complete list of the standard models recognized by @kbd{a F}:
24727
24728@table @kbd
24729@item 1
24730Linear or multilinear. @mathit{a + b x + c y + d z}.
24731@item 2-9
24732Polynomials. @mathit{a + b x + c x^2 + d x^3}.
24733@item e
24734Exponential. @mathit{a} @tfn{exp}@mathit{(b x)} @tfn{exp}@mathit{(c y)}.
24735@item E
24736Base-10 exponential. @mathit{a} @tfn{10^}@mathit{(b x)} @tfn{10^}@mathit{(c y)}.
24737@item x
24738Exponential (alternate notation). @tfn{exp}@mathit{(a + b x + c y)}.
24739@item X
24740Base-10 exponential (alternate). @tfn{10^}@mathit{(a + b x + c y)}.
24741@item l
24742Logarithmic. @mathit{a + b} @tfn{ln}@mathit{(x) + c} @tfn{ln}@mathit{(y)}.
24743@item L
24744Base-10 logarithmic. @mathit{a + b} @tfn{log10}@mathit{(x) + c} @tfn{log10}@mathit{(y)}.
24745@item ^
24746General exponential. @mathit{a b^x c^y}.
24747@item p
24748Power law. @mathit{a x^b y^c}.
24749@item q
24750Quadratic. @mathit{a + b (x-c)^2 + d (x-e)^2}.
24751@item g
40ba43b4 24752Gaussian.
4009494e
GM
24753@texline @math{{a \over b \sqrt{2 \pi}} \exp\left( -{1 \over 2} \left( x - c \over b \right)^2 \right)}.
24754@infoline @mathit{(a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)}.
24755@item s
24756Logistic @emph{s} curve.
24757@texline @math{a/(1+e^{b(x-c)})}.
24758@infoline @mathit{a/(1 + exp(b (x - c)))}.
24759@item b
24760Logistic bell curve.
24761@texline @math{ae^{b(x-c)}/(1+e^{b(x-c)})^2}.
24762@infoline @mathit{a exp(b (x - c))/(1 + exp(b (x - c)))^2}.
24763@item o
24764Hubbert linearization.
24765@texline @math{{y \over x} = a(1-x/b)}.
24766@infoline @mathit{(y/x) = a (1 - x/b)}.
24767@end table
24768
24769All of these models are used in the usual way; just press the appropriate
24770letter at the model prompt, and choose variable names if you wish. The
24771result will be a formula as shown in the above table, with the best-fit
24772values of the parameters substituted. (You may find it easier to read
24773the parameter values from the vector that is placed in the trail.)
24774
24775All models except Gaussian, logistics, Hubbert and polynomials can
24776generalize as shown to any number of independent variables. Also, all
40ba43b4 24777the built-in models except for the logistic and Hubbert curves have an
4009494e
GM
24778additive or multiplicative parameter shown as @expr{a} in the above table
24779which can be replaced by zero or one, as appropriate, by typing @kbd{h}
24780before the model key.
24781
24782Note that many of these models are essentially equivalent, but express
24783the parameters slightly differently. For example, @expr{a b^x} and
24784the other two exponential models are all algebraic rearrangements of
24785each other. Also, the ``quadratic'' model is just a degree-2 polynomial
24786with the parameters expressed differently. Use whichever form best
24787matches the problem.
24788
24789The HP-28/48 calculators support four different models for curve
24790fitting, called @code{LIN}, @code{LOG}, @code{EXP}, and @code{PWR}.
24791These correspond to Calc models @samp{a + b x}, @samp{a + b ln(x)},
24792@samp{a exp(b x)}, and @samp{a x^b}, respectively. In each case,
24793@expr{a} is what the HP-48 identifies as the ``intercept,'' and
24794@expr{b} is what it calls the ``slope.''
24795
24796@tex
24797\bigskip
24798@end tex
24799
24800If the model you want doesn't appear on this list, press @kbd{'}
24801(the apostrophe key) at the model prompt to enter any algebraic
24802formula, such as @kbd{m x - b}, as the model. (Not all models
24803will work, though---see the next section for details.)
24804
24805The model can also be an equation like @expr{y = m x + b}.
24806In this case, Calc thinks of all the rows of the data matrix on
24807equal terms; this model effectively has two parameters
24808(@expr{m} and @expr{b}) and two independent variables (@expr{x}
24809and @expr{y}), with no ``dependent'' variables. Model equations
24810do not need to take this @expr{y =} form. For example, the
24811implicit line equation @expr{a x + b y = 1} works fine as a
24812model.
24813
24814When you enter a model, Calc makes an alphabetical list of all
24815the variables that appear in the model. These are used for the
24816default parameters, independent variables, and dependent variable
24817(in that order). If you enter a plain formula (not an equation),
24818Calc assumes the dependent variable does not appear in the formula
24819and thus does not need a name.
24820
24821For example, if the model formula has the variables @expr{a,mu,sigma,t,x},
24822and the data matrix has three rows (meaning two independent variables),
24823Calc will use @expr{a,mu,sigma} as the default parameters, and the
24824data rows will be named @expr{t} and @expr{x}, respectively. If you
24825enter an equation instead of a plain formula, Calc will use @expr{a,mu}
24826as the parameters, and @expr{sigma,t,x} as the three independent
24827variables.
24828
24829You can, of course, override these choices by entering something
24830different at the prompt. If you leave some variables out of the list,
24831those variables must have stored values and those stored values will
24832be used as constants in the model. (Stored values for the parameters
24833and independent variables are ignored by the @kbd{a F} command.)
24834If you list only independent variables, all the remaining variables
24835in the model formula will become parameters.
24836
24837If there are @kbd{$} signs in the model you type, they will stand
24838for parameters and all other variables (in alphabetical order)
24839will be independent. Use @kbd{$} for one parameter, @kbd{$$} for
24840another, and so on. Thus @kbd{$ x + $$} is another way to describe
24841a linear model.
24842
24843If you type a @kbd{$} instead of @kbd{'} at the model prompt itself,
24844Calc will take the model formula from the stack. (The data must then
24845appear at the second stack level.) The same conventions are used to
24846choose which variables in the formula are independent by default and
24847which are parameters.
24848
24849Models taken from the stack can also be expressed as vectors of
24850two or three elements, @expr{[@var{model}, @var{vars}]} or
24851@expr{[@var{model}, @var{vars}, @var{params}]}. Each of @var{vars}
24852and @var{params} may be either a variable or a vector of variables.
24853(If @var{params} is omitted, all variables in @var{model} except
24854those listed as @var{vars} are parameters.)
24855
24856When you enter a model manually with @kbd{'}, Calc puts a 3-vector
24857describing the model in the trail so you can get it back if you wish.
24858
24859@tex
24860\bigskip
24861@end tex
24862
24863@vindex Model1
24864@vindex Model2
24865Finally, you can store a model in one of the Calc variables
24866@code{Model1} or @code{Model2}, then use this model by typing
24867@kbd{a F u} or @kbd{a F U} (respectively). The value stored in
24868the variable can be any of the formats that @kbd{a F $} would
24869accept for a model on the stack.
24870
24871@tex
24872\bigskip
24873@end tex
24874
24875Calc uses the principal values of inverse functions like @code{ln}
24876and @code{arcsin} when doing fits. For example, when you enter
24877the model @samp{y = sin(a t + b)} Calc actually uses the easier
24878form @samp{arcsin(y) = a t + b}. The @code{arcsin} function always
24879returns results in the range from @mathit{-90} to 90 degrees (or the
24880equivalent range in radians). Suppose you had data that you
24881believed to represent roughly three oscillations of a sine wave,
40ba43b4 24882so that the argument of the sine might go from zero to
4009494e 24883@texline @math{3\times360}
40ba43b4 24884@infoline @mathit{3*360}
4009494e
GM
24885degrees.
24886The above model would appear to be a good way to determine the
24887true frequency and phase of the sine wave, but in practice it
24888would fail utterly. The righthand side of the actual model
24889@samp{arcsin(y) = a t + b} will grow smoothly with @expr{t}, but
24890the lefthand side will bounce back and forth between @mathit{-90} and 90.
24891No values of @expr{a} and @expr{b} can make the two sides match,
24892even approximately.
24893
24894There is no good solution to this problem at present. You could
24895restrict your data to small enough ranges so that the above problem
24896doesn't occur (i.e., not straddling any peaks in the sine wave).
24897Or, in this case, you could use a totally different method such as
24898Fourier analysis, which is beyond the scope of the @kbd{a F} command.
24899(Unfortunately, Calc does not currently have any facilities for
24900taking Fourier and related transforms.)
24901
24902@node Curve Fitting Details, Interpolation, Standard Nonlinear Models, Curve Fitting
24903@subsection Curve Fitting Details
24904
24905@noindent
24906Calc's internal least-squares fitter can only handle multilinear
24907models. More precisely, it can handle any model of the form
24908@expr{a f(x,y,z) + b g(x,y,z) + c h(x,y,z)}, where @expr{a,b,c}
24909are the parameters and @expr{x,y,z} are the independent variables
24910(of course there can be any number of each, not just three).
24911
24912In a simple multilinear or polynomial fit, it is easy to see how
24913to convert the model into this form. For example, if the model
24914is @expr{a + b x + c x^2}, then @expr{f(x) = 1}, @expr{g(x) = x},
24915and @expr{h(x) = x^2} are suitable functions.
24916
24917For most other models, Calc uses a variety of algebraic manipulations
24918to try to put the problem into the form
24919
24920@smallexample
24921Y(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)
24922@end smallexample
24923
24924@noindent
24925where @expr{Y,A,B,C,F,G,H} are arbitrary functions. It computes
24926@expr{Y}, @expr{F}, @expr{G}, and @expr{H} for all the data points,
24927does a standard linear fit to find the values of @expr{A}, @expr{B},
24928and @expr{C}, then uses the equation solver to solve for @expr{a,b,c}
24929in terms of @expr{A,B,C}.
24930
24931A remarkable number of models can be cast into this general form.
24932We'll look at two examples here to see how it works. The power-law
24933model @expr{y = a x^b} with two independent variables and two parameters
24934can be rewritten as follows:
24935
24936@example
24937y = a x^b
24938y = a exp(b ln(x))
24939y = exp(ln(a) + b ln(x))
24940ln(y) = ln(a) + b ln(x)
24941@end example
24942
24943@noindent
40ba43b4 24944which matches the desired form with
4009494e 24945@texline @math{Y = \ln(y)},
40ba43b4 24946@infoline @expr{Y = ln(y)},
4009494e
GM
24947@texline @math{A = \ln(a)},
24948@infoline @expr{A = ln(a)},
40ba43b4 24949@expr{F = 1}, @expr{B = b}, and
4009494e 24950@texline @math{G = \ln(x)}.
40ba43b4 24951@infoline @expr{G = ln(x)}.
4009494e 24952Calc thus computes the logarithms of your @expr{y} and @expr{x} values,
40ba43b4
PE
24953does a linear fit for @expr{A} and @expr{B}, then solves to get
24954@texline @math{a = \exp(A)}
24955@infoline @expr{a = exp(A)}
4009494e
GM
24956and @expr{b = B}.
24957
24958Another interesting example is the ``quadratic'' model, which can
24959be handled by expanding according to the distributive law.
24960
24961@example
24962y = a + b*(x - c)^2
24963y = a + b c^2 - 2 b c x + b x^2
24964@end example
24965
24966@noindent
24967which matches with @expr{Y = y}, @expr{A = a + b c^2}, @expr{F = 1},
24968@expr{B = -2 b c}, @expr{G = x} (the @mathit{-2} factor could just as easily
24969have been put into @expr{G} instead of @expr{B}), @expr{C = b}, and
24970@expr{H = x^2}.
24971
24972The Gaussian model looks quite complicated, but a closer examination
24973shows that it's actually similar to the quadratic model but with an
24974exponential that can be brought to the top and moved into @expr{Y}.
24975
24976The logistic models cannot be put into general linear form. For these
24977models, and the Hubbert linearization, Calc computes a rough
24978approximation for the parameters, then uses the Levenberg-Marquardt
24979iterative method to refine the approximations.
24980
24981Another model that cannot be put into general linear
24982form is a Gaussian with a constant background added on, i.e.,
24983@expr{d} + the regular Gaussian formula. If you have a model like
24984this, your best bet is to replace enough of your parameters with
24985constants to make the model linearizable, then adjust the constants
24986manually by doing a series of fits. You can compare the fits by
24987graphing them, by examining the goodness-of-fit measures returned by
24988@kbd{I a F}, or by some other method suitable to your application.
24989Note that some models can be linearized in several ways. The
24990Gaussian-plus-@var{d} model can be linearized by setting @expr{d}
24991(the background) to a constant, or by setting @expr{b} (the standard
24992deviation) and @expr{c} (the mean) to constants.
24993
24994To fit a model with constants substituted for some parameters, just
24995store suitable values in those parameter variables, then omit them
24996from the list of parameters when you answer the variables prompt.
24997
24998@tex
24999\bigskip
25000@end tex
25001
25002A last desperate step would be to use the general-purpose
25003@code{minimize} function rather than @code{fit}. After all, both
40ba43b4 25004functions solve the problem of minimizing an expression (the
4009494e
GM
25005@texline @math{\chi^2}
25006@infoline @expr{chi^2}
25007sum) by adjusting certain parameters in the expression. The @kbd{a F}
25008command is able to use a vastly more efficient algorithm due to its
25009special knowledge about linear chi-square sums, but the @kbd{a N}
25010command can do the same thing by brute force.
25011
25012A compromise would be to pick out a few parameters without which the
25013fit is linearizable, and use @code{minimize} on a call to @code{fit}
25014which efficiently takes care of the rest of the parameters. The thing
40ba43b4 25015to be minimized would be the value of
4009494e 25016@texline @math{\chi^2}
40ba43b4 25017@infoline @expr{chi^2}
4009494e
GM
25018returned as the fifth result of the @code{xfit} function:
25019
25020@smallexample
25021minimize(xfit(gaus(a,b,c,d,x), x, [a,b,c], data)_5, d, guess)
25022@end smallexample
25023
25024@noindent
25025where @code{gaus} represents the Gaussian model with background,
25026@code{data} represents the data matrix, and @code{guess} represents
25027the initial guess for @expr{d} that @code{minimize} requires.
25028This operation will only be, shall we say, extraordinarily slow
25029rather than astronomically slow (as would be the case if @code{minimize}
25030were used by itself to solve the problem).
25031
25032@tex
25033\bigskip
25034@end tex
25035
25036The @kbd{I a F} [@code{xfit}] command is somewhat trickier when
25037nonlinear models are used. The second item in the result is the
25038vector of ``raw'' parameters @expr{A}, @expr{B}, @expr{C}. The
25039covariance matrix is written in terms of those raw parameters.
25040The fifth item is a vector of @dfn{filter} expressions. This
25041is the empty vector @samp{[]} if the raw parameters were the same
25042as the requested parameters, i.e., if @expr{A = a}, @expr{B = b},
25043and so on (which is always true if the model is already linear
25044in the parameters as written, e.g., for polynomial fits). If the
25045parameters had to be rearranged, the fifth item is instead a vector
25046of one formula per parameter in the original model. The raw
25047parameters are expressed in these ``filter'' formulas as
25048@samp{fitdummy(1)} for @expr{A}, @samp{fitdummy(2)} for @expr{B},
25049and so on.
25050
25051When Calc needs to modify the model to return the result, it replaces
25052@samp{fitdummy(1)} in all the filters with the first item in the raw
25053parameters list, and so on for the other raw parameters, then
25054evaluates the resulting filter formulas to get the actual parameter
25055values to be substituted into the original model. In the case of
25056@kbd{H a F} and @kbd{I a F} where the parameters must be error forms,
25057Calc uses the square roots of the diagonal entries of the covariance
25058matrix as error values for the raw parameters, then lets Calc's
25059standard error-form arithmetic take it from there.
25060
25061If you use @kbd{I a F} with a nonlinear model, be sure to remember
25062that the covariance matrix is in terms of the raw parameters,
25063@emph{not} the actual requested parameters. It's up to you to
25064figure out how to interpret the covariances in the presence of
25065nontrivial filter functions.
25066
25067Things are also complicated when the input contains error forms.
25068Suppose there are three independent and dependent variables, @expr{x},
25069@expr{y}, and @expr{z}, one or more of which are error forms in the
25070data. Calc combines all the error values by taking the square root
25071of the sum of the squares of the errors. It then changes @expr{x}
25072and @expr{y} to be plain numbers, and makes @expr{z} into an error
25073form with this combined error. The @expr{Y(x,y,z)} part of the
25074linearized model is evaluated, and the result should be an error
40ba43b4 25075form. The error part of that result is used for
4009494e 25076@texline @math{\sigma_i}
40ba43b4
PE
25077@infoline @expr{sigma_i}
25078for the data point. If for some reason @expr{Y(x,y,z)} does not return
25079an error form, the combined error from @expr{z} is used directly for
4009494e 25080@texline @math{\sigma_i}.
40ba43b4 25081@infoline @expr{sigma_i}.
4009494e
GM
25082Finally, @expr{z} is also stripped of its error
25083for use in computing @expr{F(x,y,z)}, @expr{G(x,y,z)} and so on;
25084the righthand side of the linearized model is computed in regular
25085arithmetic with no error forms.
25086
25087(While these rules may seem complicated, they are designed to do
25088the most reasonable thing in the typical case that @expr{Y(x,y,z)}
25089depends only on the dependent variable @expr{z}, and in fact is
25090often simply equal to @expr{z}. For common cases like polynomials
25091and multilinear models, the combined error is simply used as the
25092@texline @math{\sigma}
40ba43b4 25093@infoline @expr{sigma}
4009494e
GM
25094for the data point with no further ado.)
25095
25096@tex
25097\bigskip
25098@end tex
25099
25100@vindex FitRules
25101It may be the case that the model you wish to use is linearizable,
25102but Calc's built-in rules are unable to figure it out. Calc uses
25103its algebraic rewrite mechanism to linearize a model. The rewrite
25104rules are kept in the variable @code{FitRules}. You can edit this
25105variable using the @kbd{s e FitRules} command; in fact, there is
25106a special @kbd{s F} command just for editing @code{FitRules}.
25107@xref{Operations on Variables}.
25108
25109@xref{Rewrite Rules}, for a discussion of rewrite rules.
25110
25111@ignore
25112@starindex
25113@end ignore
25114@tindex fitvar
25115@ignore
25116@starindex
25117@end ignore
25118@ignore
25119@mindex @idots
25120@end ignore
25121@tindex fitparam
25122@ignore
25123@starindex
25124@end ignore
25125@ignore
25126@mindex @null
25127@end ignore
25128@tindex fitmodel
25129@ignore
25130@starindex
25131@end ignore
25132@ignore
25133@mindex @null
25134@end ignore
25135@tindex fitsystem
25136@ignore
25137@starindex
25138@end ignore
25139@ignore
25140@mindex @null
25141@end ignore
25142@tindex fitdummy
25143Calc uses @code{FitRules} as follows. First, it converts the model
25144to an equation if necessary and encloses the model equation in a
25145call to the function @code{fitmodel} (which is not actually a defined
25146function in Calc; it is only used as a placeholder by the rewrite rules).
25147Parameter variables are renamed to function calls @samp{fitparam(1)},
25148@samp{fitparam(2)}, and so on, and independent variables are renamed
25149to @samp{fitvar(1)}, @samp{fitvar(2)}, etc. The dependent variable
25150is the highest-numbered @code{fitvar}. For example, the power law
25151model @expr{a x^b} is converted to @expr{y = a x^b}, then to
25152
25153@smallexample
25154@group
25155fitmodel(fitvar(2) = fitparam(1) fitvar(1)^fitparam(2))
25156@end group
25157@end smallexample
25158
25159Calc then applies the rewrites as if by @samp{C-u 0 a r FitRules}.
25160(The zero prefix means that rewriting should continue until no further
25161changes are possible.)
25162
25163When rewriting is complete, the @code{fitmodel} call should have
25164been replaced by a @code{fitsystem} call that looks like this:
25165
25166@example
25167fitsystem(@var{Y}, @var{FGH}, @var{abc})
25168@end example
25169
25170@noindent
25171where @var{Y} is a formula that describes the function @expr{Y(x,y,z)},
25172@var{FGH} is the vector of formulas @expr{[F(x,y,z), G(x,y,z), H(x,y,z)]},
25173and @var{abc} is the vector of parameter filters which refer to the
25174raw parameters as @samp{fitdummy(1)} for @expr{A}, @samp{fitdummy(2)}
25175for @expr{B}, etc. While the number of raw parameters (the length of
25176the @var{FGH} vector) is usually the same as the number of original
25177parameters (the length of the @var{abc} vector), this is not required.
25178
25179The power law model eventually boils down to
25180
25181@smallexample
25182@group
25183fitsystem(ln(fitvar(2)),
25184 [1, ln(fitvar(1))],
25185 [exp(fitdummy(1)), fitdummy(2)])
25186@end group
25187@end smallexample
25188
25189The actual implementation of @code{FitRules} is complicated; it
25190proceeds in four phases. First, common rearrangements are done
25191to try to bring linear terms together and to isolate functions like
25192@code{exp} and @code{ln} either all the way ``out'' (so that they
25193can be put into @var{Y}) or all the way ``in'' (so that they can
25194be put into @var{abc} or @var{FGH}). In particular, all
25195non-constant powers are converted to logs-and-exponentials form,
25196and the distributive law is used to expand products of sums.
25197Quotients are rewritten to use the @samp{fitinv} function, where
25198@samp{fitinv(x)} represents @expr{1/x} while the @code{FitRules}
25199are operating. (The use of @code{fitinv} makes recognition of
25200linear-looking forms easier.) If you modify @code{FitRules}, you
25201will probably only need to modify the rules for this phase.
25202
25203Phase two, whose rules can actually also apply during phases one
25204and three, first rewrites @code{fitmodel} to a two-argument
25205form @samp{fitmodel(@var{Y}, @var{model})}, where @var{Y} is
25206initially zero and @var{model} has been changed from @expr{a=b}
25207to @expr{a-b} form. It then tries to peel off invertible functions
25208from the outside of @var{model} and put them into @var{Y} instead,
25209calling the equation solver to invert the functions. Finally, when
25210this is no longer possible, the @code{fitmodel} is changed to a
25211four-argument @code{fitsystem}, where the fourth argument is
25212@var{model} and the @var{FGH} and @var{abc} vectors are initially
25213empty. (The last vector is really @var{ABC}, corresponding to
25214raw parameters, for now.)
25215
25216Phase three converts a sum of items in the @var{model} to a sum
25217of @samp{fitpart(@var{a}, @var{b}, @var{c})} terms which represent
25218terms @samp{@var{a}*@var{b}*@var{c}} of the sum, where @var{a}
25219is all factors that do not involve any variables, @var{b} is all
25220factors that involve only parameters, and @var{c} is the factors
25221that involve only independent variables. (If this decomposition
25222is not possible, the rule set will not complete and Calc will
25223complain that the model is too complex.) Then @code{fitpart}s
25224with equal @var{b} or @var{c} components are merged back together
25225using the distributive law in order to minimize the number of
25226raw parameters needed.
25227
25228Phase four moves the @code{fitpart} terms into the @var{FGH} and
25229@var{ABC} vectors. Also, some of the algebraic expansions that
25230were done in phase 1 are undone now to make the formulas more
25231computationally efficient. Finally, it calls the solver one more
25232time to convert the @var{ABC} vector to an @var{abc} vector, and
25233removes the fourth @var{model} argument (which by now will be zero)
25234to obtain the three-argument @code{fitsystem} that the linear
25235least-squares solver wants to see.
25236
25237@ignore
25238@starindex
25239@end ignore
25240@ignore
25241@mindex hasfit@idots
25242@end ignore
25243@tindex hasfitparams
25244@ignore
25245@starindex
25246@end ignore
25247@ignore
25248@mindex @null
25249@end ignore
25250@tindex hasfitvars
25251Two functions which are useful in connection with @code{FitRules}
25252are @samp{hasfitparams(x)} and @samp{hasfitvars(x)}, which check
25253whether @expr{x} refers to any parameters or independent variables,
25254respectively. Specifically, these functions return ``true'' if the
25255argument contains any @code{fitparam} (or @code{fitvar}) function
25256calls, and ``false'' otherwise. (Recall that ``true'' means a
25257nonzero number, and ``false'' means zero. The actual nonzero number
25258returned is the largest @var{n} from all the @samp{fitparam(@var{n})}s
25259or @samp{fitvar(@var{n})}s, respectively, that appear in the formula.)
25260
25261@tex
25262\bigskip
25263@end tex
25264
25265The @code{fit} function in algebraic notation normally takes four
25266arguments, @samp{fit(@var{model}, @var{vars}, @var{params}, @var{data})},
25267where @var{model} is the model formula as it would be typed after
25268@kbd{a F '}, @var{vars} is the independent variable or a vector of
25269independent variables, @var{params} likewise gives the parameter(s),
25270and @var{data} is the data matrix. Note that the length of @var{vars}
25271must be equal to the number of rows in @var{data} if @var{model} is
25272an equation, or one less than the number of rows if @var{model} is
25273a plain formula. (Actually, a name for the dependent variable is
25274allowed but will be ignored in the plain-formula case.)
25275
25276If @var{params} is omitted, the parameters are all variables in
25277@var{model} except those that appear in @var{vars}. If @var{vars}
25278is also omitted, Calc sorts all the variables that appear in
25279@var{model} alphabetically and uses the higher ones for @var{vars}
25280and the lower ones for @var{params}.
25281
25282Alternatively, @samp{fit(@var{modelvec}, @var{data})} is allowed
25283where @var{modelvec} is a 2- or 3-vector describing the model
25284and variables, as discussed previously.
25285
25286If Calc is unable to do the fit, the @code{fit} function is left
25287in symbolic form, ordinarily with an explanatory message. The
25288message will be ``Model expression is too complex'' if the
25289linearizer was unable to put the model into the required form.
25290
25291The @code{efit} (corresponding to @kbd{H a F}) and @code{xfit}
25292(for @kbd{I a F}) functions are completely analogous.
25293
25294@node Interpolation, , Curve Fitting Details, Curve Fitting
25295@subsection Polynomial Interpolation
25296
25297@kindex a p
25298@pindex calc-poly-interp
25299@tindex polint
25300The @kbd{a p} (@code{calc-poly-interp}) [@code{polint}] command does
25301a polynomial interpolation at a particular @expr{x} value. It takes
25302two arguments from the stack: A data matrix of the sort used by
25303@kbd{a F}, and a single number which represents the desired @expr{x}
25304value. Calc effectively does an exact polynomial fit as if by @kbd{a F i},
25305then substitutes the @expr{x} value into the result in order to get an
25306approximate @expr{y} value based on the fit. (Calc does not actually
25307use @kbd{a F i}, however; it uses a direct method which is both more
25308efficient and more numerically stable.)
25309
25310The result of @kbd{a p} is actually a vector of two values: The @expr{y}
25311value approximation, and an error measure @expr{dy} that reflects Calc's
25312estimation of the probable error of the approximation at that value of
25313@expr{x}. If the input @expr{x} is equal to any of the @expr{x} values
25314in the data matrix, the output @expr{y} will be the corresponding @expr{y}
25315value from the matrix, and the output @expr{dy} will be exactly zero.
25316
25317A prefix argument of 2 causes @kbd{a p} to take separate x- and
25318y-vectors from the stack instead of one data matrix.
25319
25320If @expr{x} is a vector of numbers, @kbd{a p} will return a matrix of
25321interpolated results for each of those @expr{x} values. (The matrix will
25322have two columns, the @expr{y} values and the @expr{dy} values.)
25323If @expr{x} is a formula instead of a number, the @code{polint} function
25324remains in symbolic form; use the @kbd{a "} command to expand it out to
25325a formula that describes the fit in symbolic terms.
25326
25327In all cases, the @kbd{a p} command leaves the data vectors or matrix
25328on the stack. Only the @expr{x} value is replaced by the result.
25329
25330@kindex H a p
25331@tindex ratint
25332The @kbd{H a p} [@code{ratint}] command does a rational function
25333interpolation. It is used exactly like @kbd{a p}, except that it
25334uses as its model the quotient of two polynomials. If there are
25335@expr{N} data points, the numerator and denominator polynomials will
25336each have degree @expr{N/2} (if @expr{N} is odd, the denominator will
25337have degree one higher than the numerator).
25338
25339Rational approximations have the advantage that they can accurately
25340describe functions that have poles (points at which the function's value
25341goes to infinity, so that the denominator polynomial of the approximation
25342goes to zero). If @expr{x} corresponds to a pole of the fitted rational
25343function, then the result will be a division by zero. If Infinite mode
25344is enabled, the result will be @samp{[uinf, uinf]}.
25345
25346There is no way to get the actual coefficients of the rational function
25347used by @kbd{H a p}. (The algorithm never generates these coefficients
25348explicitly, and quotients of polynomials are beyond @w{@kbd{a F}}'s
25349capabilities to fit.)
25350
25351@node Summations, Logical Operations, Curve Fitting, Algebra
25352@section Summations
25353
25354@noindent
25355@cindex Summation of a series
25356@kindex a +
25357@pindex calc-summation
25358@tindex sum
25359The @kbd{a +} (@code{calc-summation}) [@code{sum}] command computes
25360the sum of a formula over a certain range of index values. The formula
25361is taken from the top of the stack; the command prompts for the
25362name of the summation index variable, the lower limit of the
25363sum (any formula), and the upper limit of the sum. If you
25364enter a blank line at any of these prompts, that prompt and
25365any later ones are answered by reading additional elements from
25366the stack. Thus, @kbd{' k^2 @key{RET} ' k @key{RET} 1 @key{RET} 5 @key{RET} a + @key{RET}}
25367produces the result 55.
25368@tex
4009494e
GM
25369$$ \sum_{k=1}^5 k^2 = 55 $$
25370@end tex
25371
25372The choice of index variable is arbitrary, but it's best not to
25373use a variable with a stored value. In particular, while
25374@code{i} is often a favorite index variable, it should be avoided
25375in Calc because @code{i} has the imaginary constant @expr{(0, 1)}
25376as a value. If you pressed @kbd{=} on a sum over @code{i}, it would
25377be changed to a nonsensical sum over the ``variable'' @expr{(0, 1)}!
25378If you really want to use @code{i} as an index variable, use
25379@w{@kbd{s u i @key{RET}}} first to ``unstore'' this variable.
25380(@xref{Storing Variables}.)
25381
25382A numeric prefix argument steps the index by that amount rather
25383than by one. Thus @kbd{' a_k @key{RET} C-u -2 a + k @key{RET} 10 @key{RET} 0 @key{RET}}
25384yields @samp{a_10 + a_8 + a_6 + a_4 + a_2 + a_0}. A prefix
25385argument of plain @kbd{C-u} causes @kbd{a +} to prompt for the
25386step value, in which case you can enter any formula or enter
25387a blank line to take the step value from the stack. With the
25388@kbd{C-u} prefix, @kbd{a +} can take up to five arguments from
25389the stack: The formula, the variable, the lower limit, the
25390upper limit, and (at the top of the stack), the step value.
25391
25392Calc knows how to do certain sums in closed form. For example,
25393@samp{sum(6 k^2, k, 1, n) = @w{2 n^3} + 3 n^2 + n}. In particular,
25394this is possible if the formula being summed is polynomial or
25395exponential in the index variable. Sums of logarithms are
25396transformed into logarithms of products. Sums of trigonometric
25397and hyperbolic functions are transformed to sums of exponentials
25398and then done in closed form. Also, of course, sums in which the
25399lower and upper limits are both numbers can always be evaluated
25400just by grinding them out, although Calc will use closed forms
25401whenever it can for the sake of efficiency.
25402
25403The notation for sums in algebraic formulas is
25404@samp{sum(@var{expr}, @var{var}, @var{low}, @var{high}, @var{step})}.
25405If @var{step} is omitted, it defaults to one. If @var{high} is
25406omitted, @var{low} is actually the upper limit and the lower limit
25407is one. If @var{low} is also omitted, the limits are @samp{-inf}
25408and @samp{inf}, respectively.
25409
25410Infinite sums can sometimes be evaluated: @samp{sum(.5^k, k, 1, inf)}
25411returns @expr{1}. This is done by evaluating the sum in closed
25412form (to @samp{1. - 0.5^n} in this case), then evaluating this
25413formula with @code{n} set to @code{inf}. Calc's usual rules
25414for ``infinite'' arithmetic can find the answer from there. If
25415infinite arithmetic yields a @samp{nan}, or if the sum cannot be
25416solved in closed form, Calc leaves the @code{sum} function in
25417symbolic form. @xref{Infinities}.
25418
25419As a special feature, if the limits are infinite (or omitted, as
25420described above) but the formula includes vectors subscripted by
25421expressions that involve the iteration variable, Calc narrows
25422the limits to include only the range of integers which result in
25423valid subscripts for the vector. For example, the sum
25424@samp{sum(k [a,b,c,d,e,f,g]_(2k),k)} evaluates to @samp{b + 2 d + 3 f}.
25425
25426The limits of a sum do not need to be integers. For example,
25427@samp{sum(a_k, k, 0, 2 n, n)} produces @samp{a_0 + a_n + a_(2 n)}.
25428Calc computes the number of iterations using the formula
25429@samp{1 + (@var{high} - @var{low}) / @var{step}}, which must,
8e7046c3 25430after algebraic simplification, evaluate to an integer.
4009494e
GM
25431
25432If the number of iterations according to the above formula does
25433not come out to an integer, the sum is invalid and will be left
25434in symbolic form. However, closed forms are still supplied, and
25435you are on your honor not to misuse the resulting formulas by
25436substituting mismatched bounds into them. For example,
25437@samp{sum(k, k, 1, 10, 2)} is invalid, but Calc will go ahead and
25438evaluate the closed form solution for the limits 1 and 10 to get
25439the rather dubious answer, 29.25.
25440
25441If the lower limit is greater than the upper limit (assuming a
25442positive step size), the result is generally zero. However,
25443Calc only guarantees a zero result when the upper limit is
25444exactly one step less than the lower limit, i.e., if the number
25445of iterations is @mathit{-1}. Thus @samp{sum(f(k), k, n, n-1)} is zero
25446but the sum from @samp{n} to @samp{n-2} may report a nonzero value
25447if Calc used a closed form solution.
25448
25449Calc's logical predicates like @expr{a < b} return 1 for ``true''
25450and 0 for ``false.'' @xref{Logical Operations}. This can be
25451used to advantage for building conditional sums. For example,
25452@samp{sum(prime(k)*k^2, k, 1, 20)} is the sum of the squares of all
25453prime numbers from 1 to 20; the @code{prime} predicate returns 1 if
25454its argument is prime and 0 otherwise. You can read this expression
25455as ``the sum of @expr{k^2}, where @expr{k} is prime.'' Indeed,
25456@samp{sum(prime(k)*k^2, k)} would represent the sum of @emph{all} primes
25457squared, since the limits default to plus and minus infinity, but
25458there are no such sums that Calc's built-in rules can do in
25459closed form.
25460
25461As another example, @samp{sum((k != k_0) * f(k), k, 1, n)} is the
25462sum of @expr{f(k)} for all @expr{k} from 1 to @expr{n}, excluding
25463one value @expr{k_0}. Slightly more tricky is the summand
25464@samp{(k != k_0) / (k - k_0)}, which is an attempt to describe
25465the sum of all @expr{1/(k-k_0)} except at @expr{k = k_0}, where
25466this would be a division by zero. But at @expr{k = k_0}, this
25467formula works out to the indeterminate form @expr{0 / 0}, which
25468Calc will not assume is zero. Better would be to use
25469@samp{(k != k_0) ? 1/(k-k_0) : 0}; the @samp{? :} operator does
40ba43b4 25470an ``if-then-else'' test: This expression says, ``if
4009494e
GM
25471@texline @math{k \ne k_0},
25472@infoline @expr{k != k_0},
25473then @expr{1/(k-k_0)}, else zero.'' Now the formula @expr{1/(k-k_0)}
25474will not even be evaluated by Calc when @expr{k = k_0}.
25475
25476@cindex Alternating sums
25477@kindex a -
25478@pindex calc-alt-summation
25479@tindex asum
25480The @kbd{a -} (@code{calc-alt-summation}) [@code{asum}] command
25481computes an alternating sum. Successive terms of the sequence
25482are given alternating signs, with the first term (corresponding
25483to the lower index value) being positive. Alternating sums
25484are converted to normal sums with an extra term of the form
25485@samp{(-1)^(k-@var{low})}. This formula is adjusted appropriately
25486if the step value is other than one. For example, the Taylor
25487series for the sine function is @samp{asum(x^k / k!, k, 1, inf, 2)}.
25488(Calc cannot evaluate this infinite series, but it can approximate
25489it if you replace @code{inf} with any particular odd number.)
25490Calc converts this series to a regular sum with a step of one,
25491namely @samp{sum((-1)^k x^(2k+1) / (2k+1)!, k, 0, inf)}.
25492
25493@cindex Product of a sequence
25494@kindex a *
25495@pindex calc-product
25496@tindex prod
25497The @kbd{a *} (@code{calc-product}) [@code{prod}] command is
25498the analogous way to take a product of many terms. Calc also knows
25499some closed forms for products, such as @samp{prod(k, k, 1, n) = n!}.
25500Conditional products can be written @samp{prod(k^prime(k), k, 1, n)}
25501or @samp{prod(prime(k) ? k : 1, k, 1, n)}.
25502
25503@kindex a T
25504@pindex calc-tabulate
25505@tindex table
25506The @kbd{a T} (@code{calc-tabulate}) [@code{table}] command
25507evaluates a formula at a series of iterated index values, just
25508like @code{sum} and @code{prod}, but its result is simply a
25509vector of the results. For example, @samp{table(a_i, i, 1, 7, 2)}
25510produces @samp{[a_1, a_3, a_5, a_7]}.
25511
25512@node Logical Operations, Rewrite Rules, Summations, Algebra
25513@section Logical Operations
25514
25515@noindent
25516The following commands and algebraic functions return true/false values,
25517where 1 represents ``true'' and 0 represents ``false.'' In cases where
25518a truth value is required (such as for the condition part of a rewrite
25519rule, or as the condition for a @w{@kbd{Z [ Z ]}} control structure), any
25520nonzero value is accepted to mean ``true.'' (Specifically, anything
25521for which @code{dnonzero} returns 1 is ``true,'' and anything for
25522which @code{dnonzero} returns 0 or cannot decide is assumed ``false.''
25523Note that this means that @w{@kbd{Z [ Z ]}} will execute the ``then''
25524portion if its condition is provably true, but it will execute the
25525``else'' portion for any condition like @expr{a = b} that is not
25526provably true, even if it might be true. Algebraic functions that
25527have conditions as arguments, like @code{? :} and @code{&&}, remain
25528unevaluated if the condition is neither provably true nor provably
25529false. @xref{Declarations}.)
25530
25531@kindex a =
25532@pindex calc-equal-to
25533@tindex eq
25534@tindex =
25535@tindex ==
25536The @kbd{a =} (@code{calc-equal-to}) command, or @samp{eq(a,b)} function
25537(which can also be written @samp{a = b} or @samp{a == b} in an algebraic
25538formula) is true if @expr{a} and @expr{b} are equal, either because they
25539are identical expressions, or because they are numbers which are
25540numerically equal. (Thus the integer 1 is considered equal to the float
255411.0.) If the equality of @expr{a} and @expr{b} cannot be determined,
25542the comparison is left in symbolic form. Note that as a command, this
25543operation pops two values from the stack and pushes back either a 1 or
25544a 0, or a formula @samp{a = b} if the values' equality cannot be determined.
25545
25546Many Calc commands use @samp{=} formulas to represent @dfn{equations}.
25547For example, the @kbd{a S} (@code{calc-solve-for}) command rearranges
25548an equation to solve for a given variable. The @kbd{a M}
25549(@code{calc-map-equation}) command can be used to apply any
25550function to both sides of an equation; for example, @kbd{2 a M *}
25551multiplies both sides of the equation by two. Note that just
25552@kbd{2 *} would not do the same thing; it would produce the formula
25553@samp{2 (a = b)} which represents 2 if the equality is true or
25554zero if not.
25555
25556The @code{eq} function with more than two arguments (e.g., @kbd{C-u 3 a =}
25557or @samp{a = b = c}) tests if all of its arguments are equal. In
25558algebraic notation, the @samp{=} operator is unusual in that it is
25559neither left- nor right-associative: @samp{a = b = c} is not the
25560same as @samp{(a = b) = c} or @samp{a = (b = c)} (which each compare
25561one variable with the 1 or 0 that results from comparing two other
25562variables).
25563
25564@kindex a #
25565@pindex calc-not-equal-to
25566@tindex neq
25567@tindex !=
25568The @kbd{a #} (@code{calc-not-equal-to}) command, or @samp{neq(a,b)} or
25569@samp{a != b} function, is true if @expr{a} and @expr{b} are not equal.
25570This also works with more than two arguments; @samp{a != b != c != d}
25571tests that all four of @expr{a}, @expr{b}, @expr{c}, and @expr{d} are
25572distinct numbers.
25573
25574@kindex a <
25575@tindex lt
25576@ignore
25577@mindex @idots
25578@end ignore
25579@kindex a >
25580@ignore
25581@mindex @null
25582@end ignore
25583@kindex a [
25584@ignore
25585@mindex @null
25586@end ignore
25587@kindex a ]
25588@pindex calc-less-than
25589@pindex calc-greater-than
25590@pindex calc-less-equal
25591@pindex calc-greater-equal
25592@ignore
25593@mindex @null
25594@end ignore
25595@tindex gt
25596@ignore
25597@mindex @null
25598@end ignore
25599@tindex leq
25600@ignore
25601@mindex @null
25602@end ignore
25603@tindex geq
25604@ignore
25605@mindex @null
25606@end ignore
25607@tindex <
25608@ignore
25609@mindex @null
25610@end ignore
25611@tindex >
25612@ignore
25613@mindex @null
25614@end ignore
25615@tindex <=
25616@ignore
25617@mindex @null
25618@end ignore
25619@tindex >=
25620The @kbd{a <} (@code{calc-less-than}) [@samp{lt(a,b)} or @samp{a < b}]
25621operation is true if @expr{a} is less than @expr{b}. Similar functions
25622are @kbd{a >} (@code{calc-greater-than}) [@samp{gt(a,b)} or @samp{a > b}],
25623@kbd{a [} (@code{calc-less-equal}) [@samp{leq(a,b)} or @samp{a <= b}], and
25624@kbd{a ]} (@code{calc-greater-equal}) [@samp{geq(a,b)} or @samp{a >= b}].
25625
25626While the inequality functions like @code{lt} do not accept more
25627than two arguments, the syntax @w{@samp{a <= b < c}} is translated to an
25628equivalent expression involving intervals: @samp{b in [a .. c)}.
25629(See the description of @code{in} below.) All four combinations
25630of @samp{<} and @samp{<=} are allowed, or any of the four combinations
25631of @samp{>} and @samp{>=}. Four-argument constructions like
25632@samp{a < b < c < d}, and mixtures like @w{@samp{a < b = c}} that
e4769531 25633involve both equations and inequalities, are not allowed.
4009494e
GM
25634
25635@kindex a .
25636@pindex calc-remove-equal
25637@tindex rmeq
25638The @kbd{a .} (@code{calc-remove-equal}) [@code{rmeq}] command extracts
25639the righthand side of the equation or inequality on the top of the
25640stack. It also works elementwise on vectors. For example, if
25641@samp{[x = 2.34, y = z / 2]} is on the stack, then @kbd{a .} produces
25642@samp{[2.34, z / 2]}. As a special case, if the righthand side is a
25643variable and the lefthand side is a number (as in @samp{2.34 = x}), then
25644Calc keeps the lefthand side instead. Finally, this command works with
25645assignments @samp{x := 2.34} as well as equations, always taking the
25646righthand side, and for @samp{=>} (evaluates-to) operators, always
25647taking the lefthand side.
25648
25649@kindex a &
25650@pindex calc-logical-and
25651@tindex land
25652@tindex &&
25653The @kbd{a &} (@code{calc-logical-and}) [@samp{land(a,b)} or @samp{a && b}]
25654function is true if both of its arguments are true, i.e., are
25655non-zero numbers. In this case, the result will be either @expr{a} or
25656@expr{b}, chosen arbitrarily. If either argument is zero, the result is
25657zero. Otherwise, the formula is left in symbolic form.
25658
25659@kindex a |
25660@pindex calc-logical-or
25661@tindex lor
25662@tindex ||
25663The @kbd{a |} (@code{calc-logical-or}) [@samp{lor(a,b)} or @samp{a || b}]
25664function is true if either or both of its arguments are true (nonzero).
25665The result is whichever argument was nonzero, choosing arbitrarily if both
25666are nonzero. If both @expr{a} and @expr{b} are zero, the result is
25667zero.
25668
25669@kindex a !
25670@pindex calc-logical-not
25671@tindex lnot
25672@tindex !
25673The @kbd{a !} (@code{calc-logical-not}) [@samp{lnot(a)} or @samp{!@: a}]
25674function is true if @expr{a} is false (zero), or false if @expr{a} is
25675true (nonzero). It is left in symbolic form if @expr{a} is not a
25676number.
25677
25678@kindex a :
25679@pindex calc-logical-if
25680@tindex if
25681@ignore
25682@mindex ? :
25683@end ignore
25684@tindex ?
25685@ignore
25686@mindex @null
25687@end ignore
25688@tindex :
25689@cindex Arguments, not evaluated
25690The @kbd{a :} (@code{calc-logical-if}) [@samp{if(a,b,c)} or @samp{a ? b :@: c}]
25691function is equal to either @expr{b} or @expr{c} if @expr{a} is a nonzero
25692number or zero, respectively. If @expr{a} is not a number, the test is
25693left in symbolic form and neither @expr{b} nor @expr{c} is evaluated in
25694any way. In algebraic formulas, this is one of the few Calc functions
25695whose arguments are not automatically evaluated when the function itself
25696is evaluated. The others are @code{lambda}, @code{quote}, and
25697@code{condition}.
25698
25699One minor surprise to watch out for is that the formula @samp{a?3:4}
25700will not work because the @samp{3:4} is parsed as a fraction instead of
25701as three separate symbols. Type something like @samp{a ? 3 : 4} or
25702@samp{a?(3):4} instead.
25703
25704As a special case, if @expr{a} evaluates to a vector, then both @expr{b}
25705and @expr{c} are evaluated; the result is a vector of the same length
25706as @expr{a} whose elements are chosen from corresponding elements of
25707@expr{b} and @expr{c} according to whether each element of @expr{a}
25708is zero or nonzero. Each of @expr{b} and @expr{c} must be either a
25709vector of the same length as @expr{a}, or a non-vector which is matched
25710with all elements of @expr{a}.
25711
25712@kindex a @{
25713@pindex calc-in-set
25714@tindex in
25715The @kbd{a @{} (@code{calc-in-set}) [@samp{in(a,b)}] function is true if
25716the number @expr{a} is in the set of numbers represented by @expr{b}.
25717If @expr{b} is an interval form, @expr{a} must be one of the values
25718encompassed by the interval. If @expr{b} is a vector, @expr{a} must be
25719equal to one of the elements of the vector. (If any vector elements are
25720intervals, @expr{a} must be in any of the intervals.) If @expr{b} is a
25721plain number, @expr{a} must be numerically equal to @expr{b}.
25722@xref{Set Operations}, for a group of commands that manipulate sets
25723of this sort.
25724
25725@ignore
25726@starindex
25727@end ignore
25728@tindex typeof
25729The @samp{typeof(a)} function produces an integer or variable which
25730characterizes @expr{a}. If @expr{a} is a number, vector, or variable,
25731the result will be one of the following numbers:
25732
25733@example
25734 1 Integer
25735 2 Fraction
25736 3 Floating-point number
25737 4 HMS form
25738 5 Rectangular complex number
25739 6 Polar complex number
25740 7 Error form
25741 8 Interval form
25742 9 Modulo form
2574310 Date-only form
2574411 Date/time form
2574512 Infinity (inf, uinf, or nan)
25746100 Variable
25747101 Vector (but not a matrix)
25748102 Matrix
25749@end example
25750
25751Otherwise, @expr{a} is a formula, and the result is a variable which
25752represents the name of the top-level function call.
25753
25754@ignore
25755@starindex
25756@end ignore
25757@tindex integer
25758@ignore
25759@starindex
25760@end ignore
25761@tindex real
25762@ignore
25763@starindex
25764@end ignore
25765@tindex constant
25766The @samp{integer(a)} function returns true if @expr{a} is an integer.
25767The @samp{real(a)} function
25768is true if @expr{a} is a real number, either integer, fraction, or
25769float. The @samp{constant(a)} function returns true if @expr{a} is
25770any of the objects for which @code{typeof} would produce an integer
25771code result except for variables, and provided that the components of
25772an object like a vector or error form are themselves constant.
25773Note that infinities do not satisfy any of these tests, nor do
25774special constants like @code{pi} and @code{e}.
25775
25776@xref{Declarations}, for a set of similar functions that recognize
25777formulas as well as actual numbers. For example, @samp{dint(floor(x))}
25778is true because @samp{floor(x)} is provably integer-valued, but
25779@samp{integer(floor(x))} does not because @samp{floor(x)} is not
25780literally an integer constant.
25781
25782@ignore
25783@starindex
25784@end ignore
25785@tindex refers
25786The @samp{refers(a,b)} function is true if the variable (or sub-expression)
25787@expr{b} appears in @expr{a}, or false otherwise. Unlike the other
25788tests described here, this function returns a definite ``no'' answer
25789even if its arguments are still in symbolic form. The only case where
25790@code{refers} will be left unevaluated is if @expr{a} is a plain
25791variable (different from @expr{b}).
25792
25793@ignore
25794@starindex
25795@end ignore
25796@tindex negative
25797The @samp{negative(a)} function returns true if @expr{a} ``looks'' negative,
25798because it is a negative number, because it is of the form @expr{-x},
25799or because it is a product or quotient with a term that looks negative.
25800This is most useful in rewrite rules. Beware that @samp{negative(a)}
25801evaluates to 1 or 0 for @emph{any} argument @expr{a}, so it can only
25802be stored in a formula if the default simplifications are turned off
25803first with @kbd{m O} (or if it appears in an unevaluated context such
25804as a rewrite rule condition).
25805
25806@ignore
25807@starindex
25808@end ignore
25809@tindex variable
25810The @samp{variable(a)} function is true if @expr{a} is a variable,
25811or false if not. If @expr{a} is a function call, this test is left
25812in symbolic form. Built-in variables like @code{pi} and @code{inf}
25813are considered variables like any others by this test.
25814
25815@ignore
25816@starindex
25817@end ignore
25818@tindex nonvar
25819The @samp{nonvar(a)} function is true if @expr{a} is a non-variable.
25820If its argument is a variable it is left unsimplified; it never
25821actually returns zero. However, since Calc's condition-testing
25822commands consider ``false'' anything not provably true, this is
25823often good enough.
25824
25825@ignore
25826@starindex
25827@end ignore
25828@tindex lin
25829@ignore
25830@starindex
25831@end ignore
25832@tindex linnt
25833@ignore
25834@starindex
25835@end ignore
25836@tindex islin
25837@ignore
25838@starindex
25839@end ignore
25840@tindex islinnt
25841@cindex Linearity testing
25842The functions @code{lin}, @code{linnt}, @code{islin}, and @code{islinnt}
25843check if an expression is ``linear,'' i.e., can be written in the form
25844@expr{a + b x} for some constants @expr{a} and @expr{b}, and some
25845variable or subformula @expr{x}. The function @samp{islin(f,x)} checks
25846if formula @expr{f} is linear in @expr{x}, returning 1 if so. For
25847example, @samp{islin(x,x)}, @samp{islin(-x,x)}, @samp{islin(3,x)}, and
25848@samp{islin(x y / 3 - 2, x)} all return 1. The @samp{lin(f,x)} function
25849is similar, except that instead of returning 1 it returns the vector
25850@expr{[a, b, x]}. For the above examples, this vector would be
25851@expr{[0, 1, x]}, @expr{[0, -1, x]}, @expr{[3, 0, x]}, and
25852@expr{[-2, y/3, x]}, respectively. Both @code{lin} and @code{islin}
25853generally remain unevaluated for expressions which are not linear,
25854e.g., @samp{lin(2 x^2, x)} and @samp{lin(sin(x), x)}. The second
25855argument can also be a formula; @samp{islin(2 + 3 sin(x), sin(x))}
25856returns true.
25857
25858The @code{linnt} and @code{islinnt} functions perform a similar check,
25859but require a ``non-trivial'' linear form, which means that the
25860@expr{b} coefficient must be non-zero. For example, @samp{lin(2,x)}
25861returns @expr{[2, 0, x]} and @samp{lin(y,x)} returns @expr{[y, 0, x]},
25862but @samp{linnt(2,x)} and @samp{linnt(y,x)} are left unevaluated
25863(in other words, these formulas are considered to be only ``trivially''
25864linear in @expr{x}).
25865
25866All four linearity-testing functions allow you to omit the second
25867argument, in which case the input may be linear in any non-constant
25868formula. Here, the @expr{a=0}, @expr{b=1} case is also considered
25869trivial, and only constant values for @expr{a} and @expr{b} are
25870recognized. Thus, @samp{lin(2 x y)} returns @expr{[0, 2, x y]},
25871@samp{lin(2 - x y)} returns @expr{[2, -1, x y]}, and @samp{lin(x y)}
25872returns @expr{[0, 1, x y]}. The @code{linnt} function would allow the
25873first two cases but not the third. Also, neither @code{lin} nor
25874@code{linnt} accept plain constants as linear in the one-argument
25875case: @samp{islin(2,x)} is true, but @samp{islin(2)} is false.
25876
25877@ignore
25878@starindex
25879@end ignore
25880@tindex istrue
25881The @samp{istrue(a)} function returns 1 if @expr{a} is a nonzero
25882number or provably nonzero formula, or 0 if @expr{a} is anything else.
25883Calls to @code{istrue} can only be manipulated if @kbd{m O} mode is
25884used to make sure they are not evaluated prematurely. (Note that
25885declarations are used when deciding whether a formula is true;
25886@code{istrue} returns 1 when @code{dnonzero} would return 1, and
25887it returns 0 when @code{dnonzero} would return 0 or leave itself
25888in symbolic form.)
25889
25890@node Rewrite Rules, , Logical Operations, Algebra
25891@section Rewrite Rules
25892
25893@noindent
25894@cindex Rewrite rules
25895@cindex Transformations
25896@cindex Pattern matching
25897@kindex a r
25898@pindex calc-rewrite
25899@tindex rewrite
25900The @kbd{a r} (@code{calc-rewrite}) [@code{rewrite}] command makes
25901substitutions in a formula according to a specified pattern or patterns
25902known as @dfn{rewrite rules}. Whereas @kbd{a b} (@code{calc-substitute})
25903matches literally, so that substituting @samp{sin(x)} with @samp{cos(x)}
25904matches only the @code{sin} function applied to the variable @code{x},
25905rewrite rules match general kinds of formulas; rewriting using the rule
25906@samp{sin(x) := cos(x)} matches @code{sin} of any argument and replaces
25907it with @code{cos} of that same argument. The only significance of the
25908name @code{x} is that the same name is used on both sides of the rule.
25909
25910Rewrite rules rearrange formulas already in Calc's memory.
25911@xref{Syntax Tables}, to read about @dfn{syntax rules}, which are
25912similar to algebraic rewrite rules but operate when new algebraic
25913entries are being parsed, converting strings of characters into
25914Calc formulas.
25915
25916@menu
25917* Entering Rewrite Rules::
25918* Basic Rewrite Rules::
25919* Conditional Rewrite Rules::
25920* Algebraic Properties of Rewrite Rules::
25921* Other Features of Rewrite Rules::
25922* Composing Patterns in Rewrite Rules::
25923* Nested Formulas with Rewrite Rules::
25924* Multi-Phase Rewrite Rules::
25925* Selections with Rewrite Rules::
25926* Matching Commands::
25927* Automatic Rewrites::
25928* Debugging Rewrites::
25929* Examples of Rewrite Rules::
25930@end menu
25931
25932@node Entering Rewrite Rules, Basic Rewrite Rules, Rewrite Rules, Rewrite Rules
25933@subsection Entering Rewrite Rules
25934
25935@noindent
25936Rewrite rules normally use the ``assignment'' operator
25937@samp{@var{old} := @var{new}}.
25938This operator is equivalent to the function call @samp{assign(old, new)}.
25939The @code{assign} function is undefined by itself in Calc, so an
25940assignment formula such as a rewrite rule will be left alone by ordinary
25941Calc commands. But certain commands, like the rewrite system, interpret
25942assignments in special ways.
25943
25944For example, the rule @samp{sin(x)^2 := 1-cos(x)^2} says to replace
25945every occurrence of the sine of something, squared, with one minus the
25946square of the cosine of that same thing. All by itself as a formula
25947on the stack it does nothing, but when given to the @kbd{a r} command
25948it turns that command into a sine-squared-to-cosine-squared converter.
25949
25950To specify a set of rules to be applied all at once, make a vector of
25951rules.
25952
25953When @kbd{a r} prompts you to enter the rewrite rules, you can answer
25954in several ways:
25955
25956@enumerate
25957@item
25958With a rule: @kbd{f(x) := g(x) @key{RET}}.
25959@item
25960With a vector of rules: @kbd{[f1(x) := g1(x), f2(x) := g2(x)] @key{RET}}.
25961(You can omit the enclosing square brackets if you wish.)
25962@item
25963With the name of a variable that contains the rule or rules vector:
25964@kbd{myrules @key{RET}}.
25965@item
25966With any formula except a rule, a vector, or a variable name; this
25967will be interpreted as the @var{old} half of a rewrite rule,
25968and you will be prompted a second time for the @var{new} half:
25969@kbd{f(x) @key{RET} g(x) @key{RET}}.
25970@item
25971With a blank line, in which case the rule, rules vector, or variable
25972will be taken from the top of the stack (and the formula to be
25973rewritten will come from the second-to-top position).
25974@end enumerate
25975
25976If you enter the rules directly (as opposed to using rules stored
25977in a variable), those rules will be put into the Trail so that you
25978can retrieve them later. @xref{Trail Commands}.
25979
25980It is most convenient to store rules you use often in a variable and
25981invoke them by giving the variable name. The @kbd{s e}
25982(@code{calc-edit-variable}) command is an easy way to create or edit a
25983rule set stored in a variable. You may also wish to use @kbd{s p}
25984(@code{calc-permanent-variable}) to save your rules permanently;
25985@pxref{Operations on Variables}.
25986
25987Rewrite rules are compiled into a special internal form for faster
25988matching. If you enter a rule set directly it must be recompiled
25989every time. If you store the rules in a variable and refer to them
25990through that variable, they will be compiled once and saved away
25991along with the variable for later reference. This is another good
25992reason to store your rules in a variable.
25993
25994Calc also accepts an obsolete notation for rules, as vectors
25995@samp{[@var{old}, @var{new}]}. But because it is easily confused with a
25996vector of two rules, the use of this notation is no longer recommended.
25997
25998@node Basic Rewrite Rules, Conditional Rewrite Rules, Entering Rewrite Rules, Rewrite Rules
25999@subsection Basic Rewrite Rules
26000
26001@noindent
26002To match a particular formula @expr{x} with a particular rewrite rule
26003@samp{@var{old} := @var{new}}, Calc compares the structure of @expr{x} with
26004the structure of @var{old}. Variables that appear in @var{old} are
26005treated as @dfn{meta-variables}; the corresponding positions in @expr{x}
26006may contain any sub-formulas. For example, the pattern @samp{f(x,y)}
26007would match the expression @samp{f(12, a+1)} with the meta-variable
26008@samp{x} corresponding to 12 and with @samp{y} corresponding to
26009@samp{a+1}. However, this pattern would not match @samp{f(12)} or
26010@samp{g(12, a+1)}, since there is no assignment of the meta-variables
26011that will make the pattern match these expressions. Notice that if
26012the pattern is a single meta-variable, it will match any expression.
26013
26014If a given meta-variable appears more than once in @var{old}, the
26015corresponding sub-formulas of @expr{x} must be identical. Thus
26016the pattern @samp{f(x,x)} would match @samp{f(12, 12)} and
26017@samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(a+b, b+a)}.
26018(@xref{Conditional Rewrite Rules}, for a way to match the latter.)
26019
26020Things other than variables must match exactly between the pattern
26021and the target formula. To match a particular variable exactly, use
26022the pseudo-function @samp{quote(v)} in the pattern. For example, the
26023pattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or
26024@samp{sin(a)+y}.
26025
26026The special variable names @samp{e}, @samp{pi}, @samp{i}, @samp{phi},
26027@samp{gamma}, @samp{inf}, @samp{uinf}, and @samp{nan} always match
26028literally. Thus the pattern @samp{sin(d + e + f)} acts exactly like
26029@samp{sin(d + quote(e) + f)}.
26030
26031If the @var{old} pattern is found to match a given formula, that
26032formula is replaced by @var{new}, where any occurrences in @var{new}
26033of meta-variables from the pattern are replaced with the sub-formulas
26034that they matched. Thus, applying the rule @samp{f(x,y) := g(y+x,x)}
26035to @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}.
26036
26037The normal @kbd{a r} command applies rewrite rules over and over
26038throughout the target formula until no further changes are possible
26039(up to a limit of 100 times). Use @kbd{C-u 1 a r} to make only one
26040change at a time.
26041
26042@node Conditional Rewrite Rules, Algebraic Properties of Rewrite Rules, Basic Rewrite Rules, Rewrite Rules
26043@subsection Conditional Rewrite Rules
26044
26045@noindent
26046A rewrite rule can also be @dfn{conditional}, written in the form
26047@samp{@var{old} := @var{new} :: @var{cond}}. (There is also the obsolete
26048form @samp{[@var{old}, @var{new}, @var{cond}]}.) If a @var{cond} part
26049is present in the
26050rule, this is an additional condition that must be satisfied before
26051the rule is accepted. Once @var{old} has been successfully matched
26052to the target expression, @var{cond} is evaluated (with all the
26053meta-variables substituted for the values they matched) and simplified
8e7046c3 26054with Calc's algebraic simplifications. If the result is a nonzero
4009494e
GM
26055number or any other object known to be nonzero (@pxref{Declarations}),
26056the rule is accepted. If the result is zero or if it is a symbolic
26057formula that is not known to be nonzero, the rule is rejected.
26058@xref{Logical Operations}, for a number of functions that return
260591 or 0 according to the results of various tests.
26060
26061For example, the formula @samp{n > 0} simplifies to 1 or 0 if @expr{n}
26062is replaced by a positive or nonpositive number, respectively (or if
26063@expr{n} has been declared to be positive or nonpositive). Thus,
26064the rule @samp{f(x,y) := g(y+x,x) :: x+y > 0} would apply to
26065@samp{f(0, 4)} but not to @samp{f(-3, 2)} or @samp{f(12, a+1)}
26066(assuming no outstanding declarations for @expr{a}). In the case of
26067@samp{f(-3, 2)}, the condition can be shown not to be satisfied; in
26068the case of @samp{f(12, a+1)}, the condition merely cannot be shown
26069to be satisfied, but that is enough to reject the rule.
26070
26071While Calc will use declarations to reason about variables in the
26072formula being rewritten, declarations do not apply to meta-variables.
26073For example, the rule @samp{f(a) := g(a+1)} will match for any values
26074of @samp{a}, such as complex numbers, vectors, or formulas, even if
26075@samp{a} has been declared to be real or scalar. If you want the
26076meta-variable @samp{a} to match only literal real numbers, use
26077@samp{f(a) := g(a+1) :: real(a)}. If you want @samp{a} to match only
26078reals and formulas which are provably real, use @samp{dreal(a)} as
26079the condition.
26080
26081The @samp{::} operator is a shorthand for the @code{condition}
26082function; @samp{@var{old} := @var{new} :: @var{cond}} is equivalent to
26083the formula @samp{condition(assign(@var{old}, @var{new}), @var{cond})}.
26084
26085If you have several conditions, you can use @samp{... :: c1 :: c2 :: c3}
26086or @samp{... :: c1 && c2 && c3}. The two are entirely equivalent.
26087
26088It is also possible to embed conditions inside the pattern:
26089@samp{f(x :: x>0, y) := g(y+x, x)}. This is purely a notational
26090convenience, though; where a condition appears in a rule has no
26091effect on when it is tested. The rewrite-rule compiler automatically
26092decides when it is best to test each condition while a rule is being
26093matched.
26094
26095Certain conditions are handled as special cases by the rewrite rule
26096system and are tested very efficiently: Where @expr{x} is any
26097meta-variable, these conditions are @samp{integer(x)}, @samp{real(x)},
26098@samp{constant(x)}, @samp{negative(x)}, @samp{x >= y} where @expr{y}
26099is either a constant or another meta-variable and @samp{>=} may be
26100replaced by any of the six relational operators, and @samp{x % a = b}
26101where @expr{a} and @expr{b} are constants. Other conditions, like
26102@samp{x >= y+1} or @samp{dreal(x)}, will be less efficient to check
26103since Calc must bring the whole evaluator and simplifier into play.
26104
26105An interesting property of @samp{::} is that neither of its arguments
26106will be touched by Calc's default simplifications. This is important
26107because conditions often are expressions that cannot safely be
26108evaluated early. For example, the @code{typeof} function never
26109remains in symbolic form; entering @samp{typeof(a)} will put the
26110number 100 (the type code for variables like @samp{a}) on the stack.
26111But putting the condition @samp{... :: typeof(a) = 6} on the stack
26112is safe since @samp{::} prevents the @code{typeof} from being
26113evaluated until the condition is actually used by the rewrite system.
26114
26115Since @samp{::} protects its lefthand side, too, you can use a dummy
26116condition to protect a rule that must itself not evaluate early.
26117For example, it's not safe to put @samp{a(f,x) := apply(f, [x])} on
26118the stack because it will immediately evaluate to @samp{a(f,x) := f(x)},
26119where the meta-variable-ness of @code{f} on the righthand side has been
26120lost. But @samp{a(f,x) := apply(f, [x]) :: 1} is safe, and of course
26121the condition @samp{1} is always true (nonzero) so it has no effect on
26122the functioning of the rule. (The rewrite compiler will ensure that
26123it doesn't even impact the speed of matching the rule.)
26124
26125@node Algebraic Properties of Rewrite Rules, Other Features of Rewrite Rules, Conditional Rewrite Rules, Rewrite Rules
26126@subsection Algebraic Properties of Rewrite Rules
26127
26128@noindent
26129The rewrite mechanism understands the algebraic properties of functions
26130like @samp{+} and @samp{*}. In particular, pattern matching takes
26131the associativity and commutativity of the following functions into
26132account:
26133
26134@smallexample
26135+ - * = != && || and or xor vint vunion vxor gcd lcm max min beta
26136@end smallexample
26137
26138For example, the rewrite rule:
26139
26140@example
26141a x + b x := (a + b) x
26142@end example
26143
26144@noindent
26145will match formulas of the form,
26146
26147@example
26148a x + b x, x a + x b, a x + x b, x a + b x
26149@end example
26150
26151Rewrites also understand the relationship between the @samp{+} and @samp{-}
26152operators. The above rewrite rule will also match the formulas,
26153
26154@example
26155a x - b x, x a - x b, a x - x b, x a - b x
26156@end example
26157
26158@noindent
26159by matching @samp{b} in the pattern to @samp{-b} from the formula.
26160
26161Applied to a sum of many terms like @samp{r + a x + s + b x + t}, this
26162pattern will check all pairs of terms for possible matches. The rewrite
26163will take whichever suitable pair it discovers first.
26164
26165In general, a pattern using an associative operator like @samp{a + b}
26166will try @var{2 n} different ways to match a sum of @var{n} terms
26167like @samp{x + y + z - w}. First, @samp{a} is matched against each
26168of @samp{x}, @samp{y}, @samp{z}, and @samp{-w} in turn, with @samp{b}
26169being matched to the remainders @samp{y + z - w}, @samp{x + z - w}, etc.
26170If none of these succeed, then @samp{b} is matched against each of the
26171four terms with @samp{a} matching the remainder. Half-and-half matches,
26172like @samp{(x + y) + (z - w)}, are not tried.
26173
26174Note that @samp{*} is not commutative when applied to matrices, but
26175rewrite rules pretend that it is. If you type @kbd{m v} to enable
26176Matrix mode (@pxref{Matrix Mode}), rewrite rules will match @samp{*}
26177literally, ignoring its usual commutativity property. (In the
26178current implementation, the associativity also vanishes---it is as
26179if the pattern had been enclosed in a @code{plain} marker; see below.)
26180If you are applying rewrites to formulas with matrices, it's best to
26181enable Matrix mode first to prevent algebraically incorrect rewrites
26182from occurring.
26183
26184The pattern @samp{-x} will actually match any expression. For example,
26185the rule
26186
26187@example
26188f(-x) := -f(x)
26189@end example
26190
26191@noindent
26192will rewrite @samp{f(a)} to @samp{-f(-a)}. To avoid this, either use
26193a @code{plain} marker as described below, or add a @samp{negative(x)}
26194condition. The @code{negative} function is true if its argument
26195``looks'' negative, for example, because it is a negative number or
26196because it is a formula like @samp{-x}. The new rule using this
26197condition is:
26198
26199@example
26200f(x) := -f(-x) :: negative(x) @r{or, equivalently,}
26201f(-x) := -f(x) :: negative(-x)
26202@end example
26203
26204In the same way, the pattern @samp{x - y} will match the sum @samp{a + b}
26205by matching @samp{y} to @samp{-b}.
26206
26207The pattern @samp{a b} will also match the formula @samp{x/y} if
26208@samp{y} is a number. Thus the rule @samp{a x + @w{b x} := (a+b) x}
26209will also convert @samp{a x + x / 2} to @samp{(a + 0.5) x} (or
26210@samp{(a + 1:2) x}, depending on the current fraction mode).
26211
26212Calc will @emph{not} take other liberties with @samp{*}, @samp{/}, and
26213@samp{^}. For example, the pattern @samp{f(a b)} will not match
26214@samp{f(x^2)}, and @samp{f(a + b)} will not match @samp{f(2 x)}, even
26215though conceivably these patterns could match with @samp{a = b = x}.
26216Nor will @samp{f(a b)} match @samp{f(x / y)} if @samp{y} is not a
26217constant, even though it could be considered to match with @samp{a = x}
26218and @samp{b = 1/y}. The reasons are partly for efficiency, and partly
26219because while few mathematical operations are substantively different
26220for addition and subtraction, often it is preferable to treat the cases
26221of multiplication, division, and integer powers separately.
26222
26223Even more subtle is the rule set
26224
26225@example
26226[ f(a) + f(b) := f(a + b), -f(a) := f(-a) ]
26227@end example
26228
26229@noindent
26230attempting to match @samp{f(x) - f(y)}. You might think that Calc
26231will view this subtraction as @samp{f(x) + (-f(y))} and then apply
26232the above two rules in turn, but actually this will not work because
26233Calc only does this when considering rules for @samp{+} (like the
26234first rule in this set). So it will see first that @samp{f(x) + (-f(y))}
26235does not match @samp{f(a) + f(b)} for any assignments of the
26236meta-variables, and then it will see that @samp{f(x) - f(y)} does
26237not match @samp{-f(a)} for any assignment of @samp{a}. Because Calc
26238tries only one rule at a time, it will not be able to rewrite
26239@samp{f(x) - f(y)} with this rule set. An explicit @samp{f(a) - f(b)}
26240rule will have to be added.
26241
26242Another thing patterns will @emph{not} do is break up complex numbers.
26243The pattern @samp{myconj(a + @w{b i)} := a - b i} will work for formulas
26244involving the special constant @samp{i} (such as @samp{3 - 4 i}), but
26245it will not match actual complex numbers like @samp{(3, -4)}. A version
26246of the above rule for complex numbers would be
26247
26248@example
26249myconj(a) := re(a) - im(a) (0,1) :: im(a) != 0
26250@end example
26251
26252@noindent
26253(Because the @code{re} and @code{im} functions understand the properties
26254of the special constant @samp{i}, this rule will also work for
26255@samp{3 - 4 i}. In fact, this particular rule would probably be better
26256without the @samp{im(a) != 0} condition, since if @samp{im(a) = 0} the
26257righthand side of the rule will still give the correct answer for the
26258conjugate of a real number.)
26259
26260It is also possible to specify optional arguments in patterns. The rule
26261
26262@example
26263opt(a) x + opt(b) (x^opt(c) + opt(d)) := f(a, b, c, d)
26264@end example
26265
26266@noindent
26267will match the formula
26268
26269@example
262705 (x^2 - 4) + 3 x
26271@end example
26272
26273@noindent
26274in a fairly straightforward manner, but it will also match reduced
26275formulas like
26276
26277@example
26278x + x^2, 2(x + 1) - x, x + x
26279@end example
26280
26281@noindent
26282producing, respectively,
26283
26284@example
26285f(1, 1, 2, 0), f(-1, 2, 1, 1), f(1, 1, 1, 0)
26286@end example
26287
26288(The latter two formulas can be entered only if default simplifications
26289have been turned off with @kbd{m O}.)
26290
26291The default value for a term of a sum is zero. The default value
26292for a part of a product, for a power, or for the denominator of a
26293quotient, is one. Also, @samp{-x} matches the pattern @samp{opt(a) b}
26294with @samp{a = -1}.
26295
26296In particular, the distributive-law rule can be refined to
26297
26298@example
26299opt(a) x + opt(b) x := (a + b) x
26300@end example
26301
26302@noindent
26303so that it will convert, e.g., @samp{a x - x}, to @samp{(a - 1) x}.
26304
26305The pattern @samp{opt(a) + opt(b) x} matches almost any formulas which
26306are linear in @samp{x}. You can also use the @code{lin} and @code{islin}
26307functions with rewrite conditions to test for this; @pxref{Logical
26308Operations}. These functions are not as convenient to use in rewrite
26309rules, but they recognize more kinds of formulas as linear:
26310@samp{x/z} is considered linear with @expr{b = 1/z} by @code{lin},
26311but it will not match the above pattern because that pattern calls
26312for a multiplication, not a division.
26313
26314As another example, the obvious rule to replace @samp{sin(x)^2 + cos(x)^2}
26315by 1,
26316
26317@example
26318sin(x)^2 + cos(x)^2 := 1
26319@end example
26320
26321@noindent
26322misses many cases because the sine and cosine may both be multiplied by
26323an equal factor. Here's a more successful rule:
26324
26325@example
26326opt(a) sin(x)^2 + opt(a) cos(x)^2 := a
26327@end example
26328
26329Note that this rule will @emph{not} match @samp{sin(x)^2 + 6 cos(x)^2}
26330because one @expr{a} would have ``matched'' 1 while the other matched 6.
26331
26332Calc automatically converts a rule like
26333
26334@example
26335f(x-1, x) := g(x)
26336@end example
26337
26338@noindent
26339into the form
26340
26341@example
26342f(temp, x) := g(x) :: temp = x-1
26343@end example
26344
26345@noindent
26346(where @code{temp} stands for a new, invented meta-variable that
26347doesn't actually have a name). This modified rule will successfully
26348match @samp{f(6, 7)}, binding @samp{temp} and @samp{x} to 6 and 7,
26349respectively, then verifying that they differ by one even though
26350@samp{6} does not superficially look like @samp{x-1}.
26351
26352However, Calc does not solve equations to interpret a rule. The
26353following rule,
26354
26355@example
26356f(x-1, x+1) := g(x)
26357@end example
26358
26359@noindent
26360will not work. That is, it will match @samp{f(a - 1 + b, a + 1 + b)}
26361but not @samp{f(6, 8)}. Calc always interprets at least one occurrence
26362of a variable by literal matching. If the variable appears ``isolated''
26363then Calc is smart enough to use it for literal matching. But in this
26364last example, Calc is forced to rewrite the rule to @samp{f(x-1, temp)
26365:= g(x) :: temp = x+1} where the @samp{x-1} term must correspond to an
26366actual ``something-minus-one'' in the target formula.
26367
26368A successful way to write this would be @samp{f(x, x+2) := g(x+1)}.
26369You could make this resemble the original form more closely by using
26370@code{let} notation, which is described in the next section:
26371
26372@example
26373f(xm1, x+1) := g(x) :: let(x := xm1+1)
26374@end example
26375
26376Calc does this rewriting or ``conditionalizing'' for any sub-pattern
26377which involves only the functions in the following list, operating
26378only on constants and meta-variables which have already been matched
26379elsewhere in the pattern. When matching a function call, Calc is
26380careful to match arguments which are plain variables before arguments
26381which are calls to any of the functions below, so that a pattern like
26382@samp{f(x-1, x)} can be conditionalized even though the isolated
26383@samp{x} comes after the @samp{x-1}.
26384
26385@smallexample
26386+ - * / \ % ^ abs sign round rounde roundu trunc floor ceil
26387max min re im conj arg
26388@end smallexample
26389
26390You can suppress all of the special treatments described in this
26391section by surrounding a function call with a @code{plain} marker.
26392This marker causes the function call which is its argument to be
26393matched literally, without regard to commutativity, associativity,
26394negation, or conditionalization. When you use @code{plain}, the
26395``deep structure'' of the formula being matched can show through.
26396For example,
26397
26398@example
26399plain(a - a b) := f(a, b)
26400@end example
26401
26402@noindent
26403will match only literal subtractions. However, the @code{plain}
26404marker does not affect its arguments' arguments. In this case,
26405commutativity and associativity is still considered while matching
26406the @w{@samp{a b}} sub-pattern, so the whole pattern will match
26407@samp{x - y x} as well as @samp{x - x y}. We could go still
26408further and use
26409
26410@example
26411plain(a - plain(a b)) := f(a, b)
26412@end example
26413
26414@noindent
26415which would do a completely strict match for the pattern.
26416
26417By contrast, the @code{quote} marker means that not only the
26418function name but also the arguments must be literally the same.
26419The above pattern will match @samp{x - x y} but
26420
26421@example
26422quote(a - a b) := f(a, b)
26423@end example
26424
26425@noindent
26426will match only the single formula @samp{a - a b}. Also,
26427
26428@example
26429quote(a - quote(a b)) := f(a, b)
26430@end example
26431
26432@noindent
26433will match only @samp{a - quote(a b)}---probably not the desired
26434effect!
26435
26436A certain amount of algebra is also done when substituting the
26437meta-variables on the righthand side of a rule. For example,
26438in the rule
26439
26440@example
26441a + f(b) := f(a + b)
26442@end example
26443
26444@noindent
26445matching @samp{f(x) - y} would produce @samp{f((-y) + x)} if
26446taken literally, but the rewrite mechanism will simplify the
26447righthand side to @samp{f(x - y)} automatically. (Of course,
26448the default simplifications would do this anyway, so this
26449special simplification is only noticeable if you have turned the
26450default simplifications off.) This rewriting is done only when
26451a meta-variable expands to a ``negative-looking'' expression.
26452If this simplification is not desirable, you can use a @code{plain}
26453marker on the righthand side:
26454
26455@example
26456a + f(b) := f(plain(a + b))
26457@end example
26458
26459@noindent
26460In this example, we are still allowing the pattern-matcher to
26461use all the algebra it can muster, but the righthand side will
26462always simplify to a literal addition like @samp{f((-y) + x)}.
26463
26464@node Other Features of Rewrite Rules, Composing Patterns in Rewrite Rules, Algebraic Properties of Rewrite Rules, Rewrite Rules
26465@subsection Other Features of Rewrite Rules
26466
26467@noindent
26468Certain ``function names'' serve as markers in rewrite rules.
26469Here is a complete list of these markers. First are listed the
26470markers that work inside a pattern; then come the markers that
26471work in the righthand side of a rule.
26472
26473@ignore
26474@starindex
26475@end ignore
26476@tindex import
26477One kind of marker, @samp{import(x)}, takes the place of a whole
26478rule. Here @expr{x} is the name of a variable containing another
26479rule set; those rules are ``spliced into'' the rule set that
26480imports them. For example, if @samp{[f(a+b) := f(a) + f(b),
26481f(a b) := a f(b) :: real(a)]} is stored in variable @samp{linearF},
26482then the rule set @samp{[f(0) := 0, import(linearF)]} will apply
26483all three rules. It is possible to modify the imported rules
26484slightly: @samp{import(x, v1, x1, v2, x2, @dots{})} imports
40ba43b4 26485the rule set @expr{x} with all occurrences of
4009494e 26486@texline @math{v_1},
40ba43b4
PE
26487@infoline @expr{v1},
26488as either a variable name or a function name, replaced with
4009494e 26489@texline @math{x_1}
40ba43b4
PE
26490@infoline @expr{x1}
26491and so on. (If
4009494e 26492@texline @math{v_1}
40ba43b4
PE
26493@infoline @expr{v1}
26494is used as a function name, then
4009494e
GM
26495@texline @math{x_1}
26496@infoline @expr{x1}
26497must be either a function name itself or a @w{@samp{< >}} nameless
26498function; @pxref{Specifying Operators}.) For example, @samp{[g(0) := 0,
26499import(linearF, f, g)]} applies the linearity rules to the function
26500@samp{g} instead of @samp{f}. Imports can be nested, but the
26501import-with-renaming feature may fail to rename sub-imports properly.
26502
26503The special functions allowed in patterns are:
26504
26505@table @samp
26506@item quote(x)
26507@ignore
26508@starindex
26509@end ignore
26510@tindex quote
26511This pattern matches exactly @expr{x}; variable names in @expr{x} are
26512not interpreted as meta-variables. The only flexibility is that
26513numbers are compared for numeric equality, so that the pattern
26514@samp{f(quote(12))} will match both @samp{f(12)} and @samp{f(12.0)}.
26515(Numbers are always treated this way by the rewrite mechanism:
26516The rule @samp{f(x,x) := g(x)} will match @samp{f(12, 12.0)}.
26517The rewrite may produce either @samp{g(12)} or @samp{g(12.0)}
26518as a result in this case.)
26519
26520@item plain(x)
26521@ignore
26522@starindex
26523@end ignore
26524@tindex plain
26525Here @expr{x} must be a function call @samp{f(x1,x2,@dots{})}. This
26526pattern matches a call to function @expr{f} with the specified
26527argument patterns. No special knowledge of the properties of the
26528function @expr{f} is used in this case; @samp{+} is not commutative or
26529associative. Unlike @code{quote}, the arguments @samp{x1,x2,@dots{}}
26530are treated as patterns. If you wish them to be treated ``plainly''
26531as well, you must enclose them with more @code{plain} markers:
26532@samp{plain(plain(@w{-a}) + plain(b c))}.
26533
26534@item opt(x,def)
26535@ignore
26536@starindex
26537@end ignore
26538@tindex opt
26539Here @expr{x} must be a variable name. This must appear as an
26540argument to a function or an element of a vector; it specifies that
26541the argument or element is optional.
26542As an argument to @samp{+}, @samp{-}, @samp{*}, @samp{&&}, or @samp{||},
26543or as the second argument to @samp{/} or @samp{^}, the value @var{def}
26544may be omitted. The pattern @samp{x + opt(y)} matches a sum by
26545binding one summand to @expr{x} and the other to @expr{y}, and it
26546matches anything else by binding the whole expression to @expr{x} and
26547zero to @expr{y}. The other operators above work similarly.
26548
26549For general miscellaneous functions, the default value @code{def}
26550must be specified. Optional arguments are dropped starting with
26551the rightmost one during matching. For example, the pattern
26552@samp{f(opt(a,0), b, opt(c,b))} will match @samp{f(b)}, @samp{f(a,b)},
26553or @samp{f(a,b,c)}. Default values of zero and @expr{b} are
26554supplied in this example for the omitted arguments. Note that
26555the literal variable @expr{b} will be the default in the latter
26556case, @emph{not} the value that matched the meta-variable @expr{b}.
26557In other words, the default @var{def} is effectively quoted.
26558
26559@item condition(x,c)
26560@ignore
26561@starindex
26562@end ignore
26563@tindex condition
26564@tindex ::
26565This matches the pattern @expr{x}, with the attached condition
26566@expr{c}. It is the same as @samp{x :: c}.
26567
26568@item pand(x,y)
26569@ignore
26570@starindex
26571@end ignore
26572@tindex pand
26573@tindex &&&
26574This matches anything that matches both pattern @expr{x} and
26575pattern @expr{y}. It is the same as @samp{x &&& y}.
26576@pxref{Composing Patterns in Rewrite Rules}.
26577
26578@item por(x,y)
26579@ignore
26580@starindex
26581@end ignore
26582@tindex por
26583@tindex |||
26584This matches anything that matches either pattern @expr{x} or
26585pattern @expr{y}. It is the same as @w{@samp{x ||| y}}.
26586
26587@item pnot(x)
26588@ignore
26589@starindex
26590@end ignore
26591@tindex pnot
26592@tindex !!!
26593This matches anything that does not match pattern @expr{x}.
26594It is the same as @samp{!!! x}.
26595
26596@item cons(h,t)
26597@ignore
26598@mindex cons
26599@end ignore
26600@tindex cons (rewrites)
26601This matches any vector of one or more elements. The first
26602element is matched to @expr{h}; a vector of the remaining
26603elements is matched to @expr{t}. Note that vectors of fixed
26604length can also be matched as actual vectors: The rule
26605@samp{cons(a,cons(b,[])) := cons(a+b,[])} is equivalent
26606to the rule @samp{[a,b] := [a+b]}.
26607
26608@item rcons(t,h)
26609@ignore
26610@mindex rcons
26611@end ignore
26612@tindex rcons (rewrites)
26613This is like @code{cons}, except that the @emph{last} element
26614is matched to @expr{h}, with the remaining elements matched
26615to @expr{t}.
26616
26617@item apply(f,args)
26618@ignore
26619@mindex apply
26620@end ignore
26621@tindex apply (rewrites)
26622This matches any function call. The name of the function, in
26623the form of a variable, is matched to @expr{f}. The arguments
26624of the function, as a vector of zero or more objects, are
26625matched to @samp{args}. Constants, variables, and vectors
26626do @emph{not} match an @code{apply} pattern. For example,
26627@samp{apply(f,x)} matches any function call, @samp{apply(quote(f),x)}
26628matches any call to the function @samp{f}, @samp{apply(f,[a,b])}
26629matches any function call with exactly two arguments, and
26630@samp{apply(quote(f), cons(a,cons(b,x)))} matches any call
26631to the function @samp{f} with two or more arguments. Another
26632way to implement the latter, if the rest of the rule does not
26633need to refer to the first two arguments of @samp{f} by name,
26634would be @samp{apply(quote(f), x :: vlen(x) >= 2)}.
26635Here's a more interesting sample use of @code{apply}:
26636
26637@example
26638apply(f,[x+n]) := n + apply(f,[x])
26639 :: in(f, [floor,ceil,round,trunc]) :: integer(n)
26640@end example
26641
26642Note, however, that this will be slower to match than a rule
26643set with four separate rules. The reason is that Calc sorts
26644the rules of a rule set according to top-level function name;
26645if the top-level function is @code{apply}, Calc must try the
26646rule for every single formula and sub-formula. If the top-level
26647function in the pattern is, say, @code{floor}, then Calc invokes
26648the rule only for sub-formulas which are calls to @code{floor}.
26649
26650Formulas normally written with operators like @code{+} are still
26651considered function calls: @code{apply(f,x)} matches @samp{a+b}
26652with @samp{f = add}, @samp{x = [a,b]}.
26653
26654You must use @code{apply} for meta-variables with function names
26655on both sides of a rewrite rule: @samp{apply(f, [x]) := f(x+1)}
26656is @emph{not} correct, because it rewrites @samp{spam(6)} into
26657@samp{f(7)}. The righthand side should be @samp{apply(f, [x+1])}.
26658Also note that you will have to use No-Simplify mode (@kbd{m O})
26659when entering this rule so that the @code{apply} isn't
26660evaluated immediately to get the new rule @samp{f(x) := f(x+1)}.
26661Or, use @kbd{s e} to enter the rule without going through the stack,
26662or enter the rule as @samp{apply(f, [x]) := apply(f, [x+1]) @w{:: 1}}.
26663@xref{Conditional Rewrite Rules}.
26664
26665@item select(x)
26666@ignore
26667@starindex
26668@end ignore
26669@tindex select
26670This is used for applying rules to formulas with selections;
26671@pxref{Selections with Rewrite Rules}.
26672@end table
26673
26674Special functions for the righthand sides of rules are:
26675
26676@table @samp
26677@item quote(x)
26678The notation @samp{quote(x)} is changed to @samp{x} when the
26679righthand side is used. As far as the rewrite rule is concerned,
26680@code{quote} is invisible. However, @code{quote} has the special
26681property in Calc that its argument is not evaluated. Thus,
26682while it will not work to put the rule @samp{t(a) := typeof(a)}
26683on the stack because @samp{typeof(a)} is evaluated immediately
26684to produce @samp{t(a) := 100}, you can use @code{quote} to
26685protect the righthand side: @samp{t(a) := quote(typeof(a))}.
26686(@xref{Conditional Rewrite Rules}, for another trick for
26687protecting rules from evaluation.)
26688
26689@item plain(x)
26690Special properties of and simplifications for the function call
26691@expr{x} are not used. One interesting case where @code{plain}
26692is useful is the rule, @samp{q(x) := quote(x)}, trying to expand a
26693shorthand notation for the @code{quote} function. This rule will
26694not work as shown; instead of replacing @samp{q(foo)} with
26695@samp{quote(foo)}, it will replace it with @samp{foo}! The correct
26696rule would be @samp{q(x) := plain(quote(x))}.
26697
26698@item cons(h,t)
26699Where @expr{t} is a vector, this is converted into an expanded
26700vector during rewrite processing. Note that @code{cons} is a regular
26701Calc function which normally does this anyway; the only way @code{cons}
26702is treated specially by rewrites is that @code{cons} on the righthand
26703side of a rule will be evaluated even if default simplifications
26704have been turned off.
26705
26706@item rcons(t,h)
26707Analogous to @code{cons} except putting @expr{h} at the @emph{end} of
26708the vector @expr{t}.
26709
26710@item apply(f,args)
26711Where @expr{f} is a variable and @var{args} is a vector, this
26712is converted to a function call. Once again, note that @code{apply}
26713is also a regular Calc function.
26714
26715@item eval(x)
26716@ignore
26717@starindex
26718@end ignore
26719@tindex eval
26720The formula @expr{x} is handled in the usual way, then the
26721default simplifications are applied to it even if they have
26722been turned off normally. This allows you to treat any function
26723similarly to the way @code{cons} and @code{apply} are always
26724treated. However, there is a slight difference: @samp{cons(2+3, [])}
26725with default simplifications off will be converted to @samp{[2+3]},
26726whereas @samp{eval(cons(2+3, []))} will be converted to @samp{[5]}.
26727
26728@item evalsimp(x)
26729@ignore
26730@starindex
26731@end ignore
26732@tindex evalsimp
26733The formula @expr{x} has meta-variables substituted in the usual
8e7046c3 26734way, then algebraically simplified.
4009494e
GM
26735
26736@item evalextsimp(x)
26737@ignore
26738@starindex
26739@end ignore
26740@tindex evalextsimp
26741The formula @expr{x} has meta-variables substituted in the normal
26742way, then ``extendedly'' simplified as if by the @kbd{a e} command.
26743
26744@item select(x)
26745@xref{Selections with Rewrite Rules}.
26746@end table
26747
26748There are also some special functions you can use in conditions.
26749
26750@table @samp
26751@item let(v := x)
26752@ignore
26753@starindex
26754@end ignore
26755@tindex let
26756The expression @expr{x} is evaluated with meta-variables substituted.
8e7046c3 26757The algebraic simplifications are @emph{not} applied by
4009494e
GM
26758default, but @expr{x} can include calls to @code{evalsimp} or
26759@code{evalextsimp} as described above to invoke higher levels
8e7046c3
JB
26760of simplification. The result of @expr{x} is then bound to the
26761meta-variable @expr{v}. As usual, if this meta-variable has already
26762been matched to something else the two values must be equal; if the
26763meta-variable is new then it is bound to the result of the expression.
26764This variable can then appear in later conditions, and on the righthand
26765side of the rule.
4009494e
GM
26766In fact, @expr{v} may be any pattern in which case the result of
26767evaluating @expr{x} is matched to that pattern, binding any
26768meta-variables that appear in that pattern. Note that @code{let}
26769can only appear by itself as a condition, or as one term of an
26770@samp{&&} which is a whole condition: It cannot be inside
26771an @samp{||} term or otherwise buried.
26772
26773The alternate, equivalent form @samp{let(v, x)} is also recognized.
26774Note that the use of @samp{:=} by @code{let}, while still being
26775assignment-like in character, is unrelated to the use of @samp{:=}
26776in the main part of a rewrite rule.
26777
26778As an example, @samp{f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)}
26779replaces @samp{f(a)} with @samp{g} of the inverse of @samp{a}, if
26780that inverse exists and is constant. For example, if @samp{a} is a
26781singular matrix the operation @samp{1/a} is left unsimplified and
26782@samp{constant(ia)} fails, but if @samp{a} is an invertible matrix
26783then the rule succeeds. Without @code{let} there would be no way
26784to express this rule that didn't have to invert the matrix twice.
26785Note that, because the meta-variable @samp{ia} is otherwise unbound
26786in this rule, the @code{let} condition itself always ``succeeds''
26787because no matter what @samp{1/a} evaluates to, it can successfully
26788be bound to @code{ia}.
26789
26790Here's another example, for integrating cosines of linear
26791terms: @samp{myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))}.
26792The @code{lin} function returns a 3-vector if its argument is linear,
26793or leaves itself unevaluated if not. But an unevaluated @code{lin}
26794call will not match the 3-vector on the lefthand side of the @code{let},
26795so this @code{let} both verifies that @code{y} is linear, and binds
26796the coefficients @code{a} and @code{b} for use elsewhere in the rule.
26797(It would have been possible to use @samp{sin(a x + b)/b} for the
26798righthand side instead, but using @samp{sin(y)/b} avoids gratuitous
26799rearrangement of the argument of the sine.)
26800
26801@ignore
26802@starindex
26803@end ignore
26804@tindex ierf
26805Similarly, here is a rule that implements an inverse-@code{erf}
26806function. It uses @code{root} to search for a solution. If
26807@code{root} succeeds, it will return a vector of two numbers
26808where the first number is the desired solution. If no solution
26809is found, @code{root} remains in symbolic form. So we use
26810@code{let} to check that the result was indeed a vector.
26811
26812@example
26813ierf(x) := y :: let([y,z] := root(erf(a) = x, a, .5))
26814@end example
26815
26816@item matches(v,p)
26817The meta-variable @var{v}, which must already have been matched
26818to something elsewhere in the rule, is compared against pattern
26819@var{p}. Since @code{matches} is a standard Calc function, it
26820can appear anywhere in a condition. But if it appears alone or
26821as a term of a top-level @samp{&&}, then you get the special
26822extra feature that meta-variables which are bound to things
26823inside @var{p} can be used elsewhere in the surrounding rewrite
26824rule.
26825
26826The only real difference between @samp{let(p := v)} and
26827@samp{matches(v, p)} is that the former evaluates @samp{v} using
26828the default simplifications, while the latter does not.
26829
26830@item remember
26831@vindex remember
26832This is actually a variable, not a function. If @code{remember}
26833appears as a condition in a rule, then when that rule succeeds
26834the original expression and rewritten expression are added to the
26835front of the rule set that contained the rule. If the rule set
26836was not stored in a variable, @code{remember} is ignored. The
26837lefthand side is enclosed in @code{quote} in the added rule if it
26838contains any variables.
26839
26840For example, the rule @samp{f(n) := n f(n-1) :: remember} applied
26841to @samp{f(7)} will add the rule @samp{f(7) := 7 f(6)} to the front
26842of the rule set. The rule set @code{EvalRules} works slightly
26843differently: There, the evaluation of @samp{f(6)} will complete before
26844the result is added to the rule set, in this case as @samp{f(7) := 5040}.
26845Thus @code{remember} is most useful inside @code{EvalRules}.
26846
26847It is up to you to ensure that the optimization performed by
26848@code{remember} is safe. For example, the rule @samp{foo(n) := n
26849:: evalv(eatfoo) > 0 :: remember} is a bad idea (@code{evalv} is
26850the function equivalent of the @kbd{=} command); if the variable
26851@code{eatfoo} ever contains 1, rules like @samp{foo(7) := 7} will
26852be added to the rule set and will continue to operate even if
26853@code{eatfoo} is later changed to 0.
26854
26855@item remember(c)
26856@ignore
26857@starindex
26858@end ignore
26859@tindex remember
26860Remember the match as described above, but only if condition @expr{c}
26861is true. For example, @samp{remember(n % 4 = 0)} in the above factorial
26862rule remembers only every fourth result. Note that @samp{remember(1)}
26863is equivalent to @samp{remember}, and @samp{remember(0)} has no effect.
26864@end table
26865
26866@node Composing Patterns in Rewrite Rules, Nested Formulas with Rewrite Rules, Other Features of Rewrite Rules, Rewrite Rules
26867@subsection Composing Patterns in Rewrite Rules
26868
26869@noindent
26870There are three operators, @samp{&&&}, @samp{|||}, and @samp{!!!},
26871that combine rewrite patterns to make larger patterns. The
26872combinations are ``and,'' ``or,'' and ``not,'' respectively, and
26873these operators are the pattern equivalents of @samp{&&}, @samp{||}
26874and @samp{!} (which operate on zero-or-nonzero logical values).
26875
26876Note that @samp{&&&}, @samp{|||}, and @samp{!!!} are left in symbolic
26877form by all regular Calc features; they have special meaning only in
26878the context of rewrite rule patterns.
26879
26880The pattern @samp{@var{p1} &&& @var{p2}} matches anything that
26881matches both @var{p1} and @var{p2}. One especially useful case is
26882when one of @var{p1} or @var{p2} is a meta-variable. For example,
26883here is a rule that operates on error forms:
26884
26885@example
26886f(x &&& a +/- b, x) := g(x)
26887@end example
26888
26889This does the same thing, but is arguably simpler than, the rule
26890
26891@example
26892f(a +/- b, a +/- b) := g(a +/- b)
26893@end example
26894
26895@ignore
26896@starindex
26897@end ignore
26898@tindex ends
26899Here's another interesting example:
26900
26901@example
26902ends(cons(a, x) &&& rcons(y, b)) := [a, b]
26903@end example
26904
26905@noindent
26906which effectively clips out the middle of a vector leaving just
26907the first and last elements. This rule will change a one-element
26908vector @samp{[a]} to @samp{[a, a]}. The similar rule
26909
26910@example
26911ends(cons(a, rcons(y, b))) := [a, b]
26912@end example
26913
26914@noindent
26915would do the same thing except that it would fail to match a
26916one-element vector.
26917
26918@tex
26919\bigskip
26920@end tex
26921
26922The pattern @samp{@var{p1} ||| @var{p2}} matches anything that
26923matches either @var{p1} or @var{p2}. Calc first tries matching
26924against @var{p1}; if that fails, it goes on to try @var{p2}.
26925
26926@ignore
26927@starindex
26928@end ignore
26929@tindex curve
26930A simple example of @samp{|||} is
26931
26932@example
26933curve(inf ||| -inf) := 0
26934@end example
26935
26936@noindent
26937which converts both @samp{curve(inf)} and @samp{curve(-inf)} to zero.
26938
26939Here is a larger example:
26940
26941@example
26942log(a, b) ||| (ln(a) :: let(b := e)) := mylog(a, b)
26943@end example
26944
26945This matches both generalized and natural logarithms in a single rule.
26946Note that the @samp{::} term must be enclosed in parentheses because
26947that operator has lower precedence than @samp{|||} or @samp{:=}.
26948
26949(In practice this rule would probably include a third alternative,
26950omitted here for brevity, to take care of @code{log10}.)
26951
26952While Calc generally treats interior conditions exactly the same as
26953conditions on the outside of a rule, it does guarantee that if all the
26954variables in the condition are special names like @code{e}, or already
26955bound in the pattern to which the condition is attached (say, if
26956@samp{a} had appeared in this condition), then Calc will process this
26957condition right after matching the pattern to the left of the @samp{::}.
26958Thus, we know that @samp{b} will be bound to @samp{e} only if the
26959@code{ln} branch of the @samp{|||} was taken.
26960
26961Note that this rule was careful to bind the same set of meta-variables
26962on both sides of the @samp{|||}. Calc does not check this, but if
26963you bind a certain meta-variable only in one branch and then use that
26964meta-variable elsewhere in the rule, results are unpredictable:
26965
26966@example
26967f(a,b) ||| g(b) := h(a,b)
26968@end example
26969
26970Here if the pattern matches @samp{g(17)}, Calc makes no promises about
26971the value that will be substituted for @samp{a} on the righthand side.
26972
26973@tex
26974\bigskip
26975@end tex
26976
26977The pattern @samp{!!! @var{pat}} matches anything that does not
26978match @var{pat}. Any meta-variables that are bound while matching
26979@var{pat} remain unbound outside of @var{pat}.
26980
26981For example,
26982
26983@example
26984f(x &&& !!! a +/- b, !!![]) := g(x)
26985@end example
26986
26987@noindent
26988converts @code{f} whose first argument is anything @emph{except} an
26989error form, and whose second argument is not the empty vector, into
26990a similar call to @code{g} (but without the second argument).
26991
26992If we know that the second argument will be a vector (empty or not),
26993then an equivalent rule would be:
26994
26995@example
26996f(x, y) := g(x) :: typeof(x) != 7 :: vlen(y) > 0
26997@end example
26998
26999@noindent
27000where of course 7 is the @code{typeof} code for error forms.
27001Another final condition, that works for any kind of @samp{y},
27002would be @samp{!istrue(y == [])}. (The @code{istrue} function
27003returns an explicit 0 if its argument was left in symbolic form;
27004plain @samp{!(y == [])} or @samp{y != []} would not work to replace
27005@samp{!!![]} since these would be left unsimplified, and thus cause
27006the rule to fail, if @samp{y} was something like a variable name.)
27007
27008It is possible for a @samp{!!!} to refer to meta-variables bound
27009elsewhere in the pattern. For example,
27010
27011@example
27012f(a, !!!a) := g(a)
27013@end example
27014
27015@noindent
27016matches any call to @code{f} with different arguments, changing
27017this to @code{g} with only the first argument.
27018
27019If a function call is to be matched and one of the argument patterns
27020contains a @samp{!!!} somewhere inside it, that argument will be
27021matched last. Thus
27022
27023@example
27024f(!!!a, a) := g(a)
27025@end example
27026
27027@noindent
27028will be careful to bind @samp{a} to the second argument of @code{f}
27029before testing the first argument. If Calc had tried to match the
27030first argument of @code{f} first, the results would have been
27031disastrous: since @code{a} was unbound so far, the pattern @samp{a}
27032would have matched anything at all, and the pattern @samp{!!!a}
27033therefore would @emph{not} have matched anything at all!
27034
27035@node Nested Formulas with Rewrite Rules, Multi-Phase Rewrite Rules, Composing Patterns in Rewrite Rules, Rewrite Rules
27036@subsection Nested Formulas with Rewrite Rules
27037
27038@noindent
27039When @kbd{a r} (@code{calc-rewrite}) is used, it takes an expression from
27040the top of the stack and attempts to match any of the specified rules
27041to any part of the expression, starting with the whole expression
27042and then, if that fails, trying deeper and deeper sub-expressions.
27043For each part of the expression, the rules are tried in the order
27044they appear in the rules vector. The first rule to match the first
27045sub-expression wins; it replaces the matched sub-expression according
27046to the @var{new} part of the rule.
27047
27048Often, the rule set will match and change the formula several times.
27049The top-level formula is first matched and substituted repeatedly until
27050it no longer matches the pattern; then, sub-formulas are tried, and
27051so on. Once every part of the formula has gotten its chance, the
27052rewrite mechanism starts over again with the top-level formula
27053(in case a substitution of one of its arguments has caused it again
27054to match). This continues until no further matches can be made
27055anywhere in the formula.
27056
27057It is possible for a rule set to get into an infinite loop. The
27058most obvious case, replacing a formula with itself, is not a problem
27059because a rule is not considered to ``succeed'' unless the righthand
27060side actually comes out to something different than the original
27061formula or sub-formula that was matched. But if you accidentally
27062had both @samp{ln(a b) := ln(a) + ln(b)} and the reverse
27063@samp{ln(a) + ln(b) := ln(a b)} in your rule set, Calc would
27064run forever switching a formula back and forth between the two
27065forms.
27066
27067To avoid disaster, Calc normally stops after 100 changes have been
27068made to the formula. This will be enough for most multiple rewrites,
27069but it will keep an endless loop of rewrites from locking up the
27070computer forever. (On most systems, you can also type @kbd{C-g} to
27071halt any Emacs command prematurely.)
27072
27073To change this limit, give a positive numeric prefix argument.
27074In particular, @kbd{M-1 a r} applies only one rewrite at a time,
27075useful when you are first testing your rule (or just if repeated
27076rewriting is not what is called for by your application).
27077
27078@ignore
27079@starindex
27080@end ignore
27081@ignore
27082@mindex iter@idots
27083@end ignore
27084@tindex iterations
27085You can also put a ``function call'' @samp{iterations(@var{n})}
27086in place of a rule anywhere in your rules vector (but usually at
27087the top). Then, @var{n} will be used instead of 100 as the default
27088number of iterations for this rule set. You can use
27089@samp{iterations(inf)} if you want no iteration limit by default.
27090A prefix argument will override the @code{iterations} limit in the
27091rule set.
27092
27093@example
27094[ iterations(1),
27095 f(x) := f(x+1) ]
27096@end example
27097
27098More precisely, the limit controls the number of ``iterations,''
27099where each iteration is a successful matching of a rule pattern whose
27100righthand side, after substituting meta-variables and applying the
27101default simplifications, is different from the original sub-formula
27102that was matched.
27103
27104A prefix argument of zero sets the limit to infinity. Use with caution!
27105
27106Given a negative numeric prefix argument, @kbd{a r} will match and
27107substitute the top-level expression up to that many times, but
27108will not attempt to match the rules to any sub-expressions.
27109
27110In a formula, @code{rewrite(@var{expr}, @var{rules}, @var{n})}
27111does a rewriting operation. Here @var{expr} is the expression
27112being rewritten, @var{rules} is the rule, vector of rules, or
27113variable containing the rules, and @var{n} is the optional
27114iteration limit, which may be a positive integer, a negative
27115integer, or @samp{inf} or @samp{-inf}. If @var{n} is omitted
27116the @code{iterations} value from the rule set is used; if both
27117are omitted, 100 is used.
27118
27119@node Multi-Phase Rewrite Rules, Selections with Rewrite Rules, Nested Formulas with Rewrite Rules, Rewrite Rules
27120@subsection Multi-Phase Rewrite Rules
27121
27122@noindent
27123It is possible to separate a rewrite rule set into several @dfn{phases}.
27124During each phase, certain rules will be enabled while certain others
27125will be disabled. A @dfn{phase schedule} controls the order in which
27126phases occur during the rewriting process.
27127
27128@ignore
27129@starindex
27130@end ignore
27131@tindex phase
27132@vindex all
27133If a call to the marker function @code{phase} appears in the rules
27134vector in place of a rule, all rules following that point will be
27135members of the phase(s) identified in the arguments to @code{phase}.
27136Phases are given integer numbers. The markers @samp{phase()} and
27137@samp{phase(all)} both mean the following rules belong to all phases;
27138this is the default at the start of the rule set.
27139
27140If you do not explicitly schedule the phases, Calc sorts all phase
27141numbers that appear in the rule set and executes the phases in
27142ascending order. For example, the rule set
27143
27144@example
27145@group
27146[ f0(x) := g0(x),
27147 phase(1),
27148 f1(x) := g1(x),
27149 phase(2),
27150 f2(x) := g2(x),
27151 phase(3),
27152 f3(x) := g3(x),
27153 phase(1,2),
27154 f4(x) := g4(x) ]
27155@end group
27156@end example
27157
27158@noindent
27159has three phases, 1 through 3. Phase 1 consists of the @code{f0},
27160@code{f1}, and @code{f4} rules (in that order). Phase 2 consists of
27161@code{f0}, @code{f2}, and @code{f4}. Phase 3 consists of @code{f0}
27162and @code{f3}.
27163
27164When Calc rewrites a formula using this rule set, it first rewrites
27165the formula using only the phase 1 rules until no further changes are
27166possible. Then it switches to the phase 2 rule set and continues
27167until no further changes occur, then finally rewrites with phase 3.
27168When no more phase 3 rules apply, rewriting finishes. (This is
27169assuming @kbd{a r} with a large enough prefix argument to allow the
27170rewriting to run to completion; the sequence just described stops
27171early if the number of iterations specified in the prefix argument,
27172100 by default, is reached.)
27173
27174During each phase, Calc descends through the nested levels of the
27175formula as described previously. (@xref{Nested Formulas with Rewrite
27176Rules}.) Rewriting starts at the top of the formula, then works its
27177way down to the parts, then goes back to the top and works down again.
27178The phase 2 rules do not begin until no phase 1 rules apply anywhere
27179in the formula.
27180
27181@ignore
27182@starindex
27183@end ignore
27184@tindex schedule
27185A @code{schedule} marker appearing in the rule set (anywhere, but
27186conventionally at the top) changes the default schedule of phases.
27187In the simplest case, @code{schedule} has a sequence of phase numbers
27188for arguments; each phase number is invoked in turn until the
27189arguments to @code{schedule} are exhausted. Thus adding
27190@samp{schedule(3,2,1)} at the top of the above rule set would
27191reverse the order of the phases; @samp{schedule(1,2,3)} would have
27192no effect since this is the default schedule; and @samp{schedule(1,2,1,3)}
27193would give phase 1 a second chance after phase 2 has completed, before
27194moving on to phase 3.
27195
27196Any argument to @code{schedule} can instead be a vector of phase
27197numbers (or even of sub-vectors). Then the sub-sequence of phases
27198described by the vector are tried repeatedly until no change occurs
27199in any phase in the sequence. For example, @samp{schedule([1, 2], 3)}
27200tries phase 1, then phase 2, then, if either phase made any changes
27201to the formula, repeats these two phases until they can make no
27202further progress. Finally, it goes on to phase 3 for finishing
27203touches.
27204
27205Also, items in @code{schedule} can be variable names as well as
27206numbers. A variable name is interpreted as the name of a function
27207to call on the whole formula. For example, @samp{schedule(1, simplify)}
27208says to apply the phase-1 rules (presumably, all of them), then to
27209call @code{simplify} which is the function name equivalent of @kbd{a s}.
27210Likewise, @samp{schedule([1, simplify])} says to alternate between
27211phase 1 and @kbd{a s} until no further changes occur.
27212
27213Phases can be used purely to improve efficiency; if it is known that
27214a certain group of rules will apply only at the beginning of rewriting,
27215and a certain other group will apply only at the end, then rewriting
27216will be faster if these groups are identified as separate phases.
27217Once the phase 1 rules are done, Calc can put them aside and no longer
27218spend any time on them while it works on phase 2.
27219
27220There are also some problems that can only be solved with several
27221rewrite phases. For a real-world example of a multi-phase rule set,
27222examine the set @code{FitRules}, which is used by the curve-fitting
27223command to convert a model expression to linear form.
27224@xref{Curve Fitting Details}. This set is divided into four phases.
27225The first phase rewrites certain kinds of expressions to be more
27226easily linearizable, but less computationally efficient. After the
27227linear components have been picked out, the final phase includes the
27228opposite rewrites to put each component back into an efficient form.
27229If both sets of rules were included in one big phase, Calc could get
27230into an infinite loop going back and forth between the two forms.
27231
27232Elsewhere in @code{FitRules}, the components are first isolated,
27233then recombined where possible to reduce the complexity of the linear
27234fit, then finally packaged one component at a time into vectors.
27235If the packaging rules were allowed to begin before the recombining
27236rules were finished, some components might be put away into vectors
27237before they had a chance to recombine. By putting these rules in
27238two separate phases, this problem is neatly avoided.
27239
27240@node Selections with Rewrite Rules, Matching Commands, Multi-Phase Rewrite Rules, Rewrite Rules
27241@subsection Selections with Rewrite Rules
27242
27243@noindent
27244If a sub-formula of the current formula is selected (as by @kbd{j s};
27245@pxref{Selecting Subformulas}), the @kbd{a r} (@code{calc-rewrite})
27246command applies only to that sub-formula. Together with a negative
27247prefix argument, you can use this fact to apply a rewrite to one
27248specific part of a formula without affecting any other parts.
27249
27250@kindex j r
27251@pindex calc-rewrite-selection
27252The @kbd{j r} (@code{calc-rewrite-selection}) command allows more
27253sophisticated operations on selections. This command prompts for
27254the rules in the same way as @kbd{a r}, but it then applies those
27255rules to the whole formula in question even though a sub-formula
27256of it has been selected. However, the selected sub-formula will
27257first have been surrounded by a @samp{select( )} function call.
27258(Calc's evaluator does not understand the function name @code{select};
27259this is only a tag used by the @kbd{j r} command.)
27260
27261For example, suppose the formula on the stack is @samp{2 (a + b)^2}
27262and the sub-formula @samp{a + b} is selected. This formula will
27263be rewritten to @samp{2 select(a + b)^2} and then the rewrite
27264rules will be applied in the usual way. The rewrite rules can
27265include references to @code{select} to tell where in the pattern
27266the selected sub-formula should appear.
27267
27268If there is still exactly one @samp{select( )} function call in
27269the formula after rewriting is done, it indicates which part of
27270the formula should be selected afterwards. Otherwise, the
27271formula will be unselected.
27272
27273You can make @kbd{j r} act much like @kbd{a r} by enclosing both parts
27274of the rewrite rule with @samp{select()}. However, @kbd{j r}
27275allows you to use the current selection in more flexible ways.
27276Suppose you wished to make a rule which removed the exponent from
27277the selected term; the rule @samp{select(a)^x := select(a)} would
27278work. In the above example, it would rewrite @samp{2 select(a + b)^2}
27279to @samp{2 select(a + b)}. This would then be returned to the
27280stack as @samp{2 (a + b)} with the @samp{a + b} selected.
27281
27282The @kbd{j r} command uses one iteration by default, unlike
27283@kbd{a r} which defaults to 100 iterations. A numeric prefix
27284argument affects @kbd{j r} in the same way as @kbd{a r}.
27285@xref{Nested Formulas with Rewrite Rules}.
27286
27287As with other selection commands, @kbd{j r} operates on the stack
27288entry that contains the cursor. (If the cursor is on the top-of-stack
27289@samp{.} marker, it works as if the cursor were on the formula
27290at stack level 1.)
27291
27292If you don't specify a set of rules, the rules are taken from the
27293top of the stack, just as with @kbd{a r}. In this case, the
27294cursor must indicate stack entry 2 or above as the formula to be
27295rewritten (otherwise the same formula would be used as both the
27296target and the rewrite rules).
27297
27298If the indicated formula has no selection, the cursor position within
27299the formula temporarily selects a sub-formula for the purposes of this
27300command. If the cursor is not on any sub-formula (e.g., it is in
27301the line-number area to the left of the formula), the @samp{select( )}
27302markers are ignored by the rewrite mechanism and the rules are allowed
27303to apply anywhere in the formula.
27304
27305As a special feature, the normal @kbd{a r} command also ignores
27306@samp{select( )} calls in rewrite rules. For example, if you used the
27307above rule @samp{select(a)^x := select(a)} with @kbd{a r}, it would apply
27308the rule as if it were @samp{a^x := a}. Thus, you can write general
27309purpose rules with @samp{select( )} hints inside them so that they
27310will ``do the right thing'' in both @kbd{a r} and @kbd{j r},
27311both with and without selections.
27312
27313@node Matching Commands, Automatic Rewrites, Selections with Rewrite Rules, Rewrite Rules
27314@subsection Matching Commands
27315
27316@noindent
27317@kindex a m
27318@pindex calc-match
27319@tindex match
27320The @kbd{a m} (@code{calc-match}) [@code{match}] function takes a
27321vector of formulas and a rewrite-rule-style pattern, and produces
27322a vector of all formulas which match the pattern. The command
27323prompts you to enter the pattern; as for @kbd{a r}, you can enter
27324a single pattern (i.e., a formula with meta-variables), or a
27325vector of patterns, or a variable which contains patterns, or
27326you can give a blank response in which case the patterns are taken
27327from the top of the stack. The pattern set will be compiled once
27328and saved if it is stored in a variable. If there are several
27329patterns in the set, vector elements are kept if they match any
27330of the patterns.
27331
27332For example, @samp{match(a+b, [x, x+y, x-y, 7, x+y+z])}
27333will return @samp{[x+y, x-y, x+y+z]}.
27334
27335The @code{import} mechanism is not available for pattern sets.
27336
27337The @kbd{a m} command can also be used to extract all vector elements
27338which satisfy any condition: The pattern @samp{x :: x>0} will select
27339all the positive vector elements.
27340
27341@kindex I a m
27342@tindex matchnot
27343With the Inverse flag [@code{matchnot}], this command extracts all
27344vector elements which do @emph{not} match the given pattern.
27345
27346@ignore
27347@starindex
27348@end ignore
27349@tindex matches
27350There is also a function @samp{matches(@var{x}, @var{p})} which
27351evaluates to 1 if expression @var{x} matches pattern @var{p}, or
27352to 0 otherwise. This is sometimes useful for including into the
27353conditional clauses of other rewrite rules.
27354
27355@ignore
27356@starindex
27357@end ignore
27358@tindex vmatches
27359The function @code{vmatches} is just like @code{matches}, except
27360that if the match succeeds it returns a vector of assignments to
27361the meta-variables instead of the number 1. For example,
27362@samp{vmatches(f(1,2), f(a,b))} returns @samp{[a := 1, b := 2]}.
27363If the match fails, the function returns the number 0.
27364
27365@node Automatic Rewrites, Debugging Rewrites, Matching Commands, Rewrite Rules
27366@subsection Automatic Rewrites
27367
27368@noindent
27369@cindex @code{EvalRules} variable
27370@vindex EvalRules
27371It is possible to get Calc to apply a set of rewrite rules on all
27372results, effectively adding to the built-in set of default
27373simplifications. To do this, simply store your rule set in the
27374variable @code{EvalRules}. There is a convenient @kbd{s E} command
27375for editing @code{EvalRules}; @pxref{Operations on Variables}.
27376
27377For example, suppose you want @samp{sin(a + b)} to be expanded out
27378to @samp{sin(b) cos(a) + cos(b) sin(a)} wherever it appears, and
27379similarly for @samp{cos(a + b)}. The corresponding rewrite rule
27380set would be,
27381
27382@smallexample
27383@group
27384[ sin(a + b) := cos(a) sin(b) + sin(a) cos(b),
27385 cos(a + b) := cos(a) cos(b) - sin(a) sin(b) ]
27386@end group
27387@end smallexample
27388
27389To apply these manually, you could put them in a variable called
27390@code{trigexp} and then use @kbd{a r trigexp} every time you wanted
27391to expand trig functions. But if instead you store them in the
27392variable @code{EvalRules}, they will automatically be applied to all
27393sines and cosines of sums. Then, with @samp{2 x} and @samp{45} on
27394the stack, typing @kbd{+ S} will (assuming Degrees mode) result in
27395@samp{0.7071 sin(2 x) + 0.7071 cos(2 x)} automatically.
27396
27397As each level of a formula is evaluated, the rules from
27398@code{EvalRules} are applied before the default simplifications.
27399Rewriting continues until no further @code{EvalRules} apply.
27400Note that this is different from the usual order of application of
27401rewrite rules: @code{EvalRules} works from the bottom up, simplifying
27402the arguments to a function before the function itself, while @kbd{a r}
27403applies rules from the top down.
27404
27405Because the @code{EvalRules} are tried first, you can use them to
27406override the normal behavior of any built-in Calc function.
27407
27408It is important not to write a rule that will get into an infinite
27409loop. For example, the rule set @samp{[f(0) := 1, f(n) := n f(n-1)]}
27410appears to be a good definition of a factorial function, but it is
27411unsafe. Imagine what happens if @samp{f(2.5)} is simplified. Calc
27412will continue to subtract 1 from this argument forever without reaching
27413zero. A safer second rule would be @samp{f(n) := n f(n-1) :: n>0}.
27414Another dangerous rule is @samp{g(x, y) := g(y, x)}. Rewriting
27415@samp{g(2, 4)}, this would bounce back and forth between that and
27416@samp{g(4, 2)} forever. If an infinite loop in @code{EvalRules}
27417occurs, Emacs will eventually stop with a ``Computation got stuck
27418or ran too long'' message.
27419
27420Another subtle difference between @code{EvalRules} and regular rewrites
27421concerns rules that rewrite a formula into an identical formula. For
27422example, @samp{f(n) := f(floor(n))} ``fails to match'' when @expr{n} is
27423already an integer. But in @code{EvalRules} this case is detected only
27424if the righthand side literally becomes the original formula before any
27425further simplification. This means that @samp{f(n) := f(floor(n))} will
27426get into an infinite loop if it occurs in @code{EvalRules}. Calc will
27427replace @samp{f(6)} with @samp{f(floor(6))}, which is different from
27428@samp{f(6)}, so it will consider the rule to have matched and will
27429continue simplifying that formula; first the argument is simplified
27430to get @samp{f(6)}, then the rule matches again to get @samp{f(floor(6))}
27431again, ad infinitum. A much safer rule would check its argument first,
27432say, with @samp{f(n) := f(floor(n)) :: !dint(n)}.
27433
27434(What really happens is that the rewrite mechanism substitutes the
27435meta-variables in the righthand side of a rule, compares to see if the
27436result is the same as the original formula and fails if so, then uses
27437the default simplifications to simplify the result and compares again
27438(and again fails if the formula has simplified back to its original
27439form). The only special wrinkle for the @code{EvalRules} is that the
27440same rules will come back into play when the default simplifications
27441are used. What Calc wants to do is build @samp{f(floor(6))}, see that
27442this is different from the original formula, simplify to @samp{f(6)},
27443see that this is the same as the original formula, and thus halt the
27444rewriting. But while simplifying, @samp{f(6)} will again trigger
27445the same @code{EvalRules} rule and Calc will get into a loop inside
27446the rewrite mechanism itself.)
27447
27448The @code{phase}, @code{schedule}, and @code{iterations} markers do
27449not work in @code{EvalRules}. If the rule set is divided into phases,
27450only the phase 1 rules are applied, and the schedule is ignored.
27451The rules are always repeated as many times as possible.
27452
27453The @code{EvalRules} are applied to all function calls in a formula,
27454but not to numbers (and other number-like objects like error forms),
27455nor to vectors or individual variable names. (Though they will apply
27456to @emph{components} of vectors and error forms when appropriate.) You
27457might try to make a variable @code{phihat} which automatically expands
27458to its definition without the need to press @kbd{=} by writing the
27459rule @samp{quote(phihat) := (1-sqrt(5))/2}, but unfortunately this rule
27460will not work as part of @code{EvalRules}.
27461
27462Finally, another limitation is that Calc sometimes calls its built-in
27463functions directly rather than going through the default simplifications.
27464When it does this, @code{EvalRules} will not be able to override those
27465functions. For example, when you take the absolute value of the complex
27466number @expr{(2, 3)}, Calc computes @samp{sqrt(2*2 + 3*3)} by calling
27467the multiplication, addition, and square root functions directly rather
27468than applying the default simplifications to this formula. So an
27469@code{EvalRules} rule that (perversely) rewrites @samp{sqrt(13) := 6}
27470would not apply. (However, if you put Calc into Symbolic mode so that
27471@samp{sqrt(13)} will be left in symbolic form by the built-in square
27472root function, your rule will be able to apply. But if the complex
27473number were @expr{(3,4)}, so that @samp{sqrt(25)} must be calculated,
27474then Symbolic mode will not help because @samp{sqrt(25)} can be
27475evaluated exactly to 5.)
27476
27477One subtle restriction that normally only manifests itself with
27478@code{EvalRules} is that while a given rewrite rule is in the process
27479of being checked, that same rule cannot be recursively applied. Calc
27480effectively removes the rule from its rule set while checking the rule,
27481then puts it back once the match succeeds or fails. (The technical
27482reason for this is that compiled pattern programs are not reentrant.)
27483For example, consider the rule @samp{foo(x) := x :: foo(x/2) > 0}
27484attempting to match @samp{foo(8)}. This rule will be inactive while
27485the condition @samp{foo(4) > 0} is checked, even though it might be
27486an integral part of evaluating that condition. Note that this is not
27487a problem for the more usual recursive type of rule, such as
27488@samp{foo(x) := foo(x/2)}, because there the rule has succeeded and
27489been reactivated by the time the righthand side is evaluated.
27490
27491If @code{EvalRules} has no stored value (its default state), or if
27492anything but a vector is stored in it, then it is ignored.
27493
27494Even though Calc's rewrite mechanism is designed to compare rewrite
27495rules to formulas as quickly as possible, storing rules in
27496@code{EvalRules} may make Calc run substantially slower. This is
27497particularly true of rules where the top-level call is a commonly used
27498function, or is not fixed. The rule @samp{f(n) := n f(n-1) :: n>0} will
27499only activate the rewrite mechanism for calls to the function @code{f},
27500but @samp{lg(n) + lg(m) := lg(n m)} will check every @samp{+} operator.
27501
27502@smallexample
27503apply(f, [a*b]) := apply(f, [a]) + apply(f, [b]) :: in(f, [ln, log10])
27504@end smallexample
27505
27506@noindent
27507may seem more ``efficient'' than two separate rules for @code{ln} and
27508@code{log10}, but actually it is vastly less efficient because rules
27509with @code{apply} as the top-level pattern must be tested against
27510@emph{every} function call that is simplified.
27511
27512@cindex @code{AlgSimpRules} variable
27513@vindex AlgSimpRules
27514Suppose you want @samp{sin(a + b)} to be expanded out not all the time,
8e7046c3
JB
27515but only when algebraic simplifications are used to simplify the
27516formula. The variable @code{AlgSimpRules} holds rules for this purpose.
27517The @kbd{a s} command will apply @code{EvalRules} and
27518@code{AlgSimpRules} to the formula, as well as all of its built-in
27519simplifications.
4009494e
GM
27520
27521Most of the special limitations for @code{EvalRules} don't apply to
27522@code{AlgSimpRules}. Calc simply does an @kbd{a r AlgSimpRules}
8e7046c3
JB
27523command with an infinite repeat count as the first step of algebraic
27524simplifications. It then applies its own built-in simplifications
27525throughout the formula, and then repeats these two steps (along with
27526applying the default simplifications) until no further changes are
27527possible.
4009494e
GM
27528
27529@cindex @code{ExtSimpRules} variable
27530@cindex @code{UnitSimpRules} variable
27531@vindex ExtSimpRules
27532@vindex UnitSimpRules
27533There are also @code{ExtSimpRules} and @code{UnitSimpRules} variables
27534that are used by @kbd{a e} and @kbd{u s}, respectively; these commands
27535also apply @code{EvalRules} and @code{AlgSimpRules}. The variable
27536@code{IntegSimpRules} contains simplification rules that are used
27537only during integration by @kbd{a i}.
27538
27539@node Debugging Rewrites, Examples of Rewrite Rules, Automatic Rewrites, Rewrite Rules
27540@subsection Debugging Rewrites
27541
27542@noindent
27543If a buffer named @samp{*Trace*} exists, the rewrite mechanism will
27544record some useful information there as it operates. The original
27545formula is written there, as is the result of each successful rewrite,
27546and the final result of the rewriting. All phase changes are also
27547noted.
27548
27549Calc always appends to @samp{*Trace*}. You must empty this buffer
27550yourself periodically if it is in danger of growing unwieldy.
27551
27552Note that the rewriting mechanism is substantially slower when the
27553@samp{*Trace*} buffer exists, even if the buffer is not visible on
27554the screen. Once you are done, you will probably want to kill this
27555buffer (with @kbd{C-x k *Trace* @key{RET}}). If you leave it in
27556existence and forget about it, all your future rewrite commands will
27557be needlessly slow.
27558
27559@node Examples of Rewrite Rules, , Debugging Rewrites, Rewrite Rules
27560@subsection Examples of Rewrite Rules
27561
27562@noindent
27563Returning to the example of substituting the pattern
27564@samp{sin(x)^2 + cos(x)^2} with 1, we saw that the rule
27565@samp{opt(a) sin(x)^2 + opt(a) cos(x)^2 := a} does a good job of
27566finding suitable cases. Another solution would be to use the rule
27567@samp{cos(x)^2 := 1 - sin(x)^2}, followed by algebraic simplification
27568if necessary. This rule will be the most effective way to do the job,
27569but at the expense of making some changes that you might not desire.
27570
27571Another algebraic rewrite rule is @samp{exp(x+y) := exp(x) exp(y)}.
27572To make this work with the @w{@kbd{j r}} command so that it can be
27573easily targeted to a particular exponential in a large formula,
27574you might wish to write the rule as @samp{select(exp(x+y)) :=
27575select(exp(x) exp(y))}. The @samp{select} markers will be
27576ignored by the regular @kbd{a r} command
27577(@pxref{Selections with Rewrite Rules}).
27578
27579A surprisingly useful rewrite rule is @samp{a/(b-c) := a*(b+c)/(b^2-c^2)}.
27580This will simplify the formula whenever @expr{b} and/or @expr{c} can
27581be made simpler by squaring. For example, applying this rule to
27582@samp{2 / (sqrt(2) + 3)} yields @samp{6:7 - 2:7 sqrt(2)} (assuming
27583Symbolic mode has been enabled to keep the square root from being
27584evaluated to a floating-point approximation). This rule is also
27585useful when working with symbolic complex numbers, e.g.,
27586@samp{(a + b i) / (c + d i)}.
27587
27588As another example, we could define our own ``triangular numbers'' function
27589with the rules @samp{[tri(0) := 0, tri(n) := n + tri(n-1) :: n>0]}. Enter
27590this vector and store it in a variable: @kbd{@w{s t} trirules}. Now, given
27591a suitable formula like @samp{tri(5)} on the stack, type @samp{a r trirules}
27592to apply these rules repeatedly. After six applications, @kbd{a r} will
27593stop with 15 on the stack. Once these rules are debugged, it would probably
27594be most useful to add them to @code{EvalRules} so that Calc will evaluate
27595the new @code{tri} function automatically. We could then use @kbd{Z K} on
27596the keyboard macro @kbd{' tri($) @key{RET}} to make a command that applies
27597@code{tri} to the value on the top of the stack. @xref{Programming}.
27598
27599@cindex Quaternions
40ba43b4 27600The following rule set, contributed by
4009494e
GM
27601@texline Fran\c cois
27602@infoline Francois
27603Pinard, implements @dfn{quaternions}, a generalization of the concept of
27604complex numbers. Quaternions have four components, and are here
27605represented by function calls @samp{quat(@var{w}, [@var{x}, @var{y},
27606@var{z}])} with ``real part'' @var{w} and the three ``imaginary'' parts
27607collected into a vector. Various arithmetical operations on quaternions
27608are supported. To use these rules, either add them to @code{EvalRules},
27609or create a command based on @kbd{a r} for simplifying quaternion
27610formulas. A convenient way to enter quaternions would be a command
27611defined by a keyboard macro containing: @kbd{' quat($$$$, [$$$, $$, $])
27612@key{RET}}.
27613
27614@smallexample
27615[ quat(w, x, y, z) := quat(w, [x, y, z]),
27616 quat(w, [0, 0, 0]) := w,
27617 abs(quat(w, v)) := hypot(w, v),
27618 -quat(w, v) := quat(-w, -v),
27619 r + quat(w, v) := quat(r + w, v) :: real(r),
27620 r - quat(w, v) := quat(r - w, -v) :: real(r),
27621 quat(w1, v1) + quat(w2, v2) := quat(w1 + w2, v1 + v2),
27622 r * quat(w, v) := quat(r * w, r * v) :: real(r),
27623 plain(quat(w1, v1) * quat(w2, v2))
27624 := quat(w1 * w2 - v1 * v2, w1 * v2 + w2 * v1 + cross(v1, v2)),
27625 quat(w1, v1) / r := quat(w1 / r, v1 / r) :: real(r),
27626 z / quat(w, v) := z * quatinv(quat(w, v)),
27627 quatinv(quat(w, v)) := quat(w, -v) / (w^2 + v^2),
27628 quatsqr(quat(w, v)) := quat(w^2 - v^2, 2 * w * v),
27629 quat(w, v)^k := quatsqr(quat(w, v)^(k / 2))
27630 :: integer(k) :: k > 0 :: k % 2 = 0,
27631 quat(w, v)^k := quatsqr(quat(w, v)^((k - 1) / 2)) * quat(w, v)
27632 :: integer(k) :: k > 2,
27633 quat(w, v)^-k := quatinv(quat(w, v)^k) :: integer(k) :: k > 0 ]
27634@end smallexample
27635
27636Quaternions, like matrices, have non-commutative multiplication.
27637In other words, @expr{q1 * q2 = q2 * q1} is not necessarily true if
27638@expr{q1} and @expr{q2} are @code{quat} forms. The @samp{quat*quat}
27639rule above uses @code{plain} to prevent Calc from rearranging the
27640product. It may also be wise to add the line @samp{[quat(), matrix]}
27641to the @code{Decls} matrix, to ensure that Calc's other algebraic
27642operations will not rearrange a quaternion product. @xref{Declarations}.
27643
27644These rules also accept a four-argument @code{quat} form, converting
27645it to the preferred form in the first rule. If you would rather see
27646results in the four-argument form, just append the two items
27647@samp{phase(2), quat(w, [x, y, z]) := quat(w, x, y, z)} to the end
27648of the rule set. (But remember that multi-phase rule sets don't work
27649in @code{EvalRules}.)
27650
27651@node Units, Store and Recall, Algebra, Top
27652@chapter Operating on Units
27653
27654@noindent
27655One special interpretation of algebraic formulas is as numbers with units.
27656For example, the formula @samp{5 m / s^2} can be read ``five meters
27657per second squared.'' The commands in this chapter help you
27658manipulate units expressions in this form. Units-related commands
27659begin with the @kbd{u} prefix key.
27660
27661@menu
27662* Basic Operations on Units::
27663* The Units Table::
27664* Predefined Units::
27665* User-Defined Units::
2e78df6b 27666* Logarithmic Units::
05a29101 27667* Musical Notes::
4009494e
GM
27668@end menu
27669
27670@node Basic Operations on Units, The Units Table, Units, Units
27671@section Basic Operations on Units
27672
27673@noindent
27674A @dfn{units expression} is a formula which is basically a number
27675multiplied and/or divided by one or more @dfn{unit names}, which may
27676optionally be raised to integer powers. Actually, the value part need not
27677be a number; any product or quotient involving unit names is a units
27678expression. Many of the units commands will also accept any formula,
27679where the command applies to all units expressions which appear in the
27680formula.
27681
27682A unit name is a variable whose name appears in the @dfn{unit table},
27683or a variable whose name is a prefix character like @samp{k} (for ``kilo'')
27684or @samp{u} (for ``micro'') followed by a name in the unit table.
27685A substantial table of built-in units is provided with Calc;
27686@pxref{Predefined Units}. You can also define your own unit names;
27687@pxref{User-Defined Units}.
27688
27689Note that if the value part of a units expression is exactly @samp{1},
27690it will be removed by the Calculator's automatic algebra routines: The
27691formula @samp{1 mm} is ``simplified'' to @samp{mm}. This is only a
27692display anomaly, however; @samp{mm} will work just fine as a
27693representation of one millimeter.
27694
27695You may find that Algebraic mode (@pxref{Algebraic Entry}) makes working
27696with units expressions easier. Otherwise, you will have to remember
27697to hit the apostrophe key every time you wish to enter units.
27698
27699@kindex u s
27700@pindex calc-simplify-units
27701@ignore
27702@mindex usimpl@idots
27703@end ignore
27704@tindex usimplify
27705The @kbd{u s} (@code{calc-simplify-units}) [@code{usimplify}] command
27706simplifies a units
8e7046c3 27707expression. It uses Calc's algebraic simplifications to simplify the
4009494e
GM
27708expression first as a regular algebraic formula; it then looks for
27709features that can be further simplified by converting one object's units
27710to be compatible with another's. For example, @samp{5 m + 23 mm} will
27711simplify to @samp{5.023 m}. When different but compatible units are
27712added, the righthand term's units are converted to match those of the
27713lefthand term. @xref{Simplification Modes}, for a way to have this done
27714automatically at all times.
27715
27716Units simplification also handles quotients of two units with the same
27717dimensionality, as in @w{@samp{2 in s/L cm}} to @samp{5.08 s/L}; fractional
27718powers of unit expressions, as in @samp{sqrt(9 mm^2)} to @samp{3 mm} and
27719@samp{sqrt(9 acre)} to a quantity in meters; and @code{floor},
27720@code{ceil}, @code{round}, @code{rounde}, @code{roundu}, @code{trunc},
27721@code{float}, @code{frac}, @code{abs}, and @code{clean}
27722applied to units expressions, in which case
27723the operation in question is applied only to the numeric part of the
27724expression. Finally, trigonometric functions of quantities with units
27725of angle are evaluated, regardless of the current angular mode.
27726
27727@kindex u c
27728@pindex calc-convert-units
27729The @kbd{u c} (@code{calc-convert-units}) command converts a units
27730expression to new, compatible units. For example, given the units
27731expression @samp{55 mph}, typing @kbd{u c m/s @key{RET}} produces
27732@samp{24.5872 m/s}. If you have previously converted a units expression
27733with the same type of units (in this case, distance over time), you will
27734be offered the previous choice of new units as a default. Continuing
27735the above example, entering the units expression @samp{100 km/hr} and
27736typing @kbd{u c @key{RET}} (without specifying new units) produces
27737@samp{27.7777777778 m/s}.
27738
2be4956d
JB
27739@kindex u t
27740@pindex calc-convert-temperature
27741@cindex Temperature conversion
27742The @kbd{u c} command treats temperature units (like @samp{degC} and
27743@samp{K}) as relative temperatures. For example, @kbd{u c} converts
27744@samp{10 degC} to @samp{18 degF}: A change of 10 degrees Celsius
27745corresponds to a change of 18 degrees Fahrenheit. To convert absolute
27746temperatures, you can use the @kbd{u t}
27747(@code{calc-convert-temperature}) command. The value on the stack
27748must be a simple units expression with units of temperature only.
27749This command would convert @samp{10 degC} to @samp{50 degF}, the
27750equivalent temperature on the Fahrenheit scale.
27751
4009494e
GM
27752While many of Calc's conversion factors are exact, some are necessarily
27753approximate. If Calc is in fraction mode (@pxref{Fraction Mode}), then
27754unit conversions will try to give exact, rational conversions, but it
40ba43b4
PE
27755isn't always possible. Given @samp{55 mph} in fraction mode, typing
27756@kbd{u c m/s @key{RET}} produces @samp{15367:625 m/s}, for example,
27757while typing @kbd{u c au/yr @key{RET}} produces
4009494e
GM
27758@samp{5.18665819999e-3 au/yr}.
27759
27760If the units you request are inconsistent with the original units, the
27761number will be converted into your units times whatever ``remainder''
27762units are left over. For example, converting @samp{55 mph} into acres
27763produces @samp{6.08e-3 acre / m s}. (Recall that multiplication binds
27764more strongly than division in Calc formulas, so the units here are
27765acres per meter-second.) Remainder units are expressed in terms of
27766``fundamental'' units like @samp{m} and @samp{s}, regardless of the
27767input units.
27768
d14b0029 27769If you want to disallow using inconsistent units, you can set the customizable variable
09ae5da1 27770@code{calc-ensure-consistent-units} to @code{t} (@pxref{Customizing Calc}). In this case,
d14b0029
JB
27771if you request units which are inconsistent with the original units, you will be warned about
27772it and no conversion will occur.
27773
4009494e
GM
27774One special exception is that if you specify a single unit name, and
27775a compatible unit appears somewhere in the units expression, then
27776that compatible unit will be converted to the new unit and the
27777remaining units in the expression will be left alone. For example,
27778given the input @samp{980 cm/s^2}, the command @kbd{u c ms} will
27779change the @samp{s} to @samp{ms} to get @samp{9.8e-4 cm/ms^2}.
27780The ``remainder unit'' @samp{cm} is left alone rather than being
27781changed to the base unit @samp{m}.
27782
27783You can use explicit unit conversion instead of the @kbd{u s} command
27784to gain more control over the units of the result of an expression.
27785For example, given @samp{5 m + 23 mm}, you can type @kbd{u c m} or
27786@kbd{u c mm} to express the result in either meters or millimeters.
27787(For that matter, you could type @kbd{u c fath} to express the result
27788in fathoms, if you preferred!)
27789
27790In place of a specific set of units, you can also enter one of the
27791units system names @code{si}, @code{mks} (equivalent), or @code{cgs}.
27792For example, @kbd{u c si @key{RET}} converts the expression into
27793International System of Units (SI) base units. Also, @kbd{u c base}
27794converts to Calc's base units, which are the same as @code{si} units
27795except that @code{base} uses @samp{g} as the fundamental unit of mass
27796whereas @code{si} uses @samp{kg}.
27797
27798@cindex Composite units
27799The @kbd{u c} command also accepts @dfn{composite units}, which
27800are expressed as the sum of several compatible unit names. For
27801example, converting @samp{30.5 in} to units @samp{mi+ft+in} (miles,
27802feet, and inches) produces @samp{2 ft + 6.5 in}. Calc first
27803sorts the unit names into order of decreasing relative size.
27804It then accounts for as much of the input quantity as it can
27805using an integer number times the largest unit, then moves on
27806to the next smaller unit, and so on. Only the smallest unit
27807may have a non-integer amount attached in the result. A few
27808standard unit names exist for common combinations, such as
27809@code{mfi} for @samp{mi+ft+in}, and @code{tpo} for @samp{ton+lb+oz}.
27810Composite units are expanded as if by @kbd{a x}, so that
27811@samp{(ft+in)/hr} is first converted to @samp{ft/hr+in/hr}.
27812
27813If the value on the stack does not contain any units, @kbd{u c} will
27814prompt first for the old units which this value should be considered
27815to have, then for the new units. Assuming the old and new units you
27816give are consistent with each other, the result also will not contain
285f0d3a
JB
27817any units. For example, @kbd{@w{u c} cm @key{RET} in @key{RET}}
27818converts the number 2 on the stack to 5.08.
4009494e
GM
27819
27820@kindex u b
27821@pindex calc-base-units
27822The @kbd{u b} (@code{calc-base-units}) command is shorthand for
27823@kbd{u c base}; it converts the units expression on the top of the
27824stack into @code{base} units. If @kbd{u s} does not simplify a
27825units expression as far as you would like, try @kbd{u b}.
27826
2be4956d
JB
27827Like the @kbd{u c} command, the @kbd{u b} command treats temperature
27828units as relative temperatures.
4009494e
GM
27829
27830@kindex u r
27831@pindex calc-remove-units
27832@kindex u x
27833@pindex calc-extract-units
27834The @kbd{u r} (@code{calc-remove-units}) command removes units from the
27835formula at the top of the stack. The @kbd{u x}
27836(@code{calc-extract-units}) command extracts only the units portion of a
27837formula. These commands essentially replace every term of the formula
27838that does or doesn't (respectively) look like a unit name by the
27839constant 1, then resimplify the formula.
27840
27841@kindex u a
27842@pindex calc-autorange-units
27843The @kbd{u a} (@code{calc-autorange-units}) command turns on and off a
27844mode in which unit prefixes like @code{k} (``kilo'') are automatically
27845applied to keep the numeric part of a units expression in a reasonable
27846range. This mode affects @kbd{u s} and all units conversion commands
27847except @kbd{u b}. For example, with autoranging on, @samp{12345 Hz}
27848will be simplified to @samp{12.345 kHz}. Autoranging is useful for
27849some kinds of units (like @code{Hz} and @code{m}), but is probably
27850undesirable for non-metric units like @code{ft} and @code{tbsp}.
27851(Composite units are more appropriate for those; see above.)
27852
27853Autoranging always applies the prefix to the leftmost unit name.
27854Calc chooses the largest prefix that causes the number to be greater
27855than or equal to 1.0. Thus an increasing sequence of adjusted times
27856would be @samp{1 ms, 10 ms, 100 ms, 1 s, 10 s, 100 s, 1 ks}.
27857Generally the rule of thumb is that the number will be adjusted
27858to be in the interval @samp{[1 .. 1000)}, although there are several
27859exceptions to this rule. First, if the unit has a power then this
27860is not possible; @samp{0.1 s^2} simplifies to @samp{100000 ms^2}.
27861Second, the ``centi-'' prefix is allowed to form @code{cm} (centimeters),
27862but will not apply to other units. The ``deci-,'' ``deka-,'' and
27863``hecto-'' prefixes are never used. Thus the allowable interval is
27864@samp{[1 .. 10)} for millimeters and @samp{[1 .. 100)} for centimeters.
27865Finally, a prefix will not be added to a unit if the resulting name
27866is also the actual name of another unit; @samp{1e-15 t} would normally
27867be considered a ``femto-ton,'' but it is written as @samp{1000 at}
27868(1000 atto-tons) instead because @code{ft} would be confused with feet.
27869
27870@node The Units Table, Predefined Units, Basic Operations on Units, Units
27871@section The Units Table
27872
27873@noindent
27874@kindex u v
27875@pindex calc-enter-units-table
27876The @kbd{u v} (@code{calc-enter-units-table}) command displays the units table
27877in another buffer called @code{*Units Table*}. Each entry in this table
27878gives the unit name as it would appear in an expression, the definition
27879of the unit in terms of simpler units, and a full name or description of
27880the unit. Fundamental units are defined as themselves; these are the
27881units produced by the @kbd{u b} command. The fundamental units are
27882meters, seconds, grams, kelvins, amperes, candelas, moles, radians,
27883and steradians.
27884
27885The Units Table buffer also displays the Unit Prefix Table. Note that
27886two prefixes, ``kilo'' and ``hecto,'' accept either upper- or lower-case
27887prefix letters. @samp{Meg} is also accepted as a synonym for the @samp{M}
27888prefix. Whenever a unit name can be interpreted as either a built-in name
27889or a prefix followed by another built-in name, the former interpretation
27890wins. For example, @samp{2 pt} means two pints, not two pico-tons.
27891
27892The Units Table buffer, once created, is not rebuilt unless you define
27893new units. To force the buffer to be rebuilt, give any numeric prefix
27894argument to @kbd{u v}.
27895
27896@kindex u V
27897@pindex calc-view-units-table
27898The @kbd{u V} (@code{calc-view-units-table}) command is like @kbd{u v} except
27899that the cursor is not moved into the Units Table buffer. You can
27900type @kbd{u V} again to remove the Units Table from the display. To
27901return from the Units Table buffer after a @kbd{u v}, type @kbd{C-x * c}
27902again or use the regular Emacs @w{@kbd{C-x o}} (@code{other-window})
27903command. You can also kill the buffer with @kbd{C-x k} if you wish;
27904the actual units table is safely stored inside the Calculator.
27905
27906@kindex u g
27907@pindex calc-get-unit-definition
27908The @kbd{u g} (@code{calc-get-unit-definition}) command retrieves a unit's
27909defining expression and pushes it onto the Calculator stack. For example,
27910@kbd{u g in} will produce the expression @samp{2.54 cm}. This is the
27911same definition for the unit that would appear in the Units Table buffer.
27912Note that this command works only for actual unit names; @kbd{u g km}
27913will report that no such unit exists, for example, because @code{km} is
27914really the unit @code{m} with a @code{k} (``kilo'') prefix. To see a
27915definition of a unit in terms of base units, it is easier to push the
27916unit name on the stack and then reduce it to base units with @kbd{u b}.
27917
27918@kindex u e
27919@pindex calc-explain-units
27920The @kbd{u e} (@code{calc-explain-units}) command displays an English
27921description of the units of the expression on the stack. For example,
27922for the expression @samp{62 km^2 g / s^2 mol K}, the description is
27923``Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin).'' This
27924command uses the English descriptions that appear in the righthand
27925column of the Units Table.
27926
27927@node Predefined Units, User-Defined Units, The Units Table, Units
27928@section Predefined Units
27929
27930@noindent
285f0d3a
JB
27931The definitions of many units have changed over the years. For example,
27932the meter was originally defined in 1791 as one ten-millionth of the
27933distance from the equator to the north pole. In order to be more
27934precise, the definition was adjusted several times, and now a meter is
27935defined as the distance that light will travel in a vacuum in
279361/299792458 of a second; consequently, the speed of light in a
27937vacuum is exactly 299792458 m/s. Many other units have been
27938redefined in terms of fundamental physical processes; a second, for
27939example, is currently defined as 9192631770 periods of a certain
27940radiation related to the cesium-133 atom. The only SI unit that is not
27941based on a fundamental physical process (although there are efforts to
27942change this) is the kilogram, which was originally defined as the mass
27943of one liter of water, but is now defined as the mass of the
27944International Prototype Kilogram (IPK), a cylinder of platinum-iridium
27945kept at the Bureau International des Poids et Mesures in S@`evres,
27946France. (There are several copies of the IPK throughout the world.)
27947The British imperial units, once defined in terms of physical objects,
27948were redefined in 1963 in terms of SI units. The US customary units,
27949which were the same as British units until the British imperial system
27950was created in 1824, were also defined in terms of the SI units in 1893.
27951Because of these redefinitions, conversions between metric, British
27952Imperial, and US customary units can often be done precisely.
27953
4009494e
GM
27954Since the exact definitions of many kinds of units have evolved over the
27955years, and since certain countries sometimes have local differences in
27956their definitions, it is a good idea to examine Calc's definition of a
27957unit before depending on its exact value. For example, there are three
27958different units for gallons, corresponding to the US (@code{gal}),
27959Canadian (@code{galC}), and British (@code{galUK}) definitions. Also,
27960note that @code{oz} is a standard ounce of mass, @code{ozt} is a Troy
27961ounce, and @code{ozfl} is a fluid ounce.
27962
27963The temperature units corresponding to degrees Kelvin and Centigrade
27964(Celsius) are the same in this table, since most units commands treat
27965temperatures as being relative. The @code{calc-convert-temperature}
27966command has special rules for handling the different absolute magnitudes
27967of the various temperature scales.
27968
27969The unit of volume ``liters'' can be referred to by either the lower-case
27970@code{l} or the upper-case @code{L}.
27971
27972The unit @code{A} stands for Amperes; the name @code{Ang} is used
27973@tex
27974for \AA ngstroms.
27975@end tex
27976@ifnottex
27977for Angstroms.
27978@end ifnottex
27979
27980The unit @code{pt} stands for pints; the name @code{point} stands for
27981a typographical point, defined by @samp{72 point = 1 in}. This is
27982slightly different than the point defined by the American Typefounder's
27983Association in 1886, but the point used by Calc has become standard
27984largely due to its use by the PostScript page description language.
27985There is also @code{texpt}, which stands for a printer's point as
27986defined by the @TeX{} typesetting system: @samp{72.27 texpt = 1 in}.
27987Other units used by @TeX{} are available; they are @code{texpc} (a pica),
27988@code{texbp} (a ``big point'', equal to a standard point which is larger
27989than the point used by @TeX{}), @code{texdd} (a Didot point),
40ba43b4 27990@code{texcc} (a Cicero) and @code{texsp} (a scaled @TeX{} point,
4009494e
GM
27991all dimensions representable in @TeX{} are multiples of this value).
27992
c1dabff0 27993When Calc is using the @TeX{} or @LaTeX{} language mode (@pxref{TeX
1265829e
JB
27994and LaTeX Language Modes}), the @TeX{} specific unit names will not
27995use the @samp{tex} prefix; the unit name for a @TeX{} point will be
27996@samp{pt} instead of @samp{texpt}, for example. To avoid conflicts,
27997the unit names for pint and parsec will simply be @samp{pint} and
27998@samp{parsec} instead of @samp{pt} and @samp{pc}.
27999
28000
4009494e
GM
28001The unit @code{e} stands for the elementary (electron) unit of charge;
28002because algebra command could mistake this for the special constant
28003@expr{e}, Calc provides the alternate unit name @code{ech} which is
28004preferable to @code{e}.
28005
28006The name @code{g} stands for one gram of mass; there is also @code{gf},
28007one gram of force. (Likewise for @kbd{lb}, pounds, and @kbd{lbf}.)
28008Meanwhile, one ``@expr{g}'' of acceleration is denoted @code{ga}.
28009
28010The unit @code{ton} is a U.S. ton of @samp{2000 lb}, and @code{t} is
28011a metric ton of @samp{1000 kg}.
28012
28013The names @code{s} (or @code{sec}) and @code{min} refer to units of
28014time; @code{arcsec} and @code{arcmin} are units of angle.
28015
28016Some ``units'' are really physical constants; for example, @code{c}
28017represents the speed of light, and @code{h} represents Planck's
28018constant. You can use these just like other units: converting
28019@samp{.5 c} to @samp{m/s} expresses one-half the speed of light in
28020meters per second. You can also use this merely as a handy reference;
28021the @kbd{u g} command gets the definition of one of these constants
28022in its normal terms, and @kbd{u b} expresses the definition in base
28023units.
28024
28025Two units, @code{pi} and @code{alpha} (the fine structure constant,
28026approximately @mathit{1/137}) are dimensionless. The units simplification
28027commands simply treat these names as equivalent to their corresponding
28028values. However you can, for example, use @kbd{u c} to convert a pure
28029number into multiples of the fine structure constant, or @kbd{u b} to
28030convert this back into a pure number. (When @kbd{u c} prompts for the
28031``old units,'' just enter a blank line to signify that the value
28032really is unitless.)
28033
28034@c Describe angular units, luminosity vs. steradians problem.
28035
2e78df6b 28036@node User-Defined Units, Logarithmic Units, Predefined Units, Units
4009494e
GM
28037@section User-Defined Units
28038
28039@noindent
28040Calc provides ways to get quick access to your selected ``favorite''
28041units, as well as ways to define your own new units.
28042
28043@kindex u 0-9
28044@pindex calc-quick-units
28045@vindex Units
28046@cindex @code{Units} variable
28047@cindex Quick units
28048To select your favorite units, store a vector of unit names or
28049expressions in the Calc variable @code{Units}. The @kbd{u 1}
28050through @kbd{u 9} commands (@code{calc-quick-units}) provide access
28051to these units. If the value on the top of the stack is a plain
28052number (with no units attached), then @kbd{u 1} gives it the
28053specified units. (Basically, it multiplies the number by the
28054first item in the @code{Units} vector.) If the number on the
28055stack @emph{does} have units, then @kbd{u 1} converts that number
28056to the new units. For example, suppose the vector @samp{[in, ft]}
28057is stored in @code{Units}. Then @kbd{30 u 1} will create the
28058expression @samp{30 in}, and @kbd{u 2} will convert that expression
28059to @samp{2.5 ft}.
28060
28061The @kbd{u 0} command accesses the tenth element of @code{Units}.
28062Only ten quick units may be defined at a time. If the @code{Units}
28063variable has no stored value (the default), or if its value is not
28064a vector, then the quick-units commands will not function. The
28065@kbd{s U} command is a convenient way to edit the @code{Units}
28066variable; @pxref{Operations on Variables}.
28067
28068@kindex u d
28069@pindex calc-define-unit
28070@cindex User-defined units
28071The @kbd{u d} (@code{calc-define-unit}) command records the units
28072expression on the top of the stack as the definition for a new,
28073user-defined unit. For example, putting @samp{16.5 ft} on the stack and
28074typing @kbd{u d rod} defines the new unit @samp{rod} to be equivalent to
2807516.5 feet. The unit conversion and simplification commands will now
28076treat @code{rod} just like any other unit of length. You will also be
28077prompted for an optional English description of the unit, which will
4043c194
JB
28078appear in the Units Table. If you wish the definition of this unit to
28079be displayed in a special way in the Units Table buffer (such as with an
28080asterisk to indicate an approximate value), then you can call this
28081command with an argument, @kbd{C-u u d}; you will then also be prompted
28082for a string that will be used to display the definition.
4009494e
GM
28083
28084@kindex u u
28085@pindex calc-undefine-unit
28086The @kbd{u u} (@code{calc-undefine-unit}) command removes a user-defined
28087unit. It is not possible to remove one of the predefined units,
28088however.
28089
28090If you define a unit with an existing unit name, your new definition
28091will replace the original definition of that unit. If the unit was a
28092predefined unit, the old definition will not be replaced, only
28093``shadowed.'' The built-in definition will reappear if you later use
28094@kbd{u u} to remove the shadowing definition.
28095
28096To create a new fundamental unit, use either 1 or the unit name itself
28097as the defining expression. Otherwise the expression can involve any
28098other units that you like (except for composite units like @samp{mfi}).
28099You can create a new composite unit with a sum of other units as the
28100defining expression. The next unit operation like @kbd{u c} or @kbd{u v}
28101will rebuild the internal unit table incorporating your modifications.
28102Note that erroneous definitions (such as two units defined in terms of
28103each other) will not be detected until the unit table is next rebuilt;
28104@kbd{u v} is a convenient way to force this to happen.
28105
28106Temperature units are treated specially inside the Calculator; it is not
28107possible to create user-defined temperature units.
28108
28109@kindex u p
28110@pindex calc-permanent-units
28111@cindex Calc init file, user-defined units
28112The @kbd{u p} (@code{calc-permanent-units}) command stores the user-defined
28113units in your Calc init file (the file given by the variable
dcf7843e 28114@code{calc-settings-file}, typically @file{~/.emacs.d/calc.el}), so that the
4009494e
GM
28115units will still be available in subsequent Emacs sessions. If there
28116was already a set of user-defined units in your Calc init file, it
28117is replaced by the new set. (@xref{General Mode Commands}, for a way to
28118tell Calc to use a different file for the Calc init file.)
28119
05a29101 28120@node Logarithmic Units, Musical Notes, User-Defined Units, Units
2e78df6b
JB
28121@section Logarithmic Units
28122
28123The units @code{dB} (decibels) and @code{Np} (nepers) are logarithmic
d71990a1
JB
28124units which are manipulated differently than standard units. Calc
28125provides commands to work with these logarithmic units.
2e78df6b 28126
40ba43b4 28127Decibels and nepers are used to measure power quantities as well as
d71990a1
JB
28128field quantities (quantities whose squares are proportional to power);
28129these two types of quantities are handled slightly different from each
28130other. By default the Calc commands work as if power quantities are
28131being used; with the @kbd{H} prefix the Calc commands work as if field
28132quantities are being used.
2e78df6b 28133
40ba43b4 28134The decibel level of a power
2e78df6b
JB
28135@infoline @math{P1},
28136@texline @math{P_1},
40ba43b4 28137relative to a reference power
2e78df6b
JB
28138@infoline @math{P0},
28139@texline @math{P_0},
28140is defined to be
28141@infoline @math{10 log10(P1/P0) dB}.
28142@texline @math{10 \log_{10}(P_{1}/P_{0}) {\rm dB}}.
28143(The factor of 10 is because a decibel, as its name implies, is
28144one-tenth of a bel. The bel, named after Alexander Graham Bell, was
28145considered to be too large of a unit and was effectively replaced by
28146the decibel.) If @math{F} is a field quantity with power
40ba43b4 28147@math{P=k F^2}, then a reference quantity of
2e78df6b
JB
28148@infoline @math{F0}
28149@texline @math{F_0}
40ba43b4 28150would correspond to a power of
2e78df6b
JB
28151@infoline @math{P0=k F0^2}.
28152@texline @math{P_{0}=kF_{0}^2}.
28153If
28154@infoline @math{P1=k F1^2},
28155@texline @math{P_{1}=kF_{1}^2},
28156then
28157
28158@ifnottex
40ba43b4 28159@example
2e78df6b
JB
2816010 log10(P1/P0) = 10 log10(F1^2/F0^2) = 20 log10(F1/F0).
28161@end example
28162@end ifnottex
28163@tex
28164$$ 10 \log_{10}(P_1/P_0) = 10 \log_{10}(F_1^2/F_0^2) = 20
28165\log_{10}(F_1/F_0)$$
28166@end tex
28167
28168@noindent
28169In order to get the same decibel level regardless of whether a field
28170quantity or the corresponding power quantity is used, the decibel
40ba43b4 28171level of a field quantity
2e78df6b 28172@infoline @math{F1},
40ba43b4
PE
28173@texline @math{F_1},
28174relative to a reference
2e78df6b 28175@infoline @math{F0},
40ba43b4 28176@texline @math{F_0},
2e78df6b
JB
28177is defined as
28178@infoline @math{20 log10(F1/F0) dB}.
28179@texline @math{20 \log_{10}(F_{1}/F_{0}) {\rm dB}}.
40ba43b4 28180For example, the decibel value of a sound pressure level of
d71990a1
JB
28181@infoline @math{60 uPa}
28182@texline @math{60 \mu{\rm Pa}}
40ba43b4 28183relative to
d71990a1
JB
28184@infoline @math{20 uPa}
28185@texline @math{20 \mu{\rm Pa}}
40ba43b4 28186(the threshold of human hearing) is
d71990a1
JB
28187@infoline @math{20 log10(60 uPa/ 20 uPa) dB = 20 log10(3) dB},
28188@texline @math{20 \log_{10}(60 \mu{\rm Pa}/20 \mu{\rm Pa}) {\rm dB} = 20 \log_{10}(3) {\rm dB}},
40ba43b4 28189which is about
d71990a1
JB
28190@infoline @math{9.54 dB}.
28191@texline @math{9.54 {\rm dB}}.
28192Note that in taking the ratio, the original units cancel and so these
40ba43b4 28193logarithmic units are dimensionless.
2e78df6b
JB
28194
28195Nepers (named after John Napier, who is credited with inventing the
28196logarithm) are similar to bels except they use natural logarithms instead
40ba43b4 28197of common logarithms. The neper level of a power
2e78df6b
JB
28198@infoline @math{P1},
28199@texline @math{P_1},
40ba43b4 28200relative to a reference power
2e78df6b
JB
28201@infoline @math{P0},
28202@texline @math{P_0},
28203is
28204@infoline @math{(1/2) ln(P1/P0) Np}.
28205@texline @math{(1/2) \ln(P_1/P_0) {\rm Np}}.
40ba43b4 28206The neper level of a field
2e78df6b
JB
28207@infoline @math{F1},
28208@texline @math{F_1},
28209relative to a reference field
28210@infoline @math{F0},
28211@texline @math{F_0},
28212is
28213@infoline @math{ln(F1/F0) Np}.
28214@texline @math{\ln(F_1/F_0) {\rm Np}}.
28215
d71990a1
JB
28216@vindex calc-lu-power-reference
28217@vindex calc-lu-field-reference
28218For power quantities, Calc uses
40ba43b4 28219@infoline @math{1 mW}
d71990a1 28220@texline @math{1 {\rm mW}}
40ba43b4 28221as the default reference quantity; this default can be changed by changing
d71990a1
JB
28222the value of the customizable variable
28223@code{calc-lu-power-reference} (@pxref{Customizing Calc}).
40ba43b4
PE
28224For field quantities, Calc uses
28225@infoline @math{20 uPa}
d71990a1
JB
28226@texline @math{20 \mu{\rm Pa}}
28227as the default reference quantity; this is the value used in acoustics
28228which is where decibels are commonly encountered. This default can be
28229changed by changing the value of the customizable variable
28230@code{calc-lu-field-reference} (@pxref{Customizing Calc}). A
28231non-default reference quantity will be read from the stack if the
28232capital @kbd{O} prefix is used.
28233
2e78df6b 28234@kindex l q
d71990a1 28235@pindex calc-lu-quant
580b66d8
JB
28236@tindex lupquant
28237@tindex lufquant
28238The @kbd{l q} (@code{calc-lu-quant}) [@code{lupquant}]
2e78df6b
JB
28239command computes the power quantity corresponding to a given number of
28240logarithmic units. With the capital @kbd{O} prefix, @kbd{O l q}, the
28241reference level will be read from the top of the stack. (In an
580b66d8 28242algebraic formula, @code{lupquant} can be given an optional second
40ba43b4
PE
28243argument which will be used for the reference level.) For example,
28244@code{20 dB @key{RET} l q} will return @code{100 mW};
28245@code{20 dB @key{RET} 4 W @key{RET} O l q} will return @code{400 W}.
580b66d8 28246The @kbd{H l q} [@code{lufquant}] command behaves like @kbd{l q} but
2e78df6b
JB
28247computes field quantities instead of power quantities.
28248
28249@kindex l d
d71990a1
JB
28250@pindex calc-db
28251@tindex dbpower
28252@tindex dbfield
2e78df6b 28253@kindex l n
d71990a1
JB
28254@pindex calc-np
28255@tindex nppower
28256@tindex npfield
28257The @kbd{l d} (@code{calc-db}) [@code{dbpower}] command will compute
28258the decibel level of a power quantity using the default reference
28259level; @kbd{H l d} [@code{dbfield}] will compute the decibel level of
28260a field quantity. The commands @kbd{l n} (@code{calc-np})
28261[@code{nppower}] and @kbd{H l n} [@code{npfield}] will similarly
28262compute neper levels. With the capital @kbd{O} prefix these commands
28263will read a reference level from the stack; in an algebraic formula
28264the reference level can be given as an optional second argument.
2e78df6b
JB
28265
28266@kindex l +
d71990a1
JB
28267@pindex calc-lu-plus
28268@tindex lupadd
28269@tindex lufadd
2e78df6b 28270@kindex l -
d71990a1
JB
28271@pindex calc-lu-minus
28272@tindex lupsub
28273@tindex lufsub
2e78df6b 28274@kindex l *
d71990a1
JB
28275@pindex calc-lu-times
28276@tindex lupmul
28277@tindex lufmul
2e78df6b 28278@kindex l /
d71990a1
JB
28279@pindex calc-lu-divide
28280@tindex lupdiv
28281@tindex lufdiv
2e78df6b
JB
28282The sum of two power or field quantities doesn't correspond to the sum
28283of the corresponding decibel or neper levels. If the powers
40ba43b4
PE
28284corresponding to decibel levels
28285@infoline @math{D1}
28286@texline @math{D_1}
28287and
28288@infoline @math{D2}
28289@texline @math{D_2}
28290are added, the corresponding decibel level ``sum'' will be
2e78df6b
JB
28291
28292@ifnottex
28293@example
28294 10 log10(10^(D1/10) + 10^(D2/10)) dB.
28295@end example
28296@end ifnottex
28297@tex
28298$$ 10 \log_{10}(10^{D_1/10} + 10^{D_2/10}) {\rm dB}.$$
28299@end tex
28300
28301@noindent
d71990a1
JB
28302When field quantities are combined, it often means the corresponding
28303powers are added and so the above formula might be used. In
28304acoustics, for example, the sound pressure level is a field quantity
28305and so the decibels are often defined using the field formula, but the
28306sound pressure levels are combined as the sound power levels, and so
28307the above formula should be used. If two field quantities themselves
28308are added, the new decibel level will be
2e78df6b
JB
28309
28310@ifnottex
28311@example
28312 20 log10(10^(D1/20) + 10^(D2/20)) dB.
28313@end example
28314@end ifnottex
28315@tex
28316$$ 20 \log_{10}(10^{D_1/20} + 10^{D_2/20}) {\rm dB}.$$
28317@end tex
28318
28319@noindent
28320If the power corresponding to @math{D} dB is multiplied by a number @math{N},
28321then the corresponding decibel level will be
28322
28323@ifnottex
28324@example
28325 D + 10 log10(N) dB,
28326@end example
28327@end ifnottex
28328@tex
28329$$ D + 10 \log_{10}(N) {\rm dB},$$
28330@end tex
28331
28332@noindent
28333if a field quantity is multiplied by @math{N} the corresponding decibel level
40ba43b4 28334will be
2e78df6b
JB
28335
28336@ifnottex
28337@example
28338 D + 20 log10(N) dB.
28339@end example
28340@end ifnottex
28341@tex
28342$$ D + 20 \log_{10}(N) {\rm dB}.$$
28343@end tex
28344
28345@noindent
d71990a1
JB
28346There are similar formulas for combining nepers. The @kbd{l +}
28347(@code{calc-lu-plus}) [@code{lupadd}] command will ``add'' two
28348logarithmic unit power levels this way; with the @kbd{H} prefix,
28349@kbd{H l +} [@code{lufadd}] will add logarithmic unit field levels.
28350Similarly, logarithmic units can be ``subtracted'' with @kbd{l -}
28351(@code{calc-lu-minus}) [@code{lupsub}] or @kbd{H l -} [@code{lufsub}].
28352The @kbd{l *} (@code{calc-lu-times}) [@code{lupmul}] and @kbd{H l *}
28353[@code{lufmul}] commands will ``multiply'' a logarithmic unit by a
28354number; the @kbd{l /} (@code{calc-lu-divide}) [@code{lupdiv}] and
28355@kbd{H l /} [@code{lufdiv}] commands will ``divide'' a logarithmic
28356unit by a number. Note that the reference quantities don't play a role
28357in this arithmetic.
2e78df6b 28358
05a29101
JB
28359@node Musical Notes, , Logarithmic Units, Units
28360@section Musical Notes
28361
28362Calc can convert between musical notes and their associated
28363frequencies. Notes can be given using either scientific pitch
28364notation or midi numbers. Since these note systems are basically
28365logarithmic scales, Calc uses the @kbd{l} prefix for functions
28366operating on notes.
28367
28368Scientific pitch notation refers to a note by giving a letter
28369A through G, possibly followed by a flat or sharp) with a subscript
28370indicating an octave number. Each octave starts with C and ends with
40ba43b4 28371B and
05a29101
JB
28372@c increasing each note by a semitone will result
28373@c in the sequence @expr{C}, @expr{C} sharp, @expr{D}, @expr{E} flat, @expr{E},
28374@c @expr{F}, @expr{F} sharp, @expr{G}, @expr{A} flat, @expr{A}, @expr{B}
40ba43b4 28375@c flat and @expr{B}.
05a29101
JB
28376the octave numbered 0 was chosen to correspond to the lowest
28377audible frequency. Using this system, middle C (about 261.625 Hz)
28378corresponds to the note @expr{C} in octave 4 and is denoted
28379@expr{C_4}. Any frequency can be described by giving a note plus an
28380offset in cents (where a cent is a ratio of frequencies so that a
40ba43b4 28381semitone consists of 100 cents).
05a29101
JB
28382
28383The midi note number system assigns numbers to notes so that
28384@expr{C_(-1)} corresponds to the midi note number 0 and @expr{G_9}
28385corresponds to the midi note number 127. A midi controller can have
28386up to 128 keys and each midi note number from 0 to 127 corresponds to
40ba43b4 28387a possible key.
05a29101
JB
28388
28389@kindex l s
28390@pindex calc-spn
28391@tindex spn
28392The @kbd{l s} (@code{calc-spn}) [@code{spn}] command converts either
28393a frequency or a midi number to scientific pitch notation. For
40ba43b4
PE
28394example, @code{500 Hz} gets converted to
28395@code{B_4 + 21.3094853649 cents} and @code{84} to @code{C_6}.
05a29101
JB
28396
28397
28398@kindex l m
28399@pindex calc-midi
28400@tindex midi
28401The @kbd{l m} (@code{calc-midi}) [@code{midi}] command converts either
28402a frequency or a note given in scientific pitch notation to the
28403corresponding midi number. For example, @code{C_6} gets converted to 84
28404and @code{440 Hz} to 69.
28405
28406@kindex l f
28407@pindex calc-freq
28408@tindex freq
28409The @kbd{l f} (@code{calc-freq}) [@code{freq}] command converts either
28410either a midi number or a note given in scientific pitch notation to
28411the corresponding frequency. For example, @code{Asharp_2 + 30 cents}
28412gets converted to @code{118.578040134 Hz} and @code{55} to
28413@code{195.99771799 Hz}.
28414
28415Since the frequencies of notes are not usually given exactly (and are
28416typically irrational), the customizable variable
28417@code{calc-note-threshold} determines how close (in cents) a frequency
28418needs to be to a note to be recognized as that note
28419(@pxref{Customizing Calc}). This variable has a default value of
28420@code{1}. For example, middle @var{C} is approximately
28421@expr{261.625565302 Hz}; this frequency is often shortened to
28422@expr{261.625 Hz}. Without @code{calc-note-threshold} (or a value of
28423@expr{0}), Calc would convert @code{261.625 Hz} to scientific pitch
28424notation @code{B_3 + 99.9962592773 cents}; with the default value of
28425@code{1}, Calc converts @code{261.625 Hz} to @code{C_4}.
28426
28427
28428
4009494e
GM
28429@node Store and Recall, Graphics, Units, Top
28430@chapter Storing and Recalling
28431
28432@noindent
28433Calculator variables are really just Lisp variables that contain numbers
28434or formulas in a form that Calc can understand. The commands in this
28435section allow you to manipulate variables conveniently. Commands related
28436to variables use the @kbd{s} prefix key.
28437
28438@menu
28439* Storing Variables::
28440* Recalling Variables::
28441* Operations on Variables::
28442* Let Command::
28443* Evaluates-To Operator::
28444@end menu
28445
28446@node Storing Variables, Recalling Variables, Store and Recall, Store and Recall
28447@section Storing Variables
28448
28449@noindent
28450@kindex s s
28451@pindex calc-store
28452@cindex Storing variables
28453@cindex Quick variables
28454@vindex q0
28455@vindex q9
28456The @kbd{s s} (@code{calc-store}) command stores the value at the top of
28457the stack into a specified variable. It prompts you to enter the
28458name of the variable. If you press a single digit, the value is stored
28459immediately in one of the ``quick'' variables @code{q0} through
40ba43b4 28460@code{q9}. Or you can enter any variable name.
4009494e
GM
28461
28462@kindex s t
28463@pindex calc-store-into
28464The @kbd{s s} command leaves the stored value on the stack. There is
28465also an @kbd{s t} (@code{calc-store-into}) command, which removes a
28466value from the stack and stores it in a variable.
28467
28468If the top of stack value is an equation @samp{a = 7} or assignment
28469@samp{a := 7} with a variable on the lefthand side, then Calc will
28470assign that variable with that value by default, i.e., if you type
28471@kbd{s s @key{RET}} or @kbd{s t @key{RET}}. In this example, the
28472value 7 would be stored in the variable @samp{a}. (If you do type
28473a variable name at the prompt, the top-of-stack value is stored in
28474its entirety, even if it is an equation: @samp{s s b @key{RET}}
28475with @samp{a := 7} on the stack stores @samp{a := 7} in @code{b}.)
28476
28477In fact, the top of stack value can be a vector of equations or
28478assignments with different variables on their lefthand sides; the
28479default will be to store all the variables with their corresponding
28480righthand sides simultaneously.
28481
28482It is also possible to type an equation or assignment directly at
28483the prompt for the @kbd{s s} or @kbd{s t} command: @kbd{s s foo = 7}.
28484In this case the expression to the right of the @kbd{=} or @kbd{:=}
28485symbol is evaluated as if by the @kbd{=} command, and that value is
28486stored in the variable. No value is taken from the stack; @kbd{s s}
28487and @kbd{s t} are equivalent when used in this way.
28488
28489@kindex s 0-9
28490@kindex t 0-9
28491The prefix keys @kbd{s} and @kbd{t} may be followed immediately by a
28492digit; @kbd{s 9} is equivalent to @kbd{s s 9}, and @kbd{t 9} is
28493equivalent to @kbd{s t 9}. (The @kbd{t} prefix is otherwise used
28494for trail and time/date commands.)
28495
28496@kindex s +
28497@kindex s -
28498@ignore
28499@mindex @idots
28500@end ignore
28501@kindex s *
28502@ignore
28503@mindex @null
28504@end ignore
28505@kindex s /
28506@ignore
28507@mindex @null
28508@end ignore
28509@kindex s ^
28510@ignore
28511@mindex @null
28512@end ignore
28513@kindex s |
28514@ignore
28515@mindex @null
28516@end ignore
28517@kindex s n
28518@ignore
28519@mindex @null
28520@end ignore
28521@kindex s &
28522@ignore
28523@mindex @null
28524@end ignore
28525@kindex s [
28526@ignore
28527@mindex @null
28528@end ignore
28529@kindex s ]
28530@pindex calc-store-plus
28531@pindex calc-store-minus
28532@pindex calc-store-times
28533@pindex calc-store-div
28534@pindex calc-store-power
28535@pindex calc-store-concat
28536@pindex calc-store-neg
28537@pindex calc-store-inv
28538@pindex calc-store-decr
28539@pindex calc-store-incr
28540There are also several ``arithmetic store'' commands. For example,
28541@kbd{s +} removes a value from the stack and adds it to the specified
28542variable. The other arithmetic stores are @kbd{s -}, @kbd{s *}, @kbd{s /},
28543@kbd{s ^}, and @w{@kbd{s |}} (vector concatenation), plus @kbd{s n} and
28544@kbd{s &} which negate or invert the value in a variable, and @w{@kbd{s [}}
28545and @kbd{s ]} which decrease or increase a variable by one.
28546
28547All the arithmetic stores accept the Inverse prefix to reverse the
28548order of the operands. If @expr{v} represents the contents of the
28549variable, and @expr{a} is the value drawn from the stack, then regular
40ba43b4 28550@w{@kbd{s -}} assigns
4009494e 28551@texline @math{v \coloneq v - a},
40ba43b4 28552@infoline @expr{v := v - a},
4009494e
GM
28553but @kbd{I s -} assigns
28554@texline @math{v \coloneq a - v}.
40ba43b4 28555@infoline @expr{v := a - v}.
4009494e
GM
28556While @kbd{I s *} might seem pointless, it is
28557useful if matrix multiplication is involved. Actually, all the
28558arithmetic stores use formulas designed to behave usefully both
28559forwards and backwards:
28560
28561@example
28562@group
28563s + v := v + a v := a + v
28564s - v := v - a v := a - v
28565s * v := v * a v := a * v
28566s / v := v / a v := a / v
28567s ^ v := v ^ a v := a ^ v
28568s | v := v | a v := a | v
28569s n v := v / (-1) v := (-1) / v
28570s & v := v ^ (-1) v := (-1) ^ v
28571s [ v := v - 1 v := 1 - v
28572s ] v := v - (-1) v := (-1) - v
28573@end group
28574@end example
28575
28576In the last four cases, a numeric prefix argument will be used in
28577place of the number one. (For example, @kbd{M-2 s ]} increases
28578a variable by 2, and @kbd{M-2 I s ]} replaces a variable by
28579minus-two minus the variable.
28580
28581The first six arithmetic stores can also be typed @kbd{s t +}, @kbd{s t -},
28582etc. The commands @kbd{s s +}, @kbd{s s -}, and so on are analogous
28583arithmetic stores that don't remove the value @expr{a} from the stack.
28584
28585All arithmetic stores report the new value of the variable in the
28586Trail for your information. They signal an error if the variable
28587previously had no stored value. If default simplifications have been
28588turned off, the arithmetic stores temporarily turn them on for numeric
28589arguments only (i.e., they temporarily do an @kbd{m N} command).
28590@xref{Simplification Modes}. Large vectors put in the trail by
28591these commands always use abbreviated (@kbd{t .}) mode.
28592
28593@kindex s m
28594@pindex calc-store-map
28595The @kbd{s m} command is a general way to adjust a variable's value
28596using any Calc function. It is a ``mapping'' command analogous to
28597@kbd{V M}, @kbd{V R}, etc. @xref{Reducing and Mapping}, to see
28598how to specify a function for a mapping command. Basically,
28599all you do is type the Calc command key that would invoke that
28600function normally. For example, @kbd{s m n} applies the @kbd{n}
28601key to negate the contents of the variable, so @kbd{s m n} is
28602equivalent to @kbd{s n}. Also, @kbd{s m Q} takes the square root
28603of the value stored in a variable, @kbd{s m v v} uses @kbd{v v} to
28604reverse the vector stored in the variable, and @kbd{s m H I S}
28605takes the hyperbolic arcsine of the variable contents.
28606
28607If the mapping function takes two or more arguments, the additional
28608arguments are taken from the stack; the old value of the variable
28609is provided as the first argument. Thus @kbd{s m -} with @expr{a}
28610on the stack computes @expr{v - a}, just like @kbd{s -}. With the
28611Inverse prefix, the variable's original value becomes the @emph{last}
28612argument instead of the first. Thus @kbd{I s m -} is also
28613equivalent to @kbd{I s -}.
28614
28615@kindex s x
28616@pindex calc-store-exchange
28617The @kbd{s x} (@code{calc-store-exchange}) command exchanges the value
28618of a variable with the value on the top of the stack. Naturally, the
28619variable must already have a stored value for this to work.
28620
28621You can type an equation or assignment at the @kbd{s x} prompt. The
28622command @kbd{s x a=6} takes no values from the stack; instead, it
28623pushes the old value of @samp{a} on the stack and stores @samp{a = 6}.
28624
28625@kindex s u
28626@pindex calc-unstore
28627@cindex Void variables
28628@cindex Un-storing variables
28629Until you store something in them, most variables are ``void,'' that is,
28630they contain no value at all. If they appear in an algebraic formula
28631they will be left alone even if you press @kbd{=} (@code{calc-evaluate}).
28632The @kbd{s u} (@code{calc-unstore}) command returns a variable to the
28633void state.
28634
28635@kindex s c
28636@pindex calc-copy-variable
28637The @kbd{s c} (@code{calc-copy-variable}) command copies the stored
28638value of one variable to another. One way it differs from a simple
28639@kbd{s r} followed by an @kbd{s t} (aside from saving keystrokes) is
28640that the value never goes on the stack and thus is never rounded,
28641evaluated, or simplified in any way; it is not even rounded down to the
28642current precision.
28643
28644The only variables with predefined values are the ``special constants''
28645@code{pi}, @code{e}, @code{i}, @code{phi}, and @code{gamma}. You are free
28646to unstore these variables or to store new values into them if you like,
28647although some of the algebraic-manipulation functions may assume these
28648variables represent their standard values. Calc displays a warning if
28649you change the value of one of these variables, or of one of the other
28650special variables @code{inf}, @code{uinf}, and @code{nan} (which are
28651normally void).
28652
28653Note that @code{pi} doesn't actually have 3.14159265359 stored in it,
28654but rather a special magic value that evaluates to @cpi{} at the current
28655precision. Likewise @code{e}, @code{i}, and @code{phi} evaluate
28656according to the current precision or polar mode. If you recall a value
28657from @code{pi} and store it back, this magic property will be lost. The
28658magic property is preserved, however, when a variable is copied with
28659@kbd{s c}.
28660
28661@kindex s k
28662@pindex calc-copy-special-constant
28663If one of the ``special constants'' is redefined (or undefined) so that
40ba43b4 28664it no longer has its magic property, the property can be restored with
4009494e
GM
28665@kbd{s k} (@code{calc-copy-special-constant}). This command will prompt
28666for a special constant and a variable to store it in, and so a special
28667constant can be stored in any variable. Here, the special constant that
28668you enter doesn't depend on the value of the corresponding variable;
28669@code{pi} will represent 3.14159@dots{} regardless of what is currently
28670stored in the Calc variable @code{pi}. If one of the other special
28671variables, @code{inf}, @code{uinf} or @code{nan}, is given a value, its
28672original behavior can be restored by voiding it with @kbd{s u}.
28673
28674@node Recalling Variables, Operations on Variables, Storing Variables, Store and Recall
28675@section Recalling Variables
28676
28677@noindent
28678@kindex s r
28679@pindex calc-recall
28680@cindex Recalling variables
28681The most straightforward way to extract the stored value from a variable
28682is to use the @kbd{s r} (@code{calc-recall}) command. This command prompts
28683for a variable name (similarly to @code{calc-store}), looks up the value
28684of the specified variable, and pushes that value onto the stack. It is
28685an error to try to recall a void variable.
28686
28687It is also possible to recall the value from a variable by evaluating a
28688formula containing that variable. For example, @kbd{' a @key{RET} =} is
28689the same as @kbd{s r a @key{RET}} except that if the variable is void, the
28690former will simply leave the formula @samp{a} on the stack whereas the
28691latter will produce an error message.
28692
28693@kindex r 0-9
28694The @kbd{r} prefix may be followed by a digit, so that @kbd{r 9} is
538c2573 28695equivalent to @kbd{s r 9}.
4009494e
GM
28696
28697@node Operations on Variables, Let Command, Recalling Variables, Store and Recall
28698@section Other Operations on Variables
28699
28700@noindent
28701@kindex s e
28702@pindex calc-edit-variable
28703The @kbd{s e} (@code{calc-edit-variable}) command edits the stored
28704value of a variable without ever putting that value on the stack
28705or simplifying or evaluating the value. It prompts for the name of
28706the variable to edit. If the variable has no stored value, the
28707editing buffer will start out empty. If the editing buffer is
28708empty when you press @kbd{C-c C-c} to finish, the variable will
28709be made void. @xref{Editing Stack Entries}, for a general
28710description of editing.
28711
28712The @kbd{s e} command is especially useful for creating and editing
28713rewrite rules which are stored in variables. Sometimes these rules
28714contain formulas which must not be evaluated until the rules are
28715actually used. (For example, they may refer to @samp{deriv(x,y)},
28716where @code{x} will someday become some expression involving @code{y};
28717if you let Calc evaluate the rule while you are defining it, Calc will
28718replace @samp{deriv(x,y)} with 0 because the formula @code{x} does
28719not itself refer to @code{y}.) By contrast, recalling the variable,
28720editing with @kbd{`}, and storing will evaluate the variable's value
28721as a side effect of putting the value on the stack.
28722
28723@kindex s A
28724@kindex s D
28725@ignore
28726@mindex @idots
28727@end ignore
28728@kindex s E
28729@ignore
28730@mindex @null
28731@end ignore
28732@kindex s F
28733@ignore
28734@mindex @null
28735@end ignore
28736@kindex s G
28737@ignore
28738@mindex @null
28739@end ignore
28740@kindex s H
28741@ignore
28742@mindex @null
28743@end ignore
28744@kindex s I
28745@ignore
28746@mindex @null
28747@end ignore
28748@kindex s L
28749@ignore
28750@mindex @null
28751@end ignore
28752@kindex s P
28753@ignore
28754@mindex @null
28755@end ignore
28756@kindex s R
28757@ignore
28758@mindex @null
28759@end ignore
28760@kindex s T
28761@ignore
28762@mindex @null
28763@end ignore
28764@kindex s U
28765@ignore
28766@mindex @null
28767@end ignore
28768@kindex s X
28769@pindex calc-store-AlgSimpRules
28770@pindex calc-store-Decls
28771@pindex calc-store-EvalRules
28772@pindex calc-store-FitRules
28773@pindex calc-store-GenCount
28774@pindex calc-store-Holidays
28775@pindex calc-store-IntegLimit
28776@pindex calc-store-LineStyles
28777@pindex calc-store-PointStyles
28778@pindex calc-store-PlotRejects
28779@pindex calc-store-TimeZone
28780@pindex calc-store-Units
28781@pindex calc-store-ExtSimpRules
28782There are several special-purpose variable-editing commands that
28783use the @kbd{s} prefix followed by a shifted letter:
28784
28785@table @kbd
28786@item s A
28787Edit @code{AlgSimpRules}. @xref{Algebraic Simplifications}.
28788@item s D
28789Edit @code{Decls}. @xref{Declarations}.
28790@item s E
8e7046c3 28791Edit @code{EvalRules}. @xref{Basic Simplifications}.
4009494e
GM
28792@item s F
28793Edit @code{FitRules}. @xref{Curve Fitting}.
28794@item s G
28795Edit @code{GenCount}. @xref{Solving Equations}.
28796@item s H
28797Edit @code{Holidays}. @xref{Business Days}.
28798@item s I
28799Edit @code{IntegLimit}. @xref{Calculus}.
28800@item s L
28801Edit @code{LineStyles}. @xref{Graphics}.
28802@item s P
28803Edit @code{PointStyles}. @xref{Graphics}.
28804@item s R
28805Edit @code{PlotRejects}. @xref{Graphics}.
28806@item s T
28807Edit @code{TimeZone}. @xref{Time Zones}.
28808@item s U
28809Edit @code{Units}. @xref{User-Defined Units}.
28810@item s X
28811Edit @code{ExtSimpRules}. @xref{Unsafe Simplifications}.
28812@end table
28813
28814These commands are just versions of @kbd{s e} that use fixed variable
28815names rather than prompting for the variable name.
28816
28817@kindex s p
28818@pindex calc-permanent-variable
28819@cindex Storing variables
28820@cindex Permanent variables
28821@cindex Calc init file, variables
28822The @kbd{s p} (@code{calc-permanent-variable}) command saves a
28823variable's value permanently in your Calc init file (the file given by
dcf7843e 28824the variable @code{calc-settings-file}, typically @file{~/.emacs.d/calc.el}), so
4009494e
GM
28825that its value will still be available in future Emacs sessions. You
28826can re-execute @w{@kbd{s p}} later on to update the saved value, but the
28827only way to remove a saved variable is to edit your calc init file
28828by hand. (@xref{General Mode Commands}, for a way to tell Calc to
28829use a different file for the Calc init file.)
28830
28831If you do not specify the name of a variable to save (i.e.,
28832@kbd{s p @key{RET}}), all Calc variables with defined values
28833are saved except for the special constants @code{pi}, @code{e},
28834@code{i}, @code{phi}, and @code{gamma}; the variables @code{TimeZone}
28835and @code{PlotRejects};
28836@code{FitRules}, @code{DistribRules}, and other built-in rewrite
28837rules; and @code{PlotData@var{n}} variables generated
28838by the graphics commands. (You can still save these variables by
28839explicitly naming them in an @kbd{s p} command.)
28840
28841@kindex s i
28842@pindex calc-insert-variables
28843The @kbd{s i} (@code{calc-insert-variables}) command writes
28844the values of all Calc variables into a specified buffer.
28845The variables are written with the prefix @code{var-} in the form of
40ba43b4 28846Lisp @code{setq} commands
4009494e
GM
28847which store the values in string form. You can place these commands
28848in your Calc init file (or @file{.emacs}) if you wish, though in this case it
28849would be easier to use @kbd{s p @key{RET}}. (Note that @kbd{s i}
28850omits the same set of variables as @w{@kbd{s p @key{RET}}}; the difference
28851is that @kbd{s i} will store the variables in any buffer, and it also
28852stores in a more human-readable format.)
28853
28854@node Let Command, Evaluates-To Operator, Operations on Variables, Store and Recall
28855@section The Let Command
28856
28857@noindent
28858@kindex s l
28859@pindex calc-let
28860@cindex Variables, temporary assignment
28861@cindex Temporary assignment to variables
28862If you have an expression like @samp{a+b^2} on the stack and you wish to
28863compute its value where @expr{b=3}, you can simply store 3 in @expr{b} and
28864then press @kbd{=} to reevaluate the formula. This has the side-effect
28865of leaving the stored value of 3 in @expr{b} for future operations.
28866
28867The @kbd{s l} (@code{calc-let}) command evaluates a formula under a
28868@emph{temporary} assignment of a variable. It stores the value on the
28869top of the stack into the specified variable, then evaluates the
28870second-to-top stack entry, then restores the original value (or lack of one)
28871in the variable. Thus after @kbd{'@w{ }a+b^2 @key{RET} 3 s l b @key{RET}},
28872the stack will contain the formula @samp{a + 9}. The subsequent command
28873@kbd{@w{5 s l a} @key{RET}} will replace this formula with the number 14.
28874The variables @samp{a} and @samp{b} are not permanently affected in any way
28875by these commands.
28876
28877The value on the top of the stack may be an equation or assignment, or
28878a vector of equations or assignments, in which case the default will be
28879analogous to the case of @kbd{s t @key{RET}}. @xref{Storing Variables}.
28880
28881Also, you can answer the variable-name prompt with an equation or
28882assignment: @kbd{s l b=3 @key{RET}} is the same as storing 3 on the stack
28883and typing @kbd{s l b @key{RET}}.
28884
28885The @kbd{a b} (@code{calc-substitute}) command is another way to substitute
28886a variable with a value in a formula. It does an actual substitution
28887rather than temporarily assigning the variable and evaluating. For
28888example, letting @expr{n=2} in @samp{f(n pi)} with @kbd{a b} will
28889produce @samp{f(2 pi)}, whereas @kbd{s l} would give @samp{f(6.28)}
28890since the evaluation step will also evaluate @code{pi}.
28891
28892@node Evaluates-To Operator, , Let Command, Store and Recall
28893@section The Evaluates-To Operator
28894
28895@noindent
28896@tindex evalto
28897@tindex =>
28898@cindex Evaluates-to operator
28899@cindex @samp{=>} operator
28900The special algebraic symbol @samp{=>} is known as the @dfn{evaluates-to
28901operator}. (It will show up as an @code{evalto} function call in
c1dabff0 28902other language modes like Pascal and @LaTeX{}.) This is a binary
4009494e
GM
28903operator, that is, it has a lefthand and a righthand argument,
28904although it can be entered with the righthand argument omitted.
28905
28906A formula like @samp{@var{a} => @var{b}} is evaluated by Calc as
28907follows: First, @var{a} is not simplified or modified in any
28908way. The previous value of argument @var{b} is thrown away; the
28909formula @var{a} is then copied and evaluated as if by the @kbd{=}
28910command according to all current modes and stored variable values,
28911and the result is installed as the new value of @var{b}.
28912
28913For example, suppose you enter the algebraic formula @samp{2 + 3 => 17}.
28914The number 17 is ignored, and the lefthand argument is left in its
28915unevaluated form; the result is the formula @samp{2 + 3 => 5}.
28916
28917@kindex s =
28918@pindex calc-evalto
28919You can enter an @samp{=>} formula either directly using algebraic
28920entry (in which case the righthand side may be omitted since it is
28921going to be replaced right away anyhow), or by using the @kbd{s =}
28922(@code{calc-evalto}) command, which takes @var{a} from the stack
28923and replaces it with @samp{@var{a} => @var{b}}.
28924
28925Calc keeps track of all @samp{=>} operators on the stack, and
28926recomputes them whenever anything changes that might affect their
28927values, i.e., a mode setting or variable value. This occurs only
28928if the @samp{=>} operator is at the top level of the formula, or
28929if it is part of a top-level vector. In other words, pushing
28930@samp{2 + (a => 17)} will change the 17 to the actual value of
28931@samp{a} when you enter the formula, but the result will not be
28932dynamically updated when @samp{a} is changed later because the
28933@samp{=>} operator is buried inside a sum. However, a vector
28934of @samp{=>} operators will be recomputed, since it is convenient
28935to push a vector like @samp{[a =>, b =>, c =>]} on the stack to
28936make a concise display of all the variables in your problem.
28937(Another way to do this would be to use @samp{[a, b, c] =>},
28938which provides a slightly different format of display. You
28939can use whichever you find easiest to read.)
28940
28941@kindex m C
28942@pindex calc-auto-recompute
28943The @kbd{m C} (@code{calc-auto-recompute}) command allows you to
28944turn this automatic recomputation on or off. If you turn
28945recomputation off, you must explicitly recompute an @samp{=>}
28946operator on the stack in one of the usual ways, such as by
28947pressing @kbd{=}. Turning recomputation off temporarily can save
28948a lot of time if you will be changing several modes or variables
28949before you look at the @samp{=>} entries again.
28950
28951Most commands are not especially useful with @samp{=>} operators
28952as arguments. For example, given @samp{x + 2 => 17}, it won't
28953work to type @kbd{1 +} to get @samp{x + 3 => 18}. If you want
28954to operate on the lefthand side of the @samp{=>} operator on
28955the top of the stack, type @kbd{j 1} (that's the digit ``one'')
28956to select the lefthand side, execute your commands, then type
28957@kbd{j u} to unselect.
28958
28959All current modes apply when an @samp{=>} operator is computed,
28960including the current simplification mode. Recall that the
8e7046c3
JB
28961formula @samp{arcsin(sin(x))} will not be handled by Calc's algebraic
28962simplifications, but Calc's unsafe simplifications will reduce it to
28963@samp{x}. If you enter @samp{arcsin(sin(x)) =>} normally, the result
28964will be @samp{arcsin(sin(x)) => arcsin(sin(x))}. If you change to
28965Extended Simplification mode, the result will be
28966@samp{arcsin(sin(x)) => x}. However, just pressing @kbd{a e}
28967once will have no effect on @samp{arcsin(sin(x)) => arcsin(sin(x))},
4009494e
GM
28968because the righthand side depends only on the lefthand side
28969and the current mode settings, and the lefthand side is not
8e7046c3 28970affected by commands like @kbd{a e}.
4009494e
GM
28971
28972The ``let'' command (@kbd{s l}) has an interesting interaction
28973with the @samp{=>} operator. The @kbd{s l} command evaluates the
28974second-to-top stack entry with the top stack entry supplying
28975a temporary value for a given variable. As you might expect,
28976if that stack entry is an @samp{=>} operator its righthand
28977side will temporarily show this value for the variable. In
28978fact, all @samp{=>}s on the stack will be updated if they refer
28979to that variable. But this change is temporary in the sense
28980that the next command that causes Calc to look at those stack
28981entries will make them revert to the old variable value.
28982
28983@smallexample
28984@group
289852: a => a 2: a => 17 2: a => a
289861: a + 1 => a + 1 1: a + 1 => 18 1: a + 1 => a + 1
28987 . . .
28988
28989 17 s l a @key{RET} p 8 @key{RET}
28990@end group
28991@end smallexample
28992
28993Here the @kbd{p 8} command changes the current precision,
28994thus causing the @samp{=>} forms to be recomputed after the
28995influence of the ``let'' is gone. The @kbd{d @key{SPC}} command
28996(@code{calc-refresh}) is a handy way to force the @samp{=>}
28997operators on the stack to be recomputed without any other
28998side effects.
28999
29000@kindex s :
29001@pindex calc-assign
29002@tindex assign
29003@tindex :=
29004Embedded mode also uses @samp{=>} operators. In Embedded mode,
29005the lefthand side of an @samp{=>} operator can refer to variables
29006assigned elsewhere in the file by @samp{:=} operators. The
29007assignment operator @samp{a := 17} does not actually do anything
29008by itself. But Embedded mode recognizes it and marks it as a sort
29009of file-local definition of the variable. You can enter @samp{:=}
29010operators in Algebraic mode, or by using the @kbd{s :}
29011(@code{calc-assign}) [@code{assign}] command which takes a variable
29012and value from the stack and replaces them with an assignment.
29013
29014@xref{TeX and LaTeX Language Modes}, for the way @samp{=>} appears in
29015@TeX{} language output. The @dfn{eqn} mode gives similar
29016treatment to @samp{=>}.
29017
29018@node Graphics, Kill and Yank, Store and Recall, Top
29019@chapter Graphics
29020
29021@noindent
29022The commands for graphing data begin with the @kbd{g} prefix key. Calc
29023uses GNUPLOT 2.0 or later to do graphics. These commands will only work
29024if GNUPLOT is available on your system. (While GNUPLOT sounds like
29025a relative of GNU Emacs, it is actually completely unrelated.
29026However, it is free software. It can be obtained from
29027@samp{http://www.gnuplot.info}.)
29028
29029@vindex calc-gnuplot-name
29030If you have GNUPLOT installed on your system but Calc is unable to
66783bb4
EZ
29031find it, you may need to set the @code{calc-gnuplot-name} variable in
29032your Calc init file or @file{.emacs}. You may also need to set some
29033Lisp variables to show Calc how to run GNUPLOT on your system; these
29034are described under @kbd{g D} and @kbd{g O} below. If you are using
29035the X window system or MS-Windows, Calc will configure GNUPLOT for you
29036automatically. If you have GNUPLOT 3.0 or later and you are using a
29037Unix or GNU system without X, Calc will configure GNUPLOT to display
29038graphs using simple character graphics that will work on any
29039Posix-compatible terminal.
4009494e
GM
29040
29041@menu
29042* Basic Graphics::
29043* Three Dimensional Graphics::
29044* Managing Curves::
29045* Graphics Options::
29046* Devices::
29047@end menu
29048
29049@node Basic Graphics, Three Dimensional Graphics, Graphics, Graphics
29050@section Basic Graphics
29051
29052@noindent
29053@kindex g f
29054@pindex calc-graph-fast
29055The easiest graphics command is @kbd{g f} (@code{calc-graph-fast}).
29056This command takes two vectors of equal length from the stack.
29057The vector at the top of the stack represents the ``y'' values of
29058the various data points. The vector in the second-to-top position
29059represents the corresponding ``x'' values. This command runs
29060GNUPLOT (if it has not already been started by previous graphing
29061commands) and displays the set of data points. The points will
29062be connected by lines, and there will also be some kind of symbol
29063to indicate the points themselves.
29064
29065The ``x'' entry may instead be an interval form, in which case suitable
29066``x'' values are interpolated between the minimum and maximum values of
29067the interval (whether the interval is open or closed is ignored).
29068
29069The ``x'' entry may also be a number, in which case Calc uses the
29070sequence of ``x'' values @expr{x}, @expr{x+1}, @expr{x+2}, etc.
29071(Generally the number 0 or 1 would be used for @expr{x} in this case.)
29072
29073The ``y'' entry may be any formula instead of a vector. Calc effectively
29074uses @kbd{N} (@code{calc-eval-num}) to evaluate variables in the formula;
29075the result of this must be a formula in a single (unassigned) variable.
29076The formula is plotted with this variable taking on the various ``x''
29077values. Graphs of formulas by default use lines without symbols at the
29078computed data points. Note that if neither ``x'' nor ``y'' is a vector,
29079Calc guesses at a reasonable number of data points to use. See the
29080@kbd{g N} command below. (The ``x'' values must be either a vector
29081or an interval if ``y'' is a formula.)
29082
29083@ignore
29084@starindex
29085@end ignore
29086@tindex xy
29087If ``y'' is (or evaluates to) a formula of the form
29088@samp{xy(@var{x}, @var{y})} then the result is a
29089parametric plot. The two arguments of the fictitious @code{xy} function
29090are used as the ``x'' and ``y'' coordinates of the curve, respectively.
29091In this case the ``x'' vector or interval you specified is not directly
29092visible in the graph. For example, if ``x'' is the interval @samp{[0..360]}
29093and ``y'' is the formula @samp{xy(sin(t), cos(t))}, the resulting graph
29094will be a circle.
29095
29096Also, ``x'' and ``y'' may each be variable names, in which case Calc
29097looks for suitable vectors, intervals, or formulas stored in those
29098variables.
29099
29100The ``x'' and ``y'' values for the data points (as pulled from the vectors,
29101calculated from the formulas, or interpolated from the intervals) should
29102be real numbers (integers, fractions, or floats). One exception to this
29103is that the ``y'' entry can consist of a vector of numbers combined with
29104error forms, in which case the points will be plotted with the
29105appropriate error bars. Other than this, if either the ``x''
29106value or the ``y'' value of a given data point is not a real number, that
29107data point will be omitted from the graph. The points on either side
29108of the invalid point will @emph{not} be connected by a line.
29109
29110See the documentation for @kbd{g a} below for a description of the way
29111numeric prefix arguments affect @kbd{g f}.
29112
29113@cindex @code{PlotRejects} variable
29114@vindex PlotRejects
29115If you store an empty vector in the variable @code{PlotRejects}
29116(i.e., @kbd{[ ] s t PlotRejects}), Calc will append information to
29117this vector for every data point which was rejected because its
29118``x'' or ``y'' values were not real numbers. The result will be
29119a matrix where each row holds the curve number, data point number,
29120``x'' value, and ``y'' value for a rejected data point.
29121@xref{Evaluates-To Operator}, for a handy way to keep tabs on the
29122current value of @code{PlotRejects}. @xref{Operations on Variables},
29123for the @kbd{s R} command which is another easy way to examine
29124@code{PlotRejects}.
29125
29126@kindex g c
29127@pindex calc-graph-clear
29128To clear the graphics display, type @kbd{g c} (@code{calc-graph-clear}).
29129If the GNUPLOT output device is an X window, the window will go away.
29130Effects on other kinds of output devices will vary. You don't need
29131to use @kbd{g c} if you don't want to---if you give another @kbd{g f}
29132or @kbd{g p} command later on, it will reuse the existing graphics
29133window if there is one.
29134
29135@node Three Dimensional Graphics, Managing Curves, Basic Graphics, Graphics
29136@section Three-Dimensional Graphics
29137
29138@kindex g F
29139@pindex calc-graph-fast-3d
29140The @kbd{g F} (@code{calc-graph-fast-3d}) command makes a three-dimensional
29141graph. It works only if you have GNUPLOT 3.0 or later; with GNUPLOT 2.0,
29142you will see a GNUPLOT error message if you try this command.
29143
29144The @kbd{g F} command takes three values from the stack, called ``x'',
29145``y'', and ``z'', respectively. As was the case for 2D graphs, there
29146are several options for these values.
29147
29148In the first case, ``x'' and ``y'' are each vectors (not necessarily of
29149the same length); either or both may instead be interval forms. The
29150``z'' value must be a matrix with the same number of rows as elements
29151in ``x'', and the same number of columns as elements in ``y''. The
40ba43b4 29152result is a surface plot where
4009494e 29153@texline @math{z_{ij}}
40ba43b4 29154@infoline @expr{z_ij}
4009494e
GM
29155is the height of the point
29156at coordinate @expr{(x_i, y_j)} on the surface. The 3D graph will
29157be displayed from a certain default viewpoint; you can change this
29158viewpoint by adding a @samp{set view} to the @samp{*Gnuplot Commands*}
29159buffer as described later. See the GNUPLOT documentation for a
29160description of the @samp{set view} command.
29161
29162Each point in the matrix will be displayed as a dot in the graph,
29163and these points will be connected by a grid of lines (@dfn{isolines}).
29164
29165In the second case, ``x'', ``y'', and ``z'' are all vectors of equal
29166length. The resulting graph displays a 3D line instead of a surface,
29167where the coordinates of points along the line are successive triplets
29168of values from the input vectors.
29169
29170In the third case, ``x'' and ``y'' are vectors or interval forms, and
29171``z'' is any formula involving two variables (not counting variables
29172with assigned values). These variables are sorted into alphabetical
29173order; the first takes on values from ``x'' and the second takes on
29174values from ``y'' to form a matrix of results that are graphed as a
291753D surface.
29176
29177@ignore
29178@starindex
29179@end ignore
29180@tindex xyz
29181If the ``z'' formula evaluates to a call to the fictitious function
29182@samp{xyz(@var{x}, @var{y}, @var{z})}, then the result is a
29183``parametric surface.'' In this case, the axes of the graph are
29184taken from the @var{x} and @var{y} values in these calls, and the
29185``x'' and ``y'' values from the input vectors or intervals are used only
29186to specify the range of inputs to the formula. For example, plotting
29187@samp{[0..360], [0..180], xyz(sin(x)*sin(y), cos(x)*sin(y), cos(y))}
29188will draw a sphere. (Since the default resolution for 3D plots is
291895 steps in each of ``x'' and ``y'', this will draw a very crude
29190sphere. You could use the @kbd{g N} command, described below, to
29191increase this resolution, or specify the ``x'' and ``y'' values as
29192vectors with more than 5 elements.
29193
29194It is also possible to have a function in a regular @kbd{g f} plot
29195evaluate to an @code{xyz} call. Since @kbd{g f} plots a line, not
29196a surface, the result will be a 3D parametric line. For example,
29197@samp{[[0..720], xyz(sin(x), cos(x), x)]} will plot two turns of a
29198helix (a three-dimensional spiral).
29199
29200As for @kbd{g f}, each of ``x'', ``y'', and ``z'' may instead be
29201variables containing the relevant data.
29202
29203@node Managing Curves, Graphics Options, Three Dimensional Graphics, Graphics
29204@section Managing Curves
29205
29206@noindent
29207The @kbd{g f} command is really shorthand for the following commands:
29208@kbd{C-u g d g a g p}. Likewise, @w{@kbd{g F}} is shorthand for
29209@kbd{C-u g d g A g p}. You can gain more control over your graph
29210by using these commands directly.
29211
29212@kindex g a
29213@pindex calc-graph-add
29214The @kbd{g a} (@code{calc-graph-add}) command adds the ``curve''
29215represented by the two values on the top of the stack to the current
29216graph. You can have any number of curves in the same graph. When
29217you give the @kbd{g p} command, all the curves will be drawn superimposed
29218on the same axes.
29219
29220The @kbd{g a} command (and many others that affect the current graph)
29221will cause a special buffer, @samp{*Gnuplot Commands*}, to be displayed
29222in another window. This buffer is a template of the commands that will
29223be sent to GNUPLOT when it is time to draw the graph. The first
29224@kbd{g a} command adds a @code{plot} command to this buffer. Succeeding
29225@kbd{g a} commands add extra curves onto that @code{plot} command.
29226Other graph-related commands put other GNUPLOT commands into this
29227buffer. In normal usage you never need to work with this buffer
29228directly, but you can if you wish. The only constraint is that there
29229must be only one @code{plot} command, and it must be the last command
29230in the buffer. If you want to save and later restore a complete graph
29231configuration, you can use regular Emacs commands to save and restore
29232the contents of the @samp{*Gnuplot Commands*} buffer.
29233
29234@vindex PlotData1
29235@vindex PlotData2
29236If the values on the stack are not variable names, @kbd{g a} will invent
29237variable names for them (of the form @samp{PlotData@var{n}}) and store
29238the values in those variables. The ``x'' and ``y'' variables are what
29239go into the @code{plot} command in the template. If you add a curve
29240that uses a certain variable and then later change that variable, you
29241can replot the graph without having to delete and re-add the curve.
29242That's because the variable name, not the vector, interval or formula
29243itself, is what was added by @kbd{g a}.
29244
29245A numeric prefix argument on @kbd{g a} or @kbd{g f} changes the way
29246stack entries are interpreted as curves. With a positive prefix
29247argument @expr{n}, the top @expr{n} stack entries are ``y'' values
29248for @expr{n} different curves which share a common ``x'' value in
29249the @expr{n+1}st stack entry. (Thus @kbd{g a} with no prefix
29250argument is equivalent to @kbd{C-u 1 g a}.)
29251
29252A prefix of zero or plain @kbd{C-u} means to take two stack entries,
29253``x'' and ``y'' as usual, but to interpret ``y'' as a vector of
29254``y'' values for several curves that share a common ``x''.
29255
29256A negative prefix argument tells Calc to read @expr{n} vectors from
29257the stack; each vector @expr{[x, y]} describes an independent curve.
29258This is the only form of @kbd{g a} that creates several curves at once
29259that don't have common ``x'' values. (Of course, the range of ``x''
29260values covered by all the curves ought to be roughly the same if
29261they are to look nice on the same graph.)
29262
40ba43b4 29263For example, to plot
4009494e 29264@texline @math{\sin n x}
40ba43b4 29265@infoline @expr{sin(n x)}
4009494e
GM
29266for integers @expr{n}
29267from 1 to 5, you could use @kbd{v x} to create a vector of integers
29268(@expr{n}), then @kbd{V M '} or @kbd{V M $} to map @samp{sin(n x)}
29269across this vector. The resulting vector of formulas is suitable
29270for use as the ``y'' argument to a @kbd{C-u g a} or @kbd{C-u g f}
29271command.
29272
29273@kindex g A
29274@pindex calc-graph-add-3d
29275The @kbd{g A} (@code{calc-graph-add-3d}) command adds a 3D curve
29276to the graph. It is not valid to intermix 2D and 3D curves in a
29277single graph. This command takes three arguments, ``x'', ``y'',
29278and ``z'', from the stack. With a positive prefix @expr{n}, it
29279takes @expr{n+2} arguments (common ``x'' and ``y'', plus @expr{n}
29280separate ``z''s). With a zero prefix, it takes three stack entries
29281but the ``z'' entry is a vector of curve values. With a negative
29282prefix @expr{-n}, it takes @expr{n} vectors of the form @expr{[x, y, z]}.
29283The @kbd{g A} command works by adding a @code{splot} (surface-plot)
29284command to the @samp{*Gnuplot Commands*} buffer.
29285
29286(Although @kbd{g a} adds a 2D @code{plot} command to the
29287@samp{*Gnuplot Commands*} buffer, Calc changes this to @code{splot}
29288before sending it to GNUPLOT if it notices that the data points are
29289evaluating to @code{xyz} calls. It will not work to mix 2D and 3D
29290@kbd{g a} curves in a single graph, although Calc does not currently
29291check for this.)
29292
29293@kindex g d
29294@pindex calc-graph-delete
29295The @kbd{g d} (@code{calc-graph-delete}) command deletes the most
29296recently added curve from the graph. It has no effect if there are
29297no curves in the graph. With a numeric prefix argument of any kind,
29298it deletes all of the curves from the graph.
29299
29300@kindex g H
29301@pindex calc-graph-hide
29302The @kbd{g H} (@code{calc-graph-hide}) command ``hides'' or ``unhides''
29303the most recently added curve. A hidden curve will not appear in
29304the actual plot, but information about it such as its name and line and
29305point styles will be retained.
29306
29307@kindex g j
29308@pindex calc-graph-juggle
29309The @kbd{g j} (@code{calc-graph-juggle}) command moves the curve
29310at the end of the list (the ``most recently added curve'') to the
29311front of the list. The next-most-recent curve is thus exposed for
29312@w{@kbd{g d}} or similar commands to use. With @kbd{g j} you can work
29313with any curve in the graph even though curve-related commands only
29314affect the last curve in the list.
29315
29316@kindex g p
29317@pindex calc-graph-plot
29318The @kbd{g p} (@code{calc-graph-plot}) command uses GNUPLOT to draw
29319the graph described in the @samp{*Gnuplot Commands*} buffer. Any
29320GNUPLOT parameters which are not defined by commands in this buffer
29321are reset to their default values. The variables named in the @code{plot}
29322command are written to a temporary data file and the variable names
29323are then replaced by the file name in the template. The resulting
29324plotting commands are fed to the GNUPLOT program. See the documentation
29325for the GNUPLOT program for more specific information. All temporary
29326files are removed when Emacs or GNUPLOT exits.
29327
29328If you give a formula for ``y'', Calc will remember all the values that
29329it calculates for the formula so that later plots can reuse these values.
29330Calc throws out these saved values when you change any circumstances
29331that may affect the data, such as switching from Degrees to Radians
29332mode, or changing the value of a parameter in the formula. You can
29333force Calc to recompute the data from scratch by giving a negative
29334numeric prefix argument to @kbd{g p}.
29335
29336Calc uses a fairly rough step size when graphing formulas over intervals.
29337This is to ensure quick response. You can ``refine'' a plot by giving
29338a positive numeric prefix argument to @kbd{g p}. Calc goes through
29339the data points it has computed and saved from previous plots of the
29340function, and computes and inserts a new data point midway between
29341each of the existing points. You can refine a plot any number of times,
29342but beware that the amount of calculation involved doubles each time.
29343
29344Calc does not remember computed values for 3D graphs. This means the
29345numerix prefix argument, if any, to @kbd{g p} is effectively ignored if
29346the current graph is three-dimensional.
29347
29348@kindex g P
29349@pindex calc-graph-print
29350The @kbd{g P} (@code{calc-graph-print}) command is like @kbd{g p},
29351except that it sends the output to a printer instead of to the
29352screen. More precisely, @kbd{g p} looks for @samp{set terminal}
29353or @samp{set output} commands in the @samp{*Gnuplot Commands*} buffer;
29354lacking these it uses the default settings. However, @kbd{g P}
29355ignores @samp{set terminal} and @samp{set output} commands and
29356uses a different set of default values. All of these values are
29357controlled by the @kbd{g D} and @kbd{g O} commands discussed below.
29358Provided everything is set up properly, @kbd{g p} will plot to
29359the screen unless you have specified otherwise and @kbd{g P} will
29360always plot to the printer.
29361
29362@node Graphics Options, Devices, Managing Curves, Graphics
29363@section Graphics Options
29364
29365@noindent
29366@kindex g g
29367@pindex calc-graph-grid
29368The @kbd{g g} (@code{calc-graph-grid}) command turns the ``grid''
29369on and off. It is off by default; tick marks appear only at the
29370edges of the graph. With the grid turned on, dotted lines appear
29371across the graph at each tick mark. Note that this command only
29372changes the setting in @samp{*Gnuplot Commands*}; to see the effects
29373of the change you must give another @kbd{g p} command.
29374
29375@kindex g b
29376@pindex calc-graph-border
29377The @kbd{g b} (@code{calc-graph-border}) command turns the border
29378(the box that surrounds the graph) on and off. It is on by default.
29379This command will only work with GNUPLOT 3.0 and later versions.
29380
29381@kindex g k
29382@pindex calc-graph-key
29383The @kbd{g k} (@code{calc-graph-key}) command turns the ``key''
29384on and off. The key is a chart in the corner of the graph that
29385shows the correspondence between curves and line styles. It is
29386off by default, and is only really useful if you have several
29387curves on the same graph.
29388
29389@kindex g N
29390@pindex calc-graph-num-points
29391The @kbd{g N} (@code{calc-graph-num-points}) command allows you
29392to select the number of data points in the graph. This only affects
29393curves where neither ``x'' nor ``y'' is specified as a vector.
29394Enter a blank line to revert to the default value (initially 15).
29395With no prefix argument, this command affects only the current graph.
29396With a positive prefix argument this command changes or, if you enter
29397a blank line, displays the default number of points used for all
29398graphs created by @kbd{g a} that don't specify the resolution explicitly.
29399With a negative prefix argument, this command changes or displays
29400the default value (initially 5) used for 3D graphs created by @kbd{g A}.
29401Note that a 3D setting of 5 means that a total of @expr{5^2 = 25} points
29402will be computed for the surface.
29403
29404Data values in the graph of a function are normally computed to a
29405precision of five digits, regardless of the current precision at the
29406time. This is usually more than adequate, but there are cases where
29407it will not be. For example, plotting @expr{1 + x} with @expr{x} in the
29408interval @samp{[0 ..@: 1e-6]} will round all the data points down
29409to 1.0! Putting the command @samp{set precision @var{n}} in the
29410@samp{*Gnuplot Commands*} buffer will cause the data to be computed
29411at precision @var{n} instead of 5. Since this is such a rare case,
29412there is no keystroke-based command to set the precision.
29413
29414@kindex g h
29415@pindex calc-graph-header
29416The @kbd{g h} (@code{calc-graph-header}) command sets the title
29417for the graph. This will show up centered above the graph.
29418The default title is blank (no title).
29419
29420@kindex g n
29421@pindex calc-graph-name
29422The @kbd{g n} (@code{calc-graph-name}) command sets the title of an
29423individual curve. Like the other curve-manipulating commands, it
29424affects the most recently added curve, i.e., the last curve on the
29425list in the @samp{*Gnuplot Commands*} buffer. To set the title of
29426the other curves you must first juggle them to the end of the list
29427with @kbd{g j}, or edit the @samp{*Gnuplot Commands*} buffer by hand.
29428Curve titles appear in the key; if the key is turned off they are
29429not used.
29430
29431@kindex g t
29432@kindex g T
29433@pindex calc-graph-title-x
29434@pindex calc-graph-title-y
29435The @kbd{g t} (@code{calc-graph-title-x}) and @kbd{g T}
29436(@code{calc-graph-title-y}) commands set the titles on the ``x''
29437and ``y'' axes, respectively. These titles appear next to the
29438tick marks on the left and bottom edges of the graph, respectively.
29439Calc does not have commands to control the tick marks themselves,
29440but you can edit them into the @samp{*Gnuplot Commands*} buffer if
29441you wish. See the GNUPLOT documentation for details.
29442
29443@kindex g r
29444@kindex g R
29445@pindex calc-graph-range-x
29446@pindex calc-graph-range-y
29447The @kbd{g r} (@code{calc-graph-range-x}) and @kbd{g R}
29448(@code{calc-graph-range-y}) commands set the range of values on the
29449``x'' and ``y'' axes, respectively. You are prompted to enter a
29450suitable range. This should be either a pair of numbers of the
29451form, @samp{@var{min}:@var{max}}, or a blank line to revert to the
29452default behavior of setting the range based on the range of values
29453in the data, or @samp{$} to take the range from the top of the stack.
29454Ranges on the stack can be represented as either interval forms or
29455vectors: @samp{[@var{min} ..@: @var{max}]} or @samp{[@var{min}, @var{max}]}.
29456
29457@kindex g l
29458@kindex g L
29459@pindex calc-graph-log-x
29460@pindex calc-graph-log-y
29461The @kbd{g l} (@code{calc-graph-log-x}) and @kbd{g L} (@code{calc-graph-log-y})
29462commands allow you to set either or both of the axes of the graph to
29463be logarithmic instead of linear.
29464
29465@kindex g C-l
29466@kindex g C-r
29467@kindex g C-t
29468@pindex calc-graph-log-z
29469@pindex calc-graph-range-z
29470@pindex calc-graph-title-z
29471For 3D plots, @kbd{g C-t}, @kbd{g C-r}, and @kbd{g C-l} (those are
29472letters with the Control key held down) are the corresponding commands
29473for the ``z'' axis.
29474
29475@kindex g z
29476@kindex g Z
29477@pindex calc-graph-zero-x
29478@pindex calc-graph-zero-y
29479The @kbd{g z} (@code{calc-graph-zero-x}) and @kbd{g Z}
29480(@code{calc-graph-zero-y}) commands control whether a dotted line is
29481drawn to indicate the ``x'' and/or ``y'' zero axes. (These are the same
29482dotted lines that would be drawn there anyway if you used @kbd{g g} to
29483turn the ``grid'' feature on.) Zero-axis lines are on by default, and
29484may be turned off only in GNUPLOT 3.0 and later versions. They are
29485not available for 3D plots.
29486
29487@kindex g s
29488@pindex calc-graph-line-style
29489The @kbd{g s} (@code{calc-graph-line-style}) command turns the connecting
29490lines on or off for the most recently added curve, and optionally selects
29491the style of lines to be used for that curve. Plain @kbd{g s} simply
29492toggles the lines on and off. With a numeric prefix argument, @kbd{g s}
29493turns lines on and sets a particular line style. Line style numbers
29494start at one and their meanings vary depending on the output device.
29495GNUPLOT guarantees that there will be at least six different line styles
29496available for any device.
29497
29498@kindex g S
29499@pindex calc-graph-point-style
29500The @kbd{g S} (@code{calc-graph-point-style}) command similarly turns
29501the symbols at the data points on or off, or sets the point style.
29502If you turn both lines and points off, the data points will show as
40ba43b4
PE
29503tiny dots. If the ``y'' values being plotted contain error forms and
29504the connecting lines are turned off, then this command will also turn
4009494e
GM
29505the error bars on or off.
29506
29507@cindex @code{LineStyles} variable
29508@cindex @code{PointStyles} variable
29509@vindex LineStyles
29510@vindex PointStyles
29511Another way to specify curve styles is with the @code{LineStyles} and
29512@code{PointStyles} variables. These variables initially have no stored
29513values, but if you store a vector of integers in one of these variables,
29514the @kbd{g a} and @kbd{g f} commands will use those style numbers
29515instead of the defaults for new curves that are added to the graph.
29516An entry should be a positive integer for a specific style, or 0 to let
29517the style be chosen automatically, or @mathit{-1} to turn off lines or points
29518altogether. If there are more curves than elements in the vector, the
29519last few curves will continue to have the default styles. Of course,
29520you can later use @kbd{g s} and @kbd{g S} to change any of these styles.
29521
29522For example, @kbd{'[2 -1 3] @key{RET} s t LineStyles} causes the first curve
29523to have lines in style number 2, the second curve to have no connecting
29524lines, and the third curve to have lines in style 3. Point styles will
29525still be assigned automatically, but you could store another vector in
29526@code{PointStyles} to define them, too.
29527
29528@node Devices, , Graphics Options, Graphics
29529@section Graphical Devices
29530
29531@noindent
29532@kindex g D
29533@pindex calc-graph-device
29534The @kbd{g D} (@code{calc-graph-device}) command sets the device name
29535(or ``terminal name'' in GNUPLOT lingo) to be used by @kbd{g p} commands
29536on this graph. It does not affect the permanent default device name.
29537If you enter a blank name, the device name reverts to the default.
29538Enter @samp{?} to see a list of supported devices.
29539
29540With a positive numeric prefix argument, @kbd{g D} instead sets
29541the default device name, used by all plots in the future which do
29542not override it with a plain @kbd{g D} command. If you enter a
29543blank line this command shows you the current default. The special
29544name @code{default} signifies that Calc should choose @code{x11} if
29545the X window system is in use (as indicated by the presence of a
66783bb4
EZ
29546@code{DISPLAY} environment variable), @code{windows} on MS-Windows, or
29547otherwise @code{dumb} under GNUPLOT 3.0 and later, or
29548@code{postscript} under GNUPLOT 2.0. This is the initial default
29549value.
4009494e
GM
29550
29551The @code{dumb} device is an interface to ``dumb terminals,'' i.e.,
29552terminals with no special graphics facilities. It writes a crude
29553picture of the graph composed of characters like @code{-} and @code{|}
29554to a buffer called @samp{*Gnuplot Trail*}, which Calc then displays.
29555The graph is made the same size as the Emacs screen, which on most
40ba43b4 29556dumb terminals will be
4009494e
GM
29557@texline @math{80\times24}
29558@infoline 80x24
29559characters. The graph is displayed in
29560an Emacs ``recursive edit''; type @kbd{q} or @kbd{C-c C-c} to exit
29561the recursive edit and return to Calc. Note that the @code{dumb}
29562device is present only in GNUPLOT 3.0 and later versions.
29563
29564The word @code{dumb} may be followed by two numbers separated by
29565spaces. These are the desired width and height of the graph in
29566characters. Also, the device name @code{big} is like @code{dumb}
29567but creates a graph four times the width and height of the Emacs
29568screen. You will then have to scroll around to view the entire
29569graph. In the @samp{*Gnuplot Trail*} buffer, @key{SPC}, @key{DEL},
29570@kbd{<}, and @kbd{>} are defined to scroll by one screenful in each
29571of the four directions.
29572
29573With a negative numeric prefix argument, @kbd{g D} sets or displays
29574the device name used by @kbd{g P} (@code{calc-graph-print}). This
29575is initially @code{postscript}. If you don't have a PostScript
29576printer, you may decide once again to use @code{dumb} to create a
29577plot on any text-only printer.
29578
29579@kindex g O
29580@pindex calc-graph-output
66783bb4
EZ
29581The @kbd{g O} (@code{calc-graph-output}) command sets the name of the
29582output file used by GNUPLOT. For some devices, notably @code{x11} and
29583@code{windows}, there is no output file and this information is not
29584used. Many other ``devices'' are really file formats like
29585@code{postscript}; in these cases the output in the desired format
29586goes into the file you name with @kbd{g O}. Type @kbd{g O stdout
29587@key{RET}} to set GNUPLOT to write to its standard output stream,
29588i.e., to @samp{*Gnuplot Trail*}. This is the default setting.
4009494e
GM
29589
29590Another special output name is @code{tty}, which means that GNUPLOT
29591is going to write graphics commands directly to its standard output,
29592which you wish Emacs to pass through to your terminal. Tektronix
29593graphics terminals, among other devices, operate this way. Calc does
29594this by telling GNUPLOT to write to a temporary file, then running a
29595sub-shell executing the command @samp{cat tempfile >/dev/tty}. On
29596typical Unix systems, this will copy the temporary file directly to
29597the terminal, bypassing Emacs entirely. You will have to type @kbd{C-l}
29598to Emacs afterwards to refresh the screen.
29599
29600Once again, @kbd{g O} with a positive or negative prefix argument
29601sets the default or printer output file names, respectively. In each
29602case you can specify @code{auto}, which causes Calc to invent a temporary
29603file name for each @kbd{g p} (or @kbd{g P}) command. This temporary file
29604will be deleted once it has been displayed or printed. If the output file
29605name is not @code{auto}, the file is not automatically deleted.
29606
29607The default and printer devices and output files can be saved
29608permanently by the @kbd{m m} (@code{calc-save-modes}) command. The
29609default number of data points (see @kbd{g N}) and the X geometry
29610(see @kbd{g X}) are also saved. Other graph information is @emph{not}
29611saved; you can save a graph's configuration simply by saving the contents
29612of the @samp{*Gnuplot Commands*} buffer.
29613
29614@vindex calc-gnuplot-plot-command
29615@vindex calc-gnuplot-default-device
29616@vindex calc-gnuplot-default-output
29617@vindex calc-gnuplot-print-command
29618@vindex calc-gnuplot-print-device
29619@vindex calc-gnuplot-print-output
29620You may wish to configure the default and
29621printer devices and output files for the whole system. The relevant
29622Lisp variables are @code{calc-gnuplot-default-device} and @code{-output},
29623and @code{calc-gnuplot-print-device} and @code{-output}. The output
29624file names must be either strings as described above, or Lisp
29625expressions which are evaluated on the fly to get the output file names.
29626
29627Other important Lisp variables are @code{calc-gnuplot-plot-command} and
29628@code{calc-gnuplot-print-command}, which give the system commands to
29629display or print the output of GNUPLOT, respectively. These may be
29630@code{nil} if no command is necessary, or strings which can include
29631@samp{%s} to signify the name of the file to be displayed or printed.
29632Or, these variables may contain Lisp expressions which are evaluated
29633to display or print the output. These variables are customizable
29634(@pxref{Customizing Calc}).
29635
29636@kindex g x
29637@pindex calc-graph-display
29638The @kbd{g x} (@code{calc-graph-display}) command lets you specify
29639on which X window system display your graphs should be drawn. Enter
29640a blank line to see the current display name. This command has no
29641effect unless the current device is @code{x11}.
29642
29643@kindex g X
29644@pindex calc-graph-geometry
29645The @kbd{g X} (@code{calc-graph-geometry}) command is a similar
29646command for specifying the position and size of the X window.
29647The normal value is @code{default}, which generally means your
29648window manager will let you place the window interactively.
29649Entering @samp{800x500+0+0} would create an 800-by-500 pixel
66783bb4
EZ
29650window in the upper-left corner of the screen. This command has no
29651effect if the current device is @code{windows}.
4009494e
GM
29652
29653The buffer called @samp{*Gnuplot Trail*} holds a transcript of the
29654session with GNUPLOT. This shows the commands Calc has ``typed'' to
29655GNUPLOT and the responses it has received. Calc tries to notice when an
29656error message has appeared here and display the buffer for you when
29657this happens. You can check this buffer yourself if you suspect
66783bb4
EZ
29658something has gone wrong@footnote{
29659On MS-Windows, due to the peculiarities of how the Windows version of
29660GNUPLOT (called @command{wgnuplot}) works, the GNUPLOT responses are
29661not communicated back to Calc. Instead, you need to look them up in
29662the GNUPLOT command window that is displayed as in normal interactive
29663usage of GNUPLOT.
29664}.
4009494e
GM
29665
29666@kindex g C
29667@pindex calc-graph-command
29668The @kbd{g C} (@code{calc-graph-command}) command prompts you to
29669enter any line of text, then simply sends that line to the current
29670GNUPLOT process. The @samp{*Gnuplot Trail*} buffer looks deceptively
29671like a Shell buffer but you can't type commands in it yourself.
29672Instead, you must use @kbd{g C} for this purpose.
29673
29674@kindex g v
29675@kindex g V
29676@pindex calc-graph-view-commands
29677@pindex calc-graph-view-trail
29678The @kbd{g v} (@code{calc-graph-view-commands}) and @kbd{g V}
29679(@code{calc-graph-view-trail}) commands display the @samp{*Gnuplot Commands*}
29680and @samp{*Gnuplot Trail*} buffers, respectively, in another window.
29681This happens automatically when Calc thinks there is something you
29682will want to see in either of these buffers. If you type @kbd{g v}
29683or @kbd{g V} when the relevant buffer is already displayed, the
66783bb4
EZ
29684buffer is hidden again. (Note that on MS-Windows, the @samp{*Gnuplot
29685Trail*} buffer will usually show nothing of interest, because
29686GNUPLOT's responses are not communicated back to Calc.)
4009494e
GM
29687
29688One reason to use @kbd{g v} is to add your own commands to the
29689@samp{*Gnuplot Commands*} buffer. Press @kbd{g v}, then use
29690@kbd{C-x o} to switch into that window. For example, GNUPLOT has
29691@samp{set label} and @samp{set arrow} commands that allow you to
29692annotate your plots. Since Calc doesn't understand these commands,
29693you have to add them to the @samp{*Gnuplot Commands*} buffer
29694yourself, then use @w{@kbd{g p}} to replot using these new commands. Note
29695that your commands must appear @emph{before} the @code{plot} command.
29696To get help on any GNUPLOT feature, type, e.g., @kbd{g C help set label}.
29697You may have to type @kbd{g C @key{RET}} a few times to clear the
29698``press return for more'' or ``subtopic of @dots{}'' requests.
29699Note that Calc always sends commands (like @samp{set nolabel}) to
29700reset all plotting parameters to the defaults before each plot, so
29701to delete a label all you need to do is delete the @samp{set label}
29702line you added (or comment it out with @samp{#}) and then replot
29703with @kbd{g p}.
29704
29705@kindex g q
29706@pindex calc-graph-quit
29707You can use @kbd{g q} (@code{calc-graph-quit}) to kill the GNUPLOT
29708process that is running. The next graphing command you give will
29709start a fresh GNUPLOT process. The word @samp{Graph} appears in
29710the Calc window's mode line whenever a GNUPLOT process is currently
29711running. The GNUPLOT process is automatically killed when you
29712exit Emacs if you haven't killed it manually by then.
29713
29714@kindex g K
29715@pindex calc-graph-kill
29716The @kbd{g K} (@code{calc-graph-kill}) command is like @kbd{g q}
29717except that it also views the @samp{*Gnuplot Trail*} buffer so that
29718you can see the process being killed. This is better if you are
29719killing GNUPLOT because you think it has gotten stuck.
29720
29721@node Kill and Yank, Keypad Mode, Graphics, Top
29722@chapter Kill and Yank Functions
29723
29724@noindent
29725The commands in this chapter move information between the Calculator and
29726other Emacs editing buffers.
29727
29728In many cases Embedded mode is an easier and more natural way to
29729work with Calc from a regular editing buffer. @xref{Embedded Mode}.
29730
29731@menu
29732* Killing From Stack::
29733* Yanking Into Stack::
538c2573
JB
29734* Saving Into Registers::
29735* Inserting From Registers::
4009494e
GM
29736* Grabbing From Buffers::
29737* Yanking Into Buffers::
29738* X Cut and Paste::
29739@end menu
29740
29741@node Killing From Stack, Yanking Into Stack, Kill and Yank, Kill and Yank
29742@section Killing from the Stack
29743
29744@noindent
29745@kindex C-k
29746@pindex calc-kill
29747@kindex M-k
29748@pindex calc-copy-as-kill
29749@kindex C-w
29750@pindex calc-kill-region
29751@kindex M-w
29752@pindex calc-copy-region-as-kill
aee08080 29753@kindex M-C-w
4009494e 29754@cindex Kill ring
aee08080
JB
29755@dfn{Kill} commands are Emacs commands that insert text into the ``kill
29756ring,'' from which it can later be ``yanked'' by a @kbd{C-y} command.
29757Three common kill commands in normal Emacs are @kbd{C-k}, which kills
29758one line, @kbd{C-w}, which kills the region between mark and point, and
29759@kbd{M-w}, which puts the region into the kill ring without actually
29760deleting it. All of these commands work in the Calculator, too,
29761although in the Calculator they operate on whole stack entries, so they
29762``round up'' the specified region to encompass full lines. (To copy
29763only parts of lines, the @kbd{M-C-w} command in the Calculator will copy
29764the region to the kill ring without any ``rounding up'', just like the
29765@kbd{M-w} command in normal Emacs.) Also, @kbd{M-k} has been provided
29766to complete the set; it puts the current line into the kill ring without
29767deleting anything.
4009494e
GM
29768
29769The kill commands are unusual in that they pay attention to the location
aee08080
JB
29770of the cursor in the Calculator buffer. If the cursor is on or below
29771the bottom line, the kill commands operate on the top of the stack.
29772Otherwise, they operate on whatever stack element the cursor is on. The
29773text is copied into the kill ring exactly as it appears on the screen,
29774including line numbers if they are enabled.
4009494e
GM
29775
29776A numeric prefix argument to @kbd{C-k} or @kbd{M-k} affects the number
29777of lines killed. A positive argument kills the current line and @expr{n-1}
29778lines below it. A negative argument kills the @expr{-n} lines above the
29779current line. Again this mirrors the behavior of the standard Emacs
29780@kbd{C-k} command. Although a whole line is always deleted, @kbd{C-k}
29781with no argument copies only the number itself into the kill ring, whereas
29782@kbd{C-k} with a prefix argument of 1 copies the number with its trailing
29783newline.
29784
538c2573 29785@node Yanking Into Stack, Saving Into Registers, Killing From Stack, Kill and Yank
4009494e
GM
29786@section Yanking into the Stack
29787
29788@noindent
29789@kindex C-y
29790@pindex calc-yank
29791The @kbd{C-y} command yanks the most recently killed text back into the
29792Calculator. It pushes this value onto the top of the stack regardless of
29793the cursor position. In general it re-parses the killed text as a number
29794or formula (or a list of these separated by commas or newlines). However if
29795the thing being yanked is something that was just killed from the Calculator
29796itself, its full internal structure is yanked. For example, if you have
29797set the floating-point display mode to show only four significant digits,
29798then killing and re-yanking 3.14159 (which displays as 3.142) will yank the
29799full 3.14159, even though yanking it into any other buffer would yank the
29800number in its displayed form, 3.142. (Since the default display modes
29801show all objects to their full precision, this feature normally makes no
29802difference.)
29803
538c2573
JB
29804@node Saving Into Registers, Inserting From Registers, Yanking Into Stack, Kill and Yank
29805@section Saving into Registers
29806
29807@noindent
29808@kindex r s
29809@pindex calc-copy-to-register
29810@pindex calc-prepend-to-register
29811@pindex calc-append-to-register
29812@cindex Registers
40ba43b4 29813An alternative to killing and yanking stack entries is using
538c2573
JB
29814registers in Calc. Saving stack entries in registers is like
29815saving text in normal Emacs registers; although, like Calc's kill
29816commands, register commands always operate on whole stack
29817entries.
29818
29819Registers in Calc are places to store stack entries for later use;
29820each register is indexed by a single character. To store the current
29821region (rounded up, of course, to include full stack entries) into a
29822register, use the command @kbd{r s} (@code{calc-copy-to-register}).
29823You will then be prompted for a register to use, the next character
29824you type will be the index for the register. To store the region in
29825register @var{r}, the full command will be @kbd{r s @var{r}}. With an
29826argument, @kbd{C-u r s @var{r}}, the region being copied to the
29827register will be deleted from the Calc buffer.
29828
29829It is possible to add additional stack entries to a register. The
29830command @kbd{M-x calc-append-to-register} will prompt for a register,
29831then add the stack entries in the region to the end of the register
29832contents. The command @kbd{M-x calc-prepend-to-register} will
29833similarly prompt for a register and add the stack entries in the
29834region to the beginning of the register contents. Both commands take
29835@kbd{C-u} arguments, which will cause the region to be deleted after being
29836added to the register.
29837
29838@node Inserting From Registers, Grabbing From Buffers, Saving Into Registers, Kill and Yank
29839@section Inserting from Registers
29840@noindent
29841@kindex r i
29842@pindex calc-insert-register
29843The command @kbd{r i} (@code{calc-insert-register}) will prompt for a
29844register, then insert the contents of that register into the
29845Calculator. If the contents of the register were placed there from
29846within Calc, then the full internal structure of the contents will be
29847inserted into the Calculator, otherwise whatever text is in the
29848register is reparsed and then inserted into the Calculator.
29849
29850@node Grabbing From Buffers, Yanking Into Buffers, Inserting From Registers, Kill and Yank
4009494e
GM
29851@section Grabbing from Other Buffers
29852
29853@noindent
29854@kindex C-x * g
29855@pindex calc-grab-region
29856The @kbd{C-x * g} (@code{calc-grab-region}) command takes the text between
29857point and mark in the current buffer and attempts to parse it as a
29858vector of values. Basically, it wraps the text in vector brackets
29859@samp{[ ]} unless the text already is enclosed in vector brackets,
29860then reads the text as if it were an algebraic entry. The contents
29861of the vector may be numbers, formulas, or any other Calc objects.
29862If the @kbd{C-x * g} command works successfully, it does an automatic
29863@kbd{C-x * c} to enter the Calculator buffer.
29864
29865A numeric prefix argument grabs the specified number of lines around
29866point, ignoring the mark. A positive prefix grabs from point to the
29867@expr{n}th following newline (so that @kbd{M-1 C-x * g} grabs from point
29868to the end of the current line); a negative prefix grabs from point
29869back to the @expr{n+1}st preceding newline. In these cases the text
29870that is grabbed is exactly the same as the text that @kbd{C-k} would
29871delete given that prefix argument.
29872
29873A prefix of zero grabs the current line; point may be anywhere on the
29874line.
29875
29876A plain @kbd{C-u} prefix interprets the region between point and mark
29877as a single number or formula rather than a vector. For example,
29878@kbd{C-x * g} on the text @samp{2 a b} produces the vector of three
29879values @samp{[2, a, b]}, but @kbd{C-u C-x * g} on the same region
29880reads a formula which is a product of three things: @samp{2 a b}.
29881(The text @samp{a + b}, on the other hand, will be grabbed as a
29882vector of one element by plain @kbd{C-x * g} because the interpretation
29883@samp{[a, +, b]} would be a syntax error.)
29884
29885If a different language has been specified (@pxref{Language Modes}),
29886the grabbed text will be interpreted according to that language.
29887
29888@kindex C-x * r
29889@pindex calc-grab-rectangle
29890The @kbd{C-x * r} (@code{calc-grab-rectangle}) command takes the text between
29891point and mark and attempts to parse it as a matrix. If point and mark
29892are both in the leftmost column, the lines in between are parsed in their
29893entirety. Otherwise, point and mark define the corners of a rectangle
29894whose contents are parsed.
29895
29896Each line of the grabbed area becomes a row of the matrix. The result
29897will actually be a vector of vectors, which Calc will treat as a matrix
29898only if every row contains the same number of values.
29899
29900If a line contains a portion surrounded by square brackets (or curly
29901braces), that portion is interpreted as a vector which becomes a row
29902of the matrix. Any text surrounding the bracketed portion on the line
29903is ignored.
29904
29905Otherwise, the entire line is interpreted as a row vector as if it
29906were surrounded by square brackets. Leading line numbers (in the
29907format used in the Calc stack buffer) are ignored. If you wish to
29908force this interpretation (even if the line contains bracketed
29909portions), give a negative numeric prefix argument to the
29910@kbd{C-x * r} command.
29911
29912If you give a numeric prefix argument of zero or plain @kbd{C-u}, each
29913line is instead interpreted as a single formula which is converted into
29914a one-element vector. Thus the result of @kbd{C-u C-x * r} will be a
29915one-column matrix. For example, suppose one line of the data is the
29916expression @samp{2 a}. A plain @w{@kbd{C-x * r}} will interpret this as
29917@samp{[2 a]}, which in turn is read as a two-element vector that forms
29918one row of the matrix. But a @kbd{C-u C-x * r} will interpret this row
29919as @samp{[2*a]}.
29920
29921If you give a positive numeric prefix argument @var{n}, then each line
29922will be split up into columns of width @var{n}; each column is parsed
29923separately as a matrix element. If a line contained
29924@w{@samp{2 +/- 3 4 +/- 5}}, then grabbing with a prefix argument of 8
29925would correctly split the line into two error forms.
29926
29927@xref{Matrix Functions}, to see how to pull the matrix apart into its
40ba43b4 29928constituent rows and columns. (If it is a
4009494e
GM
29929@texline @math{1\times1}
29930@infoline 1x1
29931matrix, just hit @kbd{v u} (@code{calc-unpack}) twice.)
29932
29933@kindex C-x * :
29934@kindex C-x * _
29935@pindex calc-grab-sum-across
29936@pindex calc-grab-sum-down
29937@cindex Summing rows and columns of data
29938The @kbd{C-x * :} (@code{calc-grab-sum-down}) command is a handy way to
29939grab a rectangle of data and sum its columns. It is equivalent to
29940typing @kbd{C-x * r}, followed by @kbd{V R : +} (the vector reduction
29941command that sums the columns of a matrix; @pxref{Reducing}). The
29942result of the command will be a vector of numbers, one for each column
29943in the input data. The @kbd{C-x * _} (@code{calc-grab-sum-across}) command
29944similarly grabs a rectangle and sums its rows by executing @w{@kbd{V R _ +}}.
29945
29946As well as being more convenient, @kbd{C-x * :} and @kbd{C-x * _} are also
29947much faster because they don't actually place the grabbed vector on
29948the stack. In a @kbd{C-x * r V R : +} sequence, formatting the vector
29949for display on the stack takes a large fraction of the total time
29950(unless you have planned ahead and used @kbd{v .} and @kbd{t .} modes).
29951
29952For example, suppose we have a column of numbers in a file which we
29953wish to sum. Go to one corner of the column and press @kbd{C-@@} to
29954set the mark; go to the other corner and type @kbd{C-x * :}. Since there
29955is only one column, the result will be a vector of one number, the sum.
29956(You can type @kbd{v u} to unpack this vector into a plain number if
29957you want to do further arithmetic with it.)
29958
29959To compute the product of the column of numbers, we would have to do
29960it ``by hand'' since there's no special grab-and-multiply command.
29961Use @kbd{C-x * r} to grab the column of numbers into the calculator in
29962the form of a column matrix. The statistics command @kbd{u *} is a
29963handy way to find the product of a vector or matrix of numbers.
29964@xref{Statistical Operations}. Another approach would be to use
29965an explicit column reduction command, @kbd{V R : *}.
29966
29967@node Yanking Into Buffers, X Cut and Paste, Grabbing From Buffers, Kill and Yank
29968@section Yanking into Other Buffers
29969
29970@noindent
29971@kindex y
29972@pindex calc-copy-to-buffer
29973The plain @kbd{y} (@code{calc-copy-to-buffer}) command inserts the number
29974at the top of the stack into the most recently used normal editing buffer.
29975(More specifically, this is the most recently used buffer which is displayed
29976in a window and whose name does not begin with @samp{*}. If there is no
29977such buffer, this is the most recently used buffer except for Calculator
29978and Calc Trail buffers.) The number is inserted exactly as it appears and
29979without a newline. (If line-numbering is enabled, the line number is
29980normally not included.) The number is @emph{not} removed from the stack.
29981
29982With a prefix argument, @kbd{y} inserts several numbers, one per line.
29983A positive argument inserts the specified number of values from the top
29984of the stack. A negative argument inserts the @expr{n}th value from the
29985top of the stack. An argument of zero inserts the entire stack. Note
29986that @kbd{y} with an argument of 1 is slightly different from @kbd{y}
29987with no argument; the former always copies full lines, whereas the
29988latter strips off the trailing newline.
29989
29990With a lone @kbd{C-u} as a prefix argument, @kbd{y} @emph{replaces} the
29991region in the other buffer with the yanked text, then quits the
29992Calculator, leaving you in that buffer. A typical use would be to use
29993@kbd{C-x * g} to read a region of data into the Calculator, operate on the
29994data to produce a new matrix, then type @kbd{C-u y} to replace the
29995original data with the new data. One might wish to alter the matrix
29996display style (@pxref{Vector and Matrix Formats}) or change the current
29997display language (@pxref{Language Modes}) before doing this. Also, note
29998that this command replaces a linear region of text (as grabbed by
29999@kbd{C-x * g}), not a rectangle (as grabbed by @kbd{C-x * r}).
30000
30001If the editing buffer is in overwrite (as opposed to insert) mode,
30002and the @kbd{C-u} prefix was not used, then the yanked number will
30003overwrite the characters following point rather than being inserted
30004before those characters. The usual conventions of overwrite mode
30005are observed; for example, characters will be inserted at the end of
30006a line rather than overflowing onto the next line. Yanking a multi-line
30007object such as a matrix in overwrite mode overwrites the next @var{n}
30008lines in the buffer, lengthening or shortening each line as necessary.
30009Finally, if the thing being yanked is a simple integer or floating-point
30010number (like @samp{-1.2345e-3}) and the characters following point also
30011make up such a number, then Calc will replace that number with the new
30012number, lengthening or shortening as necessary. The concept of
30013``overwrite mode'' has thus been generalized from overwriting characters
30014to overwriting one complete number with another.
30015
30016@kindex C-x * y
30017The @kbd{C-x * y} key sequence is equivalent to @kbd{y} except that
30018it can be typed anywhere, not just in Calc. This provides an easy
30019way to guarantee that Calc knows which editing buffer you want to use!
30020
30021@node X Cut and Paste, , Yanking Into Buffers, Kill and Yank
30022@section X Cut and Paste
30023
30024@noindent
30025If you are using Emacs with the X window system, there is an easier
30026way to move small amounts of data into and out of the calculator:
30027Use the mouse-oriented cut and paste facilities of X.
30028
30029The default bindings for a three-button mouse cause the left button
30030to move the Emacs cursor to the given place, the right button to
30031select the text between the cursor and the clicked location, and
30032the middle button to yank the selection into the buffer at the
30033clicked location. So, if you have a Calc window and an editing
30034window on your Emacs screen, you can use left-click/right-click
30035to select a number, vector, or formula from one window, then
30036middle-click to paste that value into the other window. When you
30037paste text into the Calc window, Calc interprets it as an algebraic
30038entry. It doesn't matter where you click in the Calc window; the
30039new value is always pushed onto the top of the stack.
30040
30041The @code{xterm} program that is typically used for general-purpose
30042shell windows in X interprets the mouse buttons in the same way.
30043So you can use the mouse to move data between Calc and any other
30044Unix program. One nice feature of @code{xterm} is that a double
30045left-click selects one word, and a triple left-click selects a
30046whole line. So you can usually transfer a single number into Calc
30047just by double-clicking on it in the shell, then middle-clicking
30048in the Calc window.
30049
30050@node Keypad Mode, Embedded Mode, Kill and Yank, Top
30051@chapter Keypad Mode
30052
30053@noindent
30054@kindex C-x * k
30055@pindex calc-keypad
30056The @kbd{C-x * k} (@code{calc-keypad}) command starts the Calculator
30057and displays a picture of a calculator-style keypad. If you are using
30058the X window system, you can click on any of the ``keys'' in the
30059keypad using the left mouse button to operate the calculator.
30060The original window remains the selected window; in Keypad mode
30061you can type in your file while simultaneously performing
30062calculations with the mouse.
30063
30064@pindex full-calc-keypad
30065If you have used @kbd{C-x * b} first, @kbd{C-x * k} instead invokes
30066the @code{full-calc-keypad} command, which takes over the whole
30067Emacs screen and displays the keypad, the Calc stack, and the Calc
30068trail all at once. This mode would normally be used when running
30069Calc standalone (@pxref{Standalone Operation}).
30070
30071If you aren't using the X window system, you must switch into
30072the @samp{*Calc Keypad*} window, place the cursor on the desired
30073``key,'' and type @key{SPC} or @key{RET}. If you think this
30074is easier than using Calc normally, go right ahead.
30075
30076Calc commands are more or less the same in Keypad mode. Certain
30077keypad keys differ slightly from the corresponding normal Calc
30078keystrokes; all such deviations are described below.
30079
30080Keypad mode includes many more commands than will fit on the keypad
30081at once. Click the right mouse button [@code{calc-keypad-menu}]
30082to switch to the next menu. The bottom five rows of the keypad
30083stay the same; the top three rows change to a new set of commands.
30084To return to earlier menus, click the middle mouse button
30085[@code{calc-keypad-menu-back}] or simply advance through the menus
30086until you wrap around. Typing @key{TAB} inside the keypad window
30087is equivalent to clicking the right mouse button there.
30088
30089You can always click the @key{EXEC} button and type any normal
30090Calc key sequence. This is equivalent to switching into the
30091Calc buffer, typing the keys, then switching back to your
30092original buffer.
30093
30094@menu
30095* Keypad Main Menu::
30096* Keypad Functions Menu::
30097* Keypad Binary Menu::
30098* Keypad Vectors Menu::
30099* Keypad Modes Menu::
30100@end menu
30101
30102@node Keypad Main Menu, Keypad Functions Menu, Keypad Mode, Keypad Mode
30103@section Main Menu
30104
30105@smallexample
30106@group
5a83c46e 30107|----+----+--Calc---+----+----1
4009494e
GM
30108|FLR |CEIL|RND |TRNC|CLN2|FLT |
30109|----+----+----+----+----+----|
30110| LN |EXP | |ABS |IDIV|MOD |
30111|----+----+----+----+----+----|
30112|SIN |COS |TAN |SQRT|y^x |1/x |
30113|----+----+----+----+----+----|
30114| ENTER |+/- |EEX |UNDO| <- |
30115|-----+---+-+--+--+-+---++----|
30116| INV | 7 | 8 | 9 | / |
30117|-----+-----+-----+-----+-----|
30118| HYP | 4 | 5 | 6 | * |
30119|-----+-----+-----+-----+-----|
30120|EXEC | 1 | 2 | 3 | - |
30121|-----+-----+-----+-----+-----|
30122| OFF | 0 | . | PI | + |
30123|-----+-----+-----+-----+-----+
30124@end group
30125@end smallexample
30126
30127@noindent
30128This is the menu that appears the first time you start Keypad mode.
30129It will show up in a vertical window on the right side of your screen.
30130Above this menu is the traditional Calc stack display. On a 24-line
30131screen you will be able to see the top three stack entries.
30132
30133The ten digit keys, decimal point, and @key{EEX} key are used for
30134entering numbers in the obvious way. @key{EEX} begins entry of an
30135exponent in scientific notation. Just as with regular Calc, the
30136number is pushed onto the stack as soon as you press @key{ENTER}
30137or any other function key.
30138
30139The @key{+/-} key corresponds to normal Calc's @kbd{n} key. During
30140numeric entry it changes the sign of the number or of the exponent.
30141At other times it changes the sign of the number on the top of the
30142stack.
30143
30144The @key{INV} and @key{HYP} keys modify other keys. As well as
30145having the effects described elsewhere in this manual, Keypad mode
30146defines several other ``inverse'' operations. These are described
30147below and in the following sections.
30148
30149The @key{ENTER} key finishes the current numeric entry, or otherwise
30150duplicates the top entry on the stack.
30151
30152The @key{UNDO} key undoes the most recent Calc operation.
30153@kbd{INV UNDO} is the ``redo'' command, and @kbd{HYP UNDO} is
30154``last arguments'' (@kbd{M-@key{RET}}).
30155
30156The @key{<-} key acts as a ``backspace'' during numeric entry.
30157At other times it removes the top stack entry. @kbd{INV <-}
30158clears the entire stack. @kbd{HYP <-} takes an integer from
30159the stack, then removes that many additional stack elements.
30160
30161The @key{EXEC} key prompts you to enter any keystroke sequence
30162that would normally work in Calc mode. This can include a
30163numeric prefix if you wish. It is also possible simply to
30164switch into the Calc window and type commands in it; there is
30165nothing ``magic'' about this window when Keypad mode is active.
30166
30167The other keys in this display perform their obvious calculator
30168functions. @key{CLN2} rounds the top-of-stack by temporarily
30169reducing the precision by 2 digits. @key{FLT} converts an
30170integer or fraction on the top of the stack to floating-point.
30171
30172The @key{INV} and @key{HYP} keys combined with several of these keys
30173give you access to some common functions even if the appropriate menu
30174is not displayed. Obviously you don't need to learn these keys
30175unless you find yourself wasting time switching among the menus.
30176
30177@table @kbd
30178@item INV +/-
30179is the same as @key{1/x}.
30180@item INV +
30181is the same as @key{SQRT}.
30182@item INV -
30183is the same as @key{CONJ}.
30184@item INV *
30185is the same as @key{y^x}.
30186@item INV /
30187is the same as @key{INV y^x} (the @expr{x}th root of @expr{y}).
30188@item HYP/INV 1
30189are the same as @key{SIN} / @kbd{INV SIN}.
30190@item HYP/INV 2
30191are the same as @key{COS} / @kbd{INV COS}.
30192@item HYP/INV 3
30193are the same as @key{TAN} / @kbd{INV TAN}.
30194@item INV/HYP 4
30195are the same as @key{LN} / @kbd{HYP LN}.
30196@item INV/HYP 5
30197are the same as @key{EXP} / @kbd{HYP EXP}.
30198@item INV 6
30199is the same as @key{ABS}.
30200@item INV 7
30201is the same as @key{RND} (@code{calc-round}).
30202@item INV 8
30203is the same as @key{CLN2}.
30204@item INV 9
30205is the same as @key{FLT} (@code{calc-float}).
30206@item INV 0
30207is the same as @key{IMAG}.
30208@item INV .
30209is the same as @key{PREC}.
30210@item INV ENTER
30211is the same as @key{SWAP}.
30212@item HYP ENTER
30213is the same as @key{RLL3}.
30214@item INV HYP ENTER
30215is the same as @key{OVER}.
30216@item HYP +/-
30217packs the top two stack entries as an error form.
30218@item HYP EEX
30219packs the top two stack entries as a modulo form.
30220@item INV EEX
30221creates an interval form; this removes an integer which is one
30222of 0 @samp{[]}, 1 @samp{[)}, 2 @samp{(]} or 3 @samp{()}, followed
30223by the two limits of the interval.
30224@end table
30225
30226The @kbd{OFF} key turns Calc off; typing @kbd{C-x * k} or @kbd{C-x * *}
30227again has the same effect. This is analogous to typing @kbd{q} or
30228hitting @kbd{C-x * c} again in the normal calculator. If Calc is
30229running standalone (the @code{full-calc-keypad} command appeared in the
30230command line that started Emacs), then @kbd{OFF} is replaced with
30231@kbd{EXIT}; clicking on this actually exits Emacs itself.
30232
30233@node Keypad Functions Menu, Keypad Binary Menu, Keypad Main Menu, Keypad Mode
30234@section Functions Menu
30235
30236@smallexample
30237@group
30238|----+----+----+----+----+----2
30239|IGAM|BETA|IBET|ERF |BESJ|BESY|
30240|----+----+----+----+----+----|
30241|IMAG|CONJ| RE |ATN2|RAND|RAGN|
30242|----+----+----+----+----+----|
30243|GCD |FACT|DFCT|BNOM|PERM|NXTP|
30244|----+----+----+----+----+----|
30245@end group
30246@end smallexample
30247
30248@noindent
30249This menu provides various operations from the @kbd{f} and @kbd{k}
30250prefix keys.
30251
30252@key{IMAG} multiplies the number on the stack by the imaginary
30253number @expr{i = (0, 1)}.
30254
30255@key{RE} extracts the real part a complex number. @kbd{INV RE}
30256extracts the imaginary part.
30257
30258@key{RAND} takes a number from the top of the stack and computes
30259a random number greater than or equal to zero but less than that
30260number. (@xref{Random Numbers}.) @key{RAGN} is the ``random
30261again'' command; it computes another random number using the
30262same limit as last time.
30263
30264@key{INV GCD} computes the LCM (least common multiple) function.
30265
40ba43b4 30266@key{INV FACT} is the gamma function.
4009494e
GM
30267@texline @math{\Gamma(x) = (x-1)!}.
30268@infoline @expr{gamma(x) = (x-1)!}.
30269
30270@key{PERM} is the number-of-permutations function, which is on the
30271@kbd{H k c} key in normal Calc.
30272
30273@key{NXTP} finds the next prime after a number. @kbd{INV NXTP}
30274finds the previous prime.
30275
30276@node Keypad Binary Menu, Keypad Vectors Menu, Keypad Functions Menu, Keypad Mode
30277@section Binary Menu
30278
30279@smallexample
30280@group
30281|----+----+----+----+----+----3
30282|AND | OR |XOR |NOT |LSH |RSH |
30283|----+----+----+----+----+----|
30284|DEC |HEX |OCT |BIN |WSIZ|ARSH|
30285|----+----+----+----+----+----|
30286| A | B | C | D | E | F |
30287|----+----+----+----+----+----|
30288@end group
30289@end smallexample
30290
30291@noindent
30292The keys in this menu perform operations on binary integers.
30293Note that both logical and arithmetic right-shifts are provided.
30294@key{INV LSH} rotates one bit to the left.
30295
30296The ``difference'' function (normally on @kbd{b d}) is on @key{INV AND}.
30297The ``clip'' function (normally on @w{@kbd{b c}}) is on @key{INV NOT}.
30298
30299The @key{DEC}, @key{HEX}, @key{OCT}, and @key{BIN} keys select the
30300current radix for display and entry of numbers: Decimal, hexadecimal,
30301octal, or binary. The six letter keys @key{A} through @key{F} are used
30302for entering hexadecimal numbers.
30303
30304The @key{WSIZ} key displays the current word size for binary operations
30305and allows you to enter a new word size. You can respond to the prompt
30306using either the keyboard or the digits and @key{ENTER} from the keypad.
30307The initial word size is 32 bits.
30308
30309@node Keypad Vectors Menu, Keypad Modes Menu, Keypad Binary Menu, Keypad Mode
30310@section Vectors Menu
30311
30312@smallexample
30313@group
30314|----+----+----+----+----+----4
30315|SUM |PROD|MAX |MAP*|MAP^|MAP$|
30316|----+----+----+----+----+----|
30317|MINV|MDET|MTRN|IDNT|CRSS|"x" |
30318|----+----+----+----+----+----|
30319|PACK|UNPK|INDX|BLD |LEN |... |
30320|----+----+----+----+----+----|
30321@end group
30322@end smallexample
30323
30324@noindent
30325The keys in this menu operate on vectors and matrices.
30326
30327@key{PACK} removes an integer @var{n} from the top of the stack;
30328the next @var{n} stack elements are removed and packed into a vector,
30329which is replaced onto the stack. Thus the sequence
30330@kbd{1 ENTER 3 ENTER 5 ENTER 3 PACK} enters the vector
30331@samp{[1, 3, 5]} onto the stack. To enter a matrix, build each row
30332on the stack as a vector, then use a final @key{PACK} to collect the
30333rows into a matrix.
30334
30335@key{UNPK} unpacks the vector on the stack, pushing each of its
30336components separately.
30337
30338@key{INDX} removes an integer @var{n}, then builds a vector of
30339integers from 1 to @var{n}. @kbd{INV INDX} takes three numbers
30340from the stack: The vector size @var{n}, the starting number,
30341and the increment. @kbd{BLD} takes an integer @var{n} and any
30342value @var{x} and builds a vector of @var{n} copies of @var{x}.
30343
30344@key{IDNT} removes an integer @var{n}, then builds an @var{n}-by-@var{n}
30345identity matrix.
30346
30347@key{LEN} replaces a vector by its length, an integer.
30348
30349@key{...} turns on or off ``abbreviated'' display mode for large vectors.
30350
30351@key{MINV}, @key{MDET}, @key{MTRN}, and @key{CROSS} are the matrix
30352inverse, determinant, and transpose, and vector cross product.
30353
30354@key{SUM} replaces a vector by the sum of its elements. It is
30355equivalent to @kbd{u +} in normal Calc (@pxref{Statistical Operations}).
30356@key{PROD} computes the product of the elements of a vector, and
30357@key{MAX} computes the maximum of all the elements of a vector.
30358
30359@key{INV SUM} computes the alternating sum of the first element
30360minus the second, plus the third, minus the fourth, and so on.
30361@key{INV MAX} computes the minimum of the vector elements.
30362
30363@key{HYP SUM} computes the mean of the vector elements.
30364@key{HYP PROD} computes the sample standard deviation.
30365@key{HYP MAX} computes the median.
30366
30367@key{MAP*} multiplies two vectors elementwise. It is equivalent
30368to the @kbd{V M *} command. @key{MAP^} computes powers elementwise.
30369The arguments must be vectors of equal length, or one must be a vector
30370and the other must be a plain number. For example, @kbd{2 MAP^} squares
30371all the elements of a vector.
30372
30373@key{MAP$} maps the formula on the top of the stack across the
30374vector in the second-to-top position. If the formula contains
30375several variables, Calc takes that many vectors starting at the
30376second-to-top position and matches them to the variables in
30377alphabetical order. The result is a vector of the same size as
30378the input vectors, whose elements are the formula evaluated with
30379the variables set to the various sets of numbers in those vectors.
30380For example, you could simulate @key{MAP^} using @key{MAP$} with
30381the formula @samp{x^y}.
30382
30383The @kbd{"x"} key pushes the variable name @expr{x} onto the
30384stack. To build the formula @expr{x^2 + 6}, you would use the
30385key sequence @kbd{"x" 2 y^x 6 +}. This formula would then be
30386suitable for use with the @key{MAP$} key described above.
30387With @key{INV}, @key{HYP}, or @key{INV} and @key{HYP}, the
30388@kbd{"x"} key pushes the variable names @expr{y}, @expr{z}, and
30389@expr{t}, respectively.
30390
30391@node Keypad Modes Menu, , Keypad Vectors Menu, Keypad Mode
30392@section Modes Menu
30393
30394@smallexample
30395@group
30396|----+----+----+----+----+----5
30397|FLT |FIX |SCI |ENG |GRP | |
30398|----+----+----+----+----+----|
30399|RAD |DEG |FRAC|POLR|SYMB|PREC|
30400|----+----+----+----+----+----|
30401|SWAP|RLL3|RLL4|OVER|STO |RCL |
30402|----+----+----+----+----+----|
30403@end group
30404@end smallexample
30405
30406@noindent
30407The keys in this menu manipulate modes, variables, and the stack.
30408
30409The @key{FLT}, @key{FIX}, @key{SCI}, and @key{ENG} keys select
30410floating-point, fixed-point, scientific, or engineering notation.
30411@key{FIX} displays two digits after the decimal by default; the
30412others display full precision. With the @key{INV} prefix, these
30413keys pop a number-of-digits argument from the stack.
30414
30415The @key{GRP} key turns grouping of digits with commas on or off.
30416@kbd{INV GRP} enables grouping to the right of the decimal point as
30417well as to the left.
30418
30419The @key{RAD} and @key{DEG} keys switch between radians and degrees
30420for trigonometric functions.
30421
30422The @key{FRAC} key turns Fraction mode on or off. This affects
30423whether commands like @kbd{/} with integer arguments produce
30424fractional or floating-point results.
30425
30426The @key{POLR} key turns Polar mode on or off, determining whether
30427polar or rectangular complex numbers are used by default.
30428
30429The @key{SYMB} key turns Symbolic mode on or off, in which
30430operations that would produce inexact floating-point results
30431are left unevaluated as algebraic formulas.
30432
30433The @key{PREC} key selects the current precision. Answer with
30434the keyboard or with the keypad digit and @key{ENTER} keys.
30435
30436The @key{SWAP} key exchanges the top two stack elements.
30437The @key{RLL3} key rotates the top three stack elements upwards.
30438The @key{RLL4} key rotates the top four stack elements upwards.
30439The @key{OVER} key duplicates the second-to-top stack element.
30440
30441The @key{STO} and @key{RCL} keys are analogous to @kbd{s t} and
30442@kbd{s r} in regular Calc. @xref{Store and Recall}. Click the
30443@key{STO} or @key{RCL} key, then one of the ten digits. (Named
30444variables are not available in Keypad mode.) You can also use,
30445for example, @kbd{STO + 3} to add to register 3.
30446
30447@node Embedded Mode, Programming, Keypad Mode, Top
30448@chapter Embedded Mode
30449
30450@noindent
30451Embedded mode in Calc provides an alternative to copying numbers
30452and formulas back and forth between editing buffers and the Calc
30453stack. In Embedded mode, your editing buffer becomes temporarily
30454linked to the stack and this copying is taken care of automatically.
30455
30456@menu
30457* Basic Embedded Mode::
30458* More About Embedded Mode::
30459* Assignments in Embedded Mode::
30460* Mode Settings in Embedded Mode::
30461* Customizing Embedded Mode::
30462@end menu
30463
30464@node Basic Embedded Mode, More About Embedded Mode, Embedded Mode, Embedded Mode
30465@section Basic Embedded Mode
30466
30467@noindent
30468@kindex C-x * e
30469@pindex calc-embedded
30470To enter Embedded mode, position the Emacs point (cursor) on a
30471formula in any buffer and press @kbd{C-x * e} (@code{calc-embedded}).
30472Note that @kbd{C-x * e} is not to be used in the Calc stack buffer
30473like most Calc commands, but rather in regular editing buffers that
30474are visiting your own files.
30475
30476Calc will try to guess an appropriate language based on the major mode
30477of the editing buffer. (@xref{Language Modes}.) If the current buffer is
c1dabff0 30478in @code{latex-mode}, for example, Calc will set its language to @LaTeX{}.
4009494e
GM
30479Similarly, Calc will use @TeX{} language for @code{tex-mode},
30480@code{plain-tex-mode} and @code{context-mode}, C language for
30481@code{c-mode} and @code{c++-mode}, FORTRAN language for
30482@code{fortran-mode} and @code{f90-mode}, Pascal for @code{pascal-mode},
40ba43b4 30483and eqn for @code{nroff-mode} (@pxref{Customizing Calc}).
4009494e
GM
30484These can be overridden with Calc's mode
30485changing commands (@pxref{Mode Settings in Embedded Mode}). If no
30486suitable language is available, Calc will continue with its current language.
30487
30488Calc normally scans backward and forward in the buffer for the
30489nearest opening and closing @dfn{formula delimiters}. The simplest
30490delimiters are blank lines. Other delimiters that Embedded mode
30491understands are:
30492
30493@enumerate
30494@item
c1dabff0 30495The @TeX{} and @LaTeX{} math delimiters @samp{$ $}, @samp{$$ $$},
4009494e
GM
30496@samp{\[ \]}, and @samp{\( \)};
30497@item
30498Lines beginning with @samp{\begin} and @samp{\end} (except matrix delimiters);
30499@item
30500Lines beginning with @samp{@@} (Texinfo delimiters).
30501@item
30502Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
30503@item
30504Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
30505@end enumerate
30506
30507@xref{Customizing Embedded Mode}, to see how to make Calc recognize
30508your own favorite delimiters. Delimiters like @samp{$ $} can appear
30509on their own separate lines or in-line with the formula.
30510
30511If you give a positive or negative numeric prefix argument, Calc
30512instead uses the current point as one end of the formula, and includes
30513that many lines forward or backward (respectively, including the current
30514line). Explicit delimiters are not necessary in this case.
30515
30516With a prefix argument of zero, Calc uses the current region (delimited
30517by point and mark) instead of formula delimiters. With a prefix
30518argument of @kbd{C-u} only, Calc uses the current line as the formula.
30519
30520@kindex C-x * w
30521@pindex calc-embedded-word
30522The @kbd{C-x * w} (@code{calc-embedded-word}) command will start Embedded
30523mode on the current ``word''; in this case Calc will scan for the first
30524non-numeric character (i.e., the first character that is not a digit,
30525sign, decimal point, or upper- or lower-case @samp{e}) forward and
30526backward to delimit the formula.
30527
30528When you enable Embedded mode for a formula, Calc reads the text
30529between the delimiters and tries to interpret it as a Calc formula.
30530Calc can generally identify @TeX{} formulas and
30531Big-style formulas even if the language mode is wrong. If Calc
30532can't make sense of the formula, it beeps and refuses to enter
30533Embedded mode. But if the current language is wrong, Calc can
30534sometimes parse the formula successfully (but incorrectly);
30535for example, the C expression @samp{atan(a[1])} can be parsed
30536in Normal language mode, but the @code{atan} won't correspond to
30537the built-in @code{arctan} function, and the @samp{a[1]} will be
30538interpreted as @samp{a} times the vector @samp{[1]}!
30539
30540If you press @kbd{C-x * e} or @kbd{C-x * w} to activate an embedded
30541formula which is blank, say with the cursor on the space between
30542the two delimiters @samp{$ $}, Calc will immediately prompt for
30543an algebraic entry.
30544
30545Only one formula in one buffer can be enabled at a time. If you
30546move to another area of the current buffer and give Calc commands,
30547Calc turns Embedded mode off for the old formula and then tries
30548to restart Embedded mode at the new position. Other buffers are
30549not affected by Embedded mode.
30550
30551When Embedded mode begins, Calc pushes the current formula onto
30552the stack. No Calc stack window is created; however, Calc copies
30553the top-of-stack position into the original buffer at all times.
30554You can create a Calc window by hand with @kbd{C-x * o} if you
30555find you need to see the entire stack.
30556
30557For example, typing @kbd{C-x * e} while somewhere in the formula
30558@samp{n>2} in the following line enables Embedded mode on that
30559inequality:
30560
30561@example
30562We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.
30563@end example
30564
30565@noindent
30566The formula @expr{n>2} will be pushed onto the Calc stack, and
30567the top of stack will be copied back into the editing buffer.
30568This means that spaces will appear around the @samp{>} symbol
30569to match Calc's usual display style:
30570
30571@example
30572We define $F_n = F_(n-1)+F_(n-2)$ for all $n > 2$.
30573@end example
30574
30575@noindent
30576No spaces have appeared around the @samp{+} sign because it's
30577in a different formula, one which we have not yet touched with
30578Embedded mode.
30579
30580Now that Embedded mode is enabled, keys you type in this buffer
30581are interpreted as Calc commands. At this point we might use
30582the ``commute'' command @kbd{j C} to reverse the inequality.
30583This is a selection-based command for which we first need to
30584move the cursor onto the operator (@samp{>} in this case) that
30585needs to be commuted.
30586
30587@example
30588We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.
30589@end example
30590
30591The @kbd{C-x * o} command is a useful way to open a Calc window
30592without actually selecting that window. Giving this command
30593verifies that @samp{2 < n} is also on the Calc stack. Typing
30594@kbd{17 @key{RET}} would produce:
30595
30596@example
30597We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.
30598@end example
30599
30600@noindent
30601with @samp{2 < n} and @samp{17} on the stack; typing @key{TAB}
30602at this point will exchange the two stack values and restore
30603@samp{2 < n} to the embedded formula. Even though you can't
30604normally see the stack in Embedded mode, it is still there and
30605it still operates in the same way. But, as with old-fashioned
30606RPN calculators, you can only see the value at the top of the
30607stack at any given time (unless you use @kbd{C-x * o}).
30608
30609Typing @kbd{C-x * e} again turns Embedded mode off. The Calc
30610window reveals that the formula @w{@samp{2 < n}} is automatically
30611removed from the stack, but the @samp{17} is not. Entering
30612Embedded mode always pushes one thing onto the stack, and
30613leaving Embedded mode always removes one thing. Anything else
30614that happens on the stack is entirely your business as far as
30615Embedded mode is concerned.
30616
30617If you press @kbd{C-x * e} in the wrong place by accident, it is
30618possible that Calc will be able to parse the nearby text as a
30619formula and will mangle that text in an attempt to redisplay it
30620``properly'' in the current language mode. If this happens,
30621press @kbd{C-x * e} again to exit Embedded mode, then give the
30622regular Emacs ``undo'' command (@kbd{C-_} or @kbd{C-x u}) to put
30623the text back the way it was before Calc edited it. Note that Calc's
30624own Undo command (typed before you turn Embedded mode back off)
30625will not do you any good, because as far as Calc is concerned
30626you haven't done anything with this formula yet.
30627
30628@node More About Embedded Mode, Assignments in Embedded Mode, Basic Embedded Mode, Embedded Mode
30629@section More About Embedded Mode
30630
30631@noindent
30632When Embedded mode ``activates'' a formula, i.e., when it examines
30633the formula for the first time since the buffer was created or
30634loaded, Calc tries to sense the language in which the formula was
c1dabff0
GM
30635written. If the formula contains any @LaTeX{}-like @samp{\} sequences,
30636it is parsed (i.e., read) in @LaTeX{} mode. If the formula appears to
4009494e
GM
30637be written in multi-line Big mode, it is parsed in Big mode. Otherwise,
30638it is parsed according to the current language mode.
30639
30640Note that Calc does not change the current language mode according
c1dabff0
GM
30641the formula it reads in. Even though it can read a @LaTeX{} formula when
30642not in @LaTeX{} mode, it will immediately rewrite this formula using
4009494e
GM
30643whatever language mode is in effect.
30644
30645@tex
30646\bigskip
30647@end tex
30648
30649@kindex d p
30650@pindex calc-show-plain
30651Calc's parser is unable to read certain kinds of formulas. For
30652example, with @kbd{v ]} (@code{calc-matrix-brackets}) you can
30653specify matrix display styles which the parser is unable to
30654recognize as matrices. The @kbd{d p} (@code{calc-show-plain})
30655command turns on a mode in which a ``plain'' version of a
30656formula is placed in front of the fully-formatted version.
30657When Calc reads a formula that has such a plain version in
30658front, it reads the plain version and ignores the formatted
30659version.
30660
30661Plain formulas are preceded and followed by @samp{%%%} signs
30662by default. This notation has the advantage that the @samp{%}
c1dabff0
GM
30663character begins a comment in @TeX{} and @LaTeX{}, so if your formula is
30664embedded in a @TeX{} or @LaTeX{} document its plain version will be
4009494e 30665invisible in the final printed copy. Certain major modes have different
40ba43b4
PE
30666delimiters to ensure that the ``plain'' version will be
30667in a comment for those modes, also.
4009494e 30668See @ref{Customizing Embedded Mode} to see how to change the ``plain''
40ba43b4 30669formula delimiters.
4009494e
GM
30670
30671There are several notations which Calc's parser for ``big''
30672formatted formulas can't yet recognize. In particular, it can't
30673read the large symbols for @code{sum}, @code{prod}, and @code{integ},
30674and it can't handle @samp{=>} with the righthand argument omitted.
30675Also, Calc won't recognize special formats you have defined with
30676the @kbd{Z C} command (@pxref{User-Defined Compositions}). In
30677these cases it is important to use ``plain'' mode to make sure
30678Calc will be able to read your formula later.
30679
30680Another example where ``plain'' mode is important is if you have
30681specified a float mode with few digits of precision. Normally
30682any digits that are computed but not displayed will simply be
30683lost when you save and re-load your embedded buffer, but ``plain''
30684mode allows you to make sure that the complete number is present
30685in the file as well as the rounded-down number.
30686
30687@tex
30688\bigskip
30689@end tex
30690
30691Embedded buffers remember active formulas for as long as they
30692exist in Emacs memory. Suppose you have an embedded formula
30693which is @cpi{} to the normal 12 decimal places, and then
30694type @w{@kbd{C-u 5 d n}} to display only five decimal places.
30695If you then type @kbd{d n}, all 12 places reappear because the
30696full number is still there on the Calc stack. More surprisingly,
30697even if you exit Embedded mode and later re-enter it for that
30698formula, typing @kbd{d n} will restore all 12 places because
30699each buffer remembers all its active formulas. However, if you
30700save the buffer in a file and reload it in a new Emacs session,
30701all non-displayed digits will have been lost unless you used
30702``plain'' mode.
30703
30704@tex
30705\bigskip
30706@end tex
30707
30708In some applications of Embedded mode, you will want to have a
30709sequence of copies of a formula that show its evolution as you
30710work on it. For example, you might want to have a sequence
30711like this in your file (elaborating here on the example from
30712the ``Getting Started'' chapter):
30713
30714@smallexample
30715The derivative of
30716
30717 ln(ln(x))
30718
30719is
30720
30721 @r{(the derivative of }ln(ln(x))@r{)}
30722
30723whose value at x = 2 is
30724
30725 @r{(the value)}
30726
30727and at x = 3 is
30728
30729 @r{(the value)}
30730@end smallexample
30731
30732@kindex C-x * d
30733@pindex calc-embedded-duplicate
30734The @kbd{C-x * d} (@code{calc-embedded-duplicate}) command is a
30735handy way to make sequences like this. If you type @kbd{C-x * d},
30736the formula under the cursor (which may or may not have Embedded
30737mode enabled for it at the time) is copied immediately below and
30738Embedded mode is then enabled for that copy.
30739
30740For this example, you would start with just
30741
30742@smallexample
30743The derivative of
30744
30745 ln(ln(x))
30746@end smallexample
30747
30748@noindent
30749and press @kbd{C-x * d} with the cursor on this formula. The result
30750is
30751
30752@smallexample
30753The derivative of
30754
30755 ln(ln(x))
30756
30757
30758 ln(ln(x))
30759@end smallexample
30760
30761@noindent
30762with the second copy of the formula enabled in Embedded mode.
30763You can now press @kbd{a d x @key{RET}} to take the derivative, and
30764@kbd{C-x * d C-x * d} to make two more copies of the derivative.
30765To complete the computations, type @kbd{3 s l x @key{RET}} to evaluate
30766the last formula, then move up to the second-to-last formula
30767and type @kbd{2 s l x @key{RET}}.
30768
30769Finally, you would want to press @kbd{C-x * e} to exit Embedded
30770mode, then go up and insert the necessary text in between the
30771various formulas and numbers.
30772
30773@tex
30774\bigskip
30775@end tex
30776
30777@kindex C-x * f
30778@kindex C-x * '
30779@pindex calc-embedded-new-formula
30780The @kbd{C-x * f} (@code{calc-embedded-new-formula}) command
30781creates a new embedded formula at the current point. It inserts
30782some default delimiters, which are usually just blank lines,
30783and then does an algebraic entry to get the formula (which is
30784then enabled for Embedded mode). This is just shorthand for
30785typing the delimiters yourself, positioning the cursor between
30786the new delimiters, and pressing @kbd{C-x * e}. The key sequence
30787@kbd{C-x * '} is equivalent to @kbd{C-x * f}.
30788
30789@kindex C-x * n
30790@kindex C-x * p
30791@pindex calc-embedded-next
30792@pindex calc-embedded-previous
30793The @kbd{C-x * n} (@code{calc-embedded-next}) and @kbd{C-x * p}
30794(@code{calc-embedded-previous}) commands move the cursor to the
30795next or previous active embedded formula in the buffer. They
30796can take positive or negative prefix arguments to move by several
30797formulas. Note that these commands do not actually examine the
30798text of the buffer looking for formulas; they only see formulas
30799which have previously been activated in Embedded mode. In fact,
30800@kbd{C-x * n} and @kbd{C-x * p} are a useful way to tell which
30801embedded formulas are currently active. Also, note that these
30802commands do not enable Embedded mode on the next or previous
30803formula, they just move the cursor.
30804
30805@kindex C-x * `
30806@pindex calc-embedded-edit
30807The @kbd{C-x * `} (@code{calc-embedded-edit}) command edits the
30808embedded formula at the current point as if by @kbd{`} (@code{calc-edit}).
30809Embedded mode does not have to be enabled for this to work. Press
30810@kbd{C-c C-c} to finish the edit, or @kbd{C-x k} to cancel.
30811
30812@node Assignments in Embedded Mode, Mode Settings in Embedded Mode, More About Embedded Mode, Embedded Mode
30813@section Assignments in Embedded Mode
30814
30815@noindent
30816The @samp{:=} (assignment) and @samp{=>} (``evaluates-to'') operators
30817are especially useful in Embedded mode. They allow you to make
30818a definition in one formula, then refer to that definition in
30819other formulas embedded in the same buffer.
30820
30821An embedded formula which is an assignment to a variable, as in
30822
30823@example
30824foo := 5
30825@end example
30826
30827@noindent
30828records @expr{5} as the stored value of @code{foo} for the
30829purposes of Embedded mode operations in the current buffer. It
30830does @emph{not} actually store @expr{5} as the ``global'' value
30831of @code{foo}, however. Regular Calc operations, and Embedded
30832formulas in other buffers, will not see this assignment.
30833
30834One way to use this assigned value is simply to create an
30835Embedded formula elsewhere that refers to @code{foo}, and to press
30836@kbd{=} in that formula. However, this permanently replaces the
30837@code{foo} in the formula with its current value. More interesting
30838is to use @samp{=>} elsewhere:
30839
30840@example
30841foo + 7 => 12
30842@end example
30843
30844@xref{Evaluates-To Operator}, for a general discussion of @samp{=>}.
30845
30846If you move back and change the assignment to @code{foo}, any
30847@samp{=>} formulas which refer to it are automatically updated.
30848
30849@example
30850foo := 17
30851
30852foo + 7 => 24
30853@end example
30854
30855The obvious question then is, @emph{how} can one easily change the
30856assignment to @code{foo}? If you simply select the formula in
30857Embedded mode and type 17, the assignment itself will be replaced
30858by the 17. The effect on the other formula will be that the
30859variable @code{foo} becomes unassigned:
30860
30861@example
3086217
30863
30864foo + 7 => foo + 7
30865@end example
30866
30867The right thing to do is first to use a selection command (@kbd{j 2}
30868will do the trick) to select the righthand side of the assignment.
30869Then, @kbd{17 @key{TAB} @key{DEL}} will swap the 17 into place (@pxref{Selecting
30870Subformulas}, to see how this works).
30871
30872@kindex C-x * j
30873@pindex calc-embedded-select
30874The @kbd{C-x * j} (@code{calc-embedded-select}) command provides an
30875easy way to operate on assignments. It is just like @kbd{C-x * e},
30876except that if the enabled formula is an assignment, it uses
30877@kbd{j 2} to select the righthand side. If the enabled formula
30878is an evaluates-to, it uses @kbd{j 1} to select the lefthand side.
30879A formula can also be a combination of both:
30880
30881@example
30882bar := foo + 3 => 20
30883@end example
30884
30885@noindent
30886in which case @kbd{C-x * j} will select the middle part (@samp{foo + 3}).
30887
30888The formula is automatically deselected when you leave Embedded
30889mode.
30890
30891@kindex C-x * u
30892@pindex calc-embedded-update-formula
30893Another way to change the assignment to @code{foo} would simply be
30894to edit the number using regular Emacs editing rather than Embedded
30895mode. Then, we have to find a way to get Embedded mode to notice
30896the change. The @kbd{C-x * u} (@code{calc-embedded-update-formula})
30897command is a convenient way to do this.
30898
30899@example
30900foo := 6
30901
30902foo + 7 => 13
30903@end example
30904
30905Pressing @kbd{C-x * u} is much like pressing @kbd{C-x * e = C-x * e}, that
30906is, temporarily enabling Embedded mode for the formula under the
30907cursor and then evaluating it with @kbd{=}. But @kbd{C-x * u} does
30908not actually use @kbd{C-x * e}, and in fact another formula somewhere
30909else can be enabled in Embedded mode while you use @kbd{C-x * u} and
30910that formula will not be disturbed.
30911
30912With a numeric prefix argument, @kbd{C-x * u} updates all active
30913@samp{=>} formulas in the buffer. Formulas which have not yet
30914been activated in Embedded mode, and formulas which do not have
30915@samp{=>} as their top-level operator, are not affected by this.
30916(This is useful only if you have used @kbd{m C}; see below.)
30917
30918With a plain @kbd{C-u} prefix, @kbd{C-u C-x * u} updates only in the
30919region between mark and point rather than in the whole buffer.
30920
30921@kbd{C-x * u} is also a handy way to activate a formula, such as an
30922@samp{=>} formula that has freshly been typed in or loaded from a
30923file.
30924
30925@kindex C-x * a
30926@pindex calc-embedded-activate
30927The @kbd{C-x * a} (@code{calc-embedded-activate}) command scans
30928through the current buffer and activates all embedded formulas
30929that contain @samp{:=} or @samp{=>} symbols. This does not mean
30930that Embedded mode is actually turned on, but only that the
30931formulas' positions are registered with Embedded mode so that
30932the @samp{=>} values can be properly updated as assignments are
30933changed.
30934
30935It is a good idea to type @kbd{C-x * a} right after loading a file
30936that uses embedded @samp{=>} operators. Emacs includes a nifty
30937``buffer-local variables'' feature that you can use to do this
30938automatically. The idea is to place near the end of your file
30939a few lines that look like this:
30940
30941@example
30942--- Local Variables: ---
30943--- eval:(calc-embedded-activate) ---
30944--- End: ---
30945@end example
30946
30947@noindent
30948where the leading and trailing @samp{---} can be replaced by
30949any suitable strings (which must be the same on all three lines)
c1dabff0 30950or omitted altogether; in a @TeX{} or @LaTeX{} file, @samp{%} would be a good
4009494e
GM
30951leading string and no trailing string would be necessary. In a
30952C program, @samp{/*} and @samp{*/} would be good leading and
30953trailing strings.
30954
30955When Emacs loads a file into memory, it checks for a Local Variables
30956section like this one at the end of the file. If it finds this
30957section, it does the specified things (in this case, running
30958@kbd{C-x * a} automatically) before editing of the file begins.
30959The Local Variables section must be within 3000 characters of the
30960end of the file for Emacs to find it, and it must be in the last
30961page of the file if the file has any page separators.
30962@xref{File Variables, , Local Variables in Files, emacs, the
30963Emacs manual}.
30964
30965Note that @kbd{C-x * a} does not update the formulas it finds.
30966To do this, type, say, @kbd{M-1 C-x * u} after @w{@kbd{C-x * a}}.
30967Generally this should not be a problem, though, because the
30968formulas will have been up-to-date already when the file was
30969saved.
30970
30971Normally, @kbd{C-x * a} activates all the formulas it finds, but
30972any previous active formulas remain active as well. With a
30973positive numeric prefix argument, @kbd{C-x * a} first deactivates
30974all current active formulas, then actives the ones it finds in
30975its scan of the buffer. With a negative prefix argument,
30976@kbd{C-x * a} simply deactivates all formulas.
30977
30978Embedded mode has two symbols, @samp{Active} and @samp{~Active},
30979which it puts next to the major mode name in a buffer's mode line.
30980It puts @samp{Active} if it has reason to believe that all
30981formulas in the buffer are active, because you have typed @kbd{C-x * a}
30982and Calc has not since had to deactivate any formulas (which can
30983happen if Calc goes to update an @samp{=>} formula somewhere because
30984a variable changed, and finds that the formula is no longer there
30985due to some kind of editing outside of Embedded mode). Calc puts
30986@samp{~Active} in the mode line if some, but probably not all,
30987formulas in the buffer are active. This happens if you activate
30988a few formulas one at a time but never use @kbd{C-x * a}, or if you
30989used @kbd{C-x * a} but then Calc had to deactivate a formula
30990because it lost track of it. If neither of these symbols appears
30991in the mode line, no embedded formulas are active in the buffer
30992(e.g., before Embedded mode has been used, or after a @kbd{M-- C-x * a}).
30993
30994Embedded formulas can refer to assignments both before and after them
30995in the buffer. If there are several assignments to a variable, the
30996nearest preceding assignment is used if there is one, otherwise the
30997following assignment is used.
30998
30999@example
31000x => 1
31001
31002x := 1
31003
31004x => 1
31005
31006x := 2
31007
31008x => 2
31009@end example
31010
31011As well as simple variables, you can also assign to subscript
31012expressions of the form @samp{@var{var}_@var{number}} (as in
31013@code{x_0}), or @samp{@var{var}_@var{var}} (as in @code{x_max}).
31014Assignments to other kinds of objects can be represented by Calc,
31015but the automatic linkage between assignments and references works
31016only for plain variables and these two kinds of subscript expressions.
31017
31018If there are no assignments to a given variable, the global
31019stored value for the variable is used (@pxref{Storing Variables}),
31020or, if no value is stored, the variable is left in symbolic form.
31021Note that global stored values will be lost when the file is saved
31022and loaded in a later Emacs session, unless you have used the
31023@kbd{s p} (@code{calc-permanent-variable}) command to save them;
31024@pxref{Operations on Variables}.
31025
31026The @kbd{m C} (@code{calc-auto-recompute}) command turns automatic
31027recomputation of @samp{=>} forms on and off. If you turn automatic
31028recomputation off, you will have to use @kbd{C-x * u} to update these
31029formulas manually after an assignment has been changed. If you
31030plan to change several assignments at once, it may be more efficient
31031to type @kbd{m C}, change all the assignments, then use @kbd{M-1 C-x * u}
31032to update the entire buffer afterwards. The @kbd{m C} command also
31033controls @samp{=>} formulas on the stack; @pxref{Evaluates-To
31034Operator}. When you turn automatic recomputation back on, the
31035stack will be updated but the Embedded buffer will not; you must
31036use @kbd{C-x * u} to update the buffer by hand.
31037
31038@node Mode Settings in Embedded Mode, Customizing Embedded Mode, Assignments in Embedded Mode, Embedded Mode
31039@section Mode Settings in Embedded Mode
31040
31041@kindex m e
31042@pindex calc-embedded-preserve-modes
31043@noindent
31044The mode settings can be changed while Calc is in embedded mode, but
31045by default they will revert to their original values when embedded mode
31046is ended. However, the modes saved when the mode-recording mode is
31047@code{Save} (see below) and the modes in effect when the @kbd{m e}
31048(@code{calc-embedded-preserve-modes}) command is given
31049will be preserved when embedded mode is ended.
31050
31051Embedded mode has a rather complicated mechanism for handling mode
31052settings in Embedded formulas. It is possible to put annotations
31053in the file that specify mode settings either global to the entire
31054file or local to a particular formula or formulas. In the latter
31055case, different modes can be specified for use when a formula
31056is the enabled Embedded mode formula.
31057
31058When you give any mode-setting command, like @kbd{m f} (for Fraction
31059mode) or @kbd{d s} (for scientific notation), Embedded mode adds
31060a line like the following one to the file just before the opening
31061delimiter of the formula.
31062
31063@example
31064% [calc-mode: fractions: t]
31065% [calc-mode: float-format: (sci 0)]
31066@end example
31067
31068When Calc interprets an embedded formula, it scans the text before
31069the formula for mode-setting annotations like these and sets the
31070Calc buffer to match these modes. Modes not explicitly described
31071in the file are not changed. Calc scans all the way to the top of
31072the file, or up to a line of the form
31073
31074@example
31075% [calc-defaults]
31076@end example
31077
31078@noindent
31079which you can insert at strategic places in the file if this backward
31080scan is getting too slow, or just to provide a barrier between one
31081``zone'' of mode settings and another.
31082
31083If the file contains several annotations for the same mode, the
31084closest one before the formula is used. Annotations after the
31085formula are never used (except for global annotations, described
31086below).
31087
31088The scan does not look for the leading @samp{% }, only for the
31089square brackets and the text they enclose. In fact, the leading
31090characters are different for different major modes. You can edit the
31091mode annotations to a style that works better in context if you wish.
31092@xref{Customizing Embedded Mode}, to see how to change the style
31093that Calc uses when it generates the annotations. You can write
31094mode annotations into the file yourself if you know the syntax;
31095the easiest way to find the syntax for a given mode is to let
31096Calc write the annotation for it once and see what it does.
31097
31098If you give a mode-changing command for a mode that already has
31099a suitable annotation just above the current formula, Calc will
31100modify that annotation rather than generating a new, conflicting
31101one.
31102
31103Mode annotations have three parts, separated by colons. (Spaces
31104after the colons are optional.) The first identifies the kind
31105of mode setting, the second is a name for the mode itself, and
31106the third is the value in the form of a Lisp symbol, number,
31107or list. Annotations with unrecognizable text in the first or
31108second parts are ignored. The third part is not checked to make
31109sure the value is of a valid type or range; if you write an
31110annotation by hand, be sure to give a proper value or results
31111will be unpredictable. Mode-setting annotations are case-sensitive.
31112
31113While Embedded mode is enabled, the word @code{Local} appears in
31114the mode line. This is to show that mode setting commands generate
31115annotations that are ``local'' to the current formula or set of
31116formulas. The @kbd{m R} (@code{calc-mode-record-mode}) command
31117causes Calc to generate different kinds of annotations. Pressing
31118@kbd{m R} repeatedly cycles through the possible modes.
31119
31120@code{LocEdit} and @code{LocPerm} modes generate annotations
31121that look like this, respectively:
31122
31123@example
31124% [calc-edit-mode: float-format: (sci 0)]
31125% [calc-perm-mode: float-format: (sci 5)]
31126@end example
31127
31128The first kind of annotation will be used only while a formula
31129is enabled in Embedded mode. The second kind will be used only
31130when the formula is @emph{not} enabled. (Whether the formula
31131is ``active'' or not, i.e., whether Calc has seen this formula
31132yet, is not relevant here.)
31133
31134@code{Global} mode generates an annotation like this at the end
31135of the file:
31136
31137@example
31138% [calc-global-mode: fractions t]
31139@end example
31140
31141Global mode annotations affect all formulas throughout the file,
31142and may appear anywhere in the file. This allows you to tuck your
31143mode annotations somewhere out of the way, say, on a new page of
31144the file, as long as those mode settings are suitable for all
31145formulas in the file.
31146
31147Enabling a formula with @kbd{C-x * e} causes a fresh scan for local
31148mode annotations; you will have to use this after adding annotations
31149above a formula by hand to get the formula to notice them. Updating
31150a formula with @kbd{C-x * u} will also re-scan the local modes, but
31151global modes are only re-scanned by @kbd{C-x * a}.
31152
31153Another way that modes can get out of date is if you add a local
31154mode annotation to a formula that has another formula after it.
31155In this example, we have used the @kbd{d s} command while the
31156first of the two embedded formulas is active. But the second
31157formula has not changed its style to match, even though by the
31158rules of reading annotations the @samp{(sci 0)} applies to it, too.
31159
31160@example
31161% [calc-mode: float-format: (sci 0)]
311621.23e2
31163
31164456.
31165@end example
31166
31167We would have to go down to the other formula and press @kbd{C-x * u}
31168on it in order to get it to notice the new annotation.
31169
31170Two more mode-recording modes selectable by @kbd{m R} are available
40ba43b4 31171which are also available outside of Embedded mode.
4009494e
GM
31172(@pxref{General Mode Commands}.) They are @code{Save}, in which mode
31173settings are recorded permanently in your Calc init file (the file given
dcf7843e 31174by the variable @code{calc-settings-file}, typically @file{~/.emacs.d/calc.el})
4009494e
GM
31175rather than by annotating the current document, and no-recording
31176mode (where there is no symbol like @code{Save} or @code{Local} in
31177the mode line), in which mode-changing commands do not leave any
31178annotations at all.
31179
31180When Embedded mode is not enabled, mode-recording modes except
31181for @code{Save} have no effect.
31182
31183@node Customizing Embedded Mode, , Mode Settings in Embedded Mode, Embedded Mode
31184@section Customizing Embedded Mode
31185
31186@noindent
31187You can modify Embedded mode's behavior by setting various Lisp
40ba43b4 31188variables described here. These variables are customizable
4009494e
GM
31189(@pxref{Customizing Calc}), or you can use @kbd{M-x set-variable}
31190or @kbd{M-x edit-options} to adjust a variable on the fly.
31191(Another possibility would be to use a file-local variable annotation at
40ba43b4 31192the end of the file;
4009494e
GM
31193@pxref{File Variables, , Local Variables in Files, emacs, the Emacs manual}.)
31194Many of the variables given mentioned here can be set to depend on the
31195major mode of the editing buffer (@pxref{Customizing Calc}).
31196
31197@vindex calc-embedded-open-formula
31198The @code{calc-embedded-open-formula} variable holds a regular
31199expression for the opening delimiter of a formula. @xref{Regexp Search,
31200, Regular Expression Search, emacs, the Emacs manual}, to see
31201how regular expressions work. Basically, a regular expression is a
31202pattern that Calc can search for. A regular expression that considers
31203blank lines, @samp{$}, and @samp{$$} to be opening delimiters is
31204@code{"\\`\\|^\n\\|\\$\\$?"}. Just in case the meaning of this
31205regular expression is not completely plain, let's go through it
31206in detail.
31207
31208The surrounding @samp{" "} marks quote the text between them as a
31209Lisp string. If you left them off, @code{set-variable} or
31210@code{edit-options} would try to read the regular expression as a
31211Lisp program.
31212
31213The most obvious property of this regular expression is that it
31214contains indecently many backslashes. There are actually two levels
31215of backslash usage going on here. First, when Lisp reads a quoted
31216string, all pairs of characters beginning with a backslash are
31217interpreted as special characters. Here, @code{\n} changes to a
31218new-line character, and @code{\\} changes to a single backslash.
31219So the actual regular expression seen by Calc is
31220@samp{\`\|^ @r{(newline)} \|\$\$?}.
31221
31222Regular expressions also consider pairs beginning with backslash
31223to have special meanings. Sometimes the backslash is used to quote
31224a character that otherwise would have a special meaning in a regular
31225expression, like @samp{$}, which normally means ``end-of-line,''
31226or @samp{?}, which means that the preceding item is optional. So
31227@samp{\$\$?} matches either one or two dollar signs.
31228
31229The other codes in this regular expression are @samp{^}, which matches
31230``beginning-of-line,'' @samp{\|}, which means ``or,'' and @samp{\`},
31231which matches ``beginning-of-buffer.'' So the whole pattern means
31232that a formula begins at the beginning of the buffer, or on a newline
31233that occurs at the beginning of a line (i.e., a blank line), or at
31234one or two dollar signs.
31235
31236The default value of @code{calc-embedded-open-formula} looks just
31237like this example, with several more alternatives added on to
31238recognize various other common kinds of delimiters.
31239
31240By the way, the reason to use @samp{^\n} rather than @samp{^$}
31241or @samp{\n\n}, which also would appear to match blank lines,
31242is that the former expression actually ``consumes'' only one
31243newline character as @emph{part of} the delimiter, whereas the
31244latter expressions consume zero or two newlines, respectively.
31245The former choice gives the most natural behavior when Calc
31246must operate on a whole formula including its delimiters.
31247
31248See the Emacs manual for complete details on regular expressions.
31249But just for your convenience, here is a list of all characters
31250which must be quoted with backslash (like @samp{\$}) to avoid
31251some special interpretation: @samp{. * + ? [ ] ^ $ \}. (Note
31252the backslash in this list; for example, to match @samp{\[} you
31253must use @code{"\\\\\\["}. An exercise for the reader is to
31254account for each of these six backslashes!)
31255
31256@vindex calc-embedded-close-formula
31257The @code{calc-embedded-close-formula} variable holds a regular
31258expression for the closing delimiter of a formula. A closing
31259regular expression to match the above example would be
31260@code{"\\'\\|\n$\\|\\$\\$?"}. This is almost the same as the
31261other one, except it now uses @samp{\'} (``end-of-buffer'') and
31262@samp{\n$} (newline occurring at end of line, yet another way
31263of describing a blank line that is more appropriate for this
31264case).
31265
4a65fb7a
JB
31266@vindex calc-embedded-word-regexp
31267The @code{calc-embedded-word-regexp} variable holds a regular expression
31268used to define an expression to look for (a ``word'') when you type
31269@kbd{C-x * w} to enable Embedded mode.
4009494e
GM
31270
31271@vindex calc-embedded-open-plain
31272The @code{calc-embedded-open-plain} variable is a string which
31273begins a ``plain'' formula written in front of the formatted
31274formula when @kbd{d p} mode is turned on. Note that this is an
31275actual string, not a regular expression, because Calc must be able
31276to write this string into a buffer as well as to recognize it.
31277The default string is @code{"%%% "} (note the trailing space), but may
31278be different for certain major modes.
31279
31280@vindex calc-embedded-close-plain
31281The @code{calc-embedded-close-plain} variable is a string which
31282ends a ``plain'' formula. The default is @code{" %%%\n"}, but may be
31283different for different major modes. Without
31284the trailing newline here, the first line of a Big mode formula
31285that followed might be shifted over with respect to the other lines.
31286
31287@vindex calc-embedded-open-new-formula
31288The @code{calc-embedded-open-new-formula} variable is a string
31289which is inserted at the front of a new formula when you type
31290@kbd{C-x * f}. Its default value is @code{"\n\n"}. If this
31291string begins with a newline character and the @kbd{C-x * f} is
31292typed at the beginning of a line, @kbd{C-x * f} will skip this
31293first newline to avoid introducing unnecessary blank lines in
31294the file.
31295
31296@vindex calc-embedded-close-new-formula
31297The @code{calc-embedded-close-new-formula} variable is the corresponding
31298string which is inserted at the end of a new formula. Its default
31299value is also @code{"\n\n"}. The final newline is omitted by
31300@w{@kbd{C-x * f}} if typed at the end of a line. (It follows that if
31301@kbd{C-x * f} is typed on a blank line, both a leading opening
31302newline and a trailing closing newline are omitted.)
31303
31304@vindex calc-embedded-announce-formula
31305The @code{calc-embedded-announce-formula} variable is a regular
31306expression which is sure to be followed by an embedded formula.
31307The @kbd{C-x * a} command searches for this pattern as well as for
31308@samp{=>} and @samp{:=} operators. Note that @kbd{C-x * a} will
31309not activate just anything surrounded by formula delimiters; after
31310all, blank lines are considered formula delimiters by default!
31311But if your language includes a delimiter which can only occur
31312actually in front of a formula, you can take advantage of it here.
31313The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, but may be
31314different for different major modes.
31315This pattern will check for @samp{%Embed} followed by any number of
31316lines beginning with @samp{%} and a space. This last is important to
31317make Calc consider mode annotations part of the pattern, so that the
31318formula's opening delimiter really is sure to follow the pattern.
31319
31320@vindex calc-embedded-open-mode
31321The @code{calc-embedded-open-mode} variable is a string (not a
31322regular expression) which should precede a mode annotation.
31323Calc never scans for this string; Calc always looks for the
31324annotation itself. But this is the string that is inserted before
31325the opening bracket when Calc adds an annotation on its own.
31326The default is @code{"% "}, but may be different for different major
40ba43b4 31327modes.
4009494e
GM
31328
31329@vindex calc-embedded-close-mode
31330The @code{calc-embedded-close-mode} variable is a string which
31331follows a mode annotation written by Calc. Its default value
31332is simply a newline, @code{"\n"}, but may be different for different
31333major modes. If you change this, it is a good idea still to end with a
31334newline so that mode annotations will appear on lines by themselves.
31335
31336@node Programming, Copying, Embedded Mode, Top
31337@chapter Programming
31338
31339@noindent
31340There are several ways to ``program'' the Emacs Calculator, depending
31341on the nature of the problem you need to solve.
31342
31343@enumerate
31344@item
31345@dfn{Keyboard macros} allow you to record a sequence of keystrokes
31346and play them back at a later time. This is just the standard Emacs
31347keyboard macro mechanism, dressed up with a few more features such
31348as loops and conditionals.
31349
31350@item
31351@dfn{Algebraic definitions} allow you to use any formula to define a
31352new function. This function can then be used in algebraic formulas or
31353as an interactive command.
31354
31355@item
31356@dfn{Rewrite rules} are discussed in the section on algebra commands.
31357@xref{Rewrite Rules}. If you put your rewrite rules in the variable
31358@code{EvalRules}, they will be applied automatically to all Calc
31359results in just the same way as an internal ``rule'' is applied to
31360evaluate @samp{sqrt(9)} to 3 and so on. @xref{Automatic Rewrites}.
31361
31362@item
31363@dfn{Lisp} is the programming language that Calc (and most of Emacs)
31364is written in. If the above techniques aren't powerful enough, you
31365can write Lisp functions to do anything that built-in Calc commands
31366can do. Lisp code is also somewhat faster than keyboard macros or
31367rewrite rules.
31368@end enumerate
31369
31370@kindex z
31371Programming features are available through the @kbd{z} and @kbd{Z}
31372prefix keys. New commands that you define are two-key sequences
31373beginning with @kbd{z}. Commands for managing these definitions
31374use the shift-@kbd{Z} prefix. (The @kbd{Z T} (@code{calc-timing})
31375command is described elsewhere; @pxref{Troubleshooting Commands}.
31376The @kbd{Z C} (@code{calc-user-define-composition}) command is also
31377described elsewhere; @pxref{User-Defined Compositions}.)
31378
31379@menu
31380* Creating User Keys::
31381* Keyboard Macros::
31382* Invocation Macros::
31383* Algebraic Definitions::
31384* Lisp Definitions::
31385@end menu
31386
31387@node Creating User Keys, Keyboard Macros, Programming, Programming
31388@section Creating User Keys
31389
31390@noindent
31391@kindex Z D
31392@pindex calc-user-define
31393Any Calculator command may be bound to a key using the @kbd{Z D}
31394(@code{calc-user-define}) command. Actually, it is bound to a two-key
31395sequence beginning with the lower-case @kbd{z} prefix.
31396
31397The @kbd{Z D} command first prompts for the key to define. For example,
31398press @kbd{Z D a} to define the new key sequence @kbd{z a}. You are then
31399prompted for the name of the Calculator command that this key should
31400run. For example, the @code{calc-sincos} command is not normally
31401available on a key. Typing @kbd{Z D s sincos @key{RET}} programs the
31402@kbd{z s} key sequence to run @code{calc-sincos}. This definition will remain
31403in effect for the rest of this Emacs session, or until you redefine
31404@kbd{z s} to be something else.
31405
31406You can actually bind any Emacs command to a @kbd{z} key sequence by
31407backspacing over the @samp{calc-} when you are prompted for the command name.
31408
31409As with any other prefix key, you can type @kbd{z ?} to see a list of
31410all the two-key sequences you have defined that start with @kbd{z}.
31411Initially, no @kbd{z} sequences (except @kbd{z ?} itself) are defined.
31412
31413User keys are typically letters, but may in fact be any key.
31414(@key{META}-keys are not permitted, nor are a terminal's special
31415function keys which generate multi-character sequences when pressed.)
31416You can define different commands on the shifted and unshifted versions
31417of a letter if you wish.
31418
31419@kindex Z U
31420@pindex calc-user-undefine
31421The @kbd{Z U} (@code{calc-user-undefine}) command unbinds a user key.
31422For example, the key sequence @kbd{Z U s} will undefine the @code{sincos}
31423key we defined above.
31424
31425@kindex Z P
31426@pindex calc-user-define-permanent
31427@cindex Storing user definitions
31428@cindex Permanent user definitions
31429@cindex Calc init file, user-defined commands
31430The @kbd{Z P} (@code{calc-user-define-permanent}) command makes a key
31431binding permanent so that it will remain in effect even in future Emacs
31432sessions. (It does this by adding a suitable bit of Lisp code into
31433your Calc init file; that is, the file given by the variable
dcf7843e 31434@code{calc-settings-file}, typically @file{~/.emacs.d/calc.el}.) For example,
4009494e
GM
31435@kbd{Z P s} would register our @code{sincos} command permanently. If
31436you later wish to unregister this command you must edit your Calc init
31437file by hand. (@xref{General Mode Commands}, for a way to tell Calc to
31438use a different file for the Calc init file.)
31439
31440The @kbd{Z P} command also saves the user definition, if any, for the
31441command bound to the key. After @kbd{Z F} and @kbd{Z C}, a given user
31442key could invoke a command, which in turn calls an algebraic function,
31443which might have one or more special display formats. A single @kbd{Z P}
31444command will save all of these definitions.
31445To save an algebraic function, type @kbd{'} (the apostrophe)
31446when prompted for a key, and type the function name. To save a command
31447without its key binding, type @kbd{M-x} and enter a function name. (The
31448@samp{calc-} prefix will automatically be inserted for you.)
31449(If the command you give implies a function, the function will be saved,
31450and if the function has any display formats, those will be saved, but
31451not the other way around: Saving a function will not save any commands
40ba43b4 31452or key bindings associated with the function.)
4009494e
GM
31453
31454@kindex Z E
31455@pindex calc-user-define-edit
31456@cindex Editing user definitions
31457The @kbd{Z E} (@code{calc-user-define-edit}) command edits the definition
31458of a user key. This works for keys that have been defined by either
31459keyboard macros or formulas; further details are contained in the relevant
31460following sections.
31461
31462@node Keyboard Macros, Invocation Macros, Creating User Keys, Programming
31463@section Programming with Keyboard Macros
31464
31465@noindent
31466@kindex X
31467@cindex Programming with keyboard macros
31468@cindex Keyboard macros
31469The easiest way to ``program'' the Emacs Calculator is to use standard
31470keyboard macros. Press @w{@kbd{C-x (}} to begin recording a macro. From
31471this point on, keystrokes you type will be saved away as well as
31472performing their usual functions. Press @kbd{C-x )} to end recording.
31473Press shift-@kbd{X} (or the standard Emacs key sequence @kbd{C-x e}) to
31474execute your keyboard macro by replaying the recorded keystrokes.
31475@xref{Keyboard Macros, , , emacs, the Emacs Manual}, for further
31476information.
31477
31478When you use @kbd{X} to invoke a keyboard macro, the entire macro is
31479treated as a single command by the undo and trail features. The stack
31480display buffer is not updated during macro execution, but is instead
31481fixed up once the macro completes. Thus, commands defined with keyboard
31482macros are convenient and efficient. The @kbd{C-x e} command, on the
31483other hand, invokes the keyboard macro with no special treatment: Each
31484command in the macro will record its own undo information and trail entry,
31485and update the stack buffer accordingly. If your macro uses features
31486outside of Calc's control to operate on the contents of the Calc stack
31487buffer, or if it includes Undo, Redo, or last-arguments commands, you
31488must use @kbd{C-x e} to make sure the buffer and undo list are up-to-date
31489at all times. You could also consider using @kbd{K} (@code{calc-keep-args})
31490instead of @kbd{M-@key{RET}} (@code{calc-last-args}).
31491
31492Calc extends the standard Emacs keyboard macros in several ways.
31493Keyboard macros can be used to create user-defined commands. Keyboard
31494macros can include conditional and iteration structures, somewhat
31495analogous to those provided by a traditional programmable calculator.
31496
31497@menu
31498* Naming Keyboard Macros::
31499* Conditionals in Macros::
31500* Loops in Macros::
31501* Local Values in Macros::
31502* Queries in Macros::
31503@end menu
31504
31505@node Naming Keyboard Macros, Conditionals in Macros, Keyboard Macros, Keyboard Macros
31506@subsection Naming Keyboard Macros
31507
31508@noindent
31509@kindex Z K
31510@pindex calc-user-define-kbd-macro
31511Once you have defined a keyboard macro, you can bind it to a @kbd{z}
31512key sequence with the @kbd{Z K} (@code{calc-user-define-kbd-macro}) command.
31513This command prompts first for a key, then for a command name. For
31514example, if you type @kbd{C-x ( n @key{TAB} n @key{TAB} C-x )} you will
31515define a keyboard macro which negates the top two numbers on the stack
31516(@key{TAB} swaps the top two stack elements). Now you can type
31517@kbd{Z K n @key{RET}} to define this keyboard macro onto the @kbd{z n} key
31518sequence. The default command name (if you answer the second prompt with
31519just the @key{RET} key as in this example) will be something like
31520@samp{calc-User-n}. The keyboard macro will now be available as both
31521@kbd{z n} and @kbd{M-x calc-User-n}. You can backspace and enter a more
31522descriptive command name if you wish.
31523
31524Macros defined by @kbd{Z K} act like single commands; they are executed
31525in the same way as by the @kbd{X} key. If you wish to define the macro
31526as a standard no-frills Emacs macro (to be executed as if by @kbd{C-x e}),
31527give a negative prefix argument to @kbd{Z K}.
31528
31529Once you have bound your keyboard macro to a key, you can use
31530@kbd{Z P} to register it permanently with Emacs. @xref{Creating User Keys}.
31531
31532@cindex Keyboard macros, editing
31533The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
31534been defined by a keyboard macro tries to use the @code{edmacro} package
40ba43b4 31535edit the macro. Type @kbd{C-c C-c} to finish editing and update
4009494e
GM
31536the definition stored on the key, or, to cancel the edit, kill the
31537buffer with @kbd{C-x k}.
31538The special characters @code{RET}, @code{LFD}, @code{TAB}, @code{SPC},
31539@code{DEL}, and @code{NUL} must be entered as these three character
31540sequences, written in all uppercase, as must the prefixes @code{C-} and
31541@code{M-}. Spaces and line breaks are ignored. Other characters are
31542copied verbatim into the keyboard macro. Basically, the notation is the
31543same as is used in all of this manual's examples, except that the manual
31544takes some liberties with spaces: When we say @kbd{' [1 2 3] @key{RET}},
40ba43b4 31545we take it for granted that it is clear we really mean
4009494e
GM
31546@kbd{' [1 @key{SPC} 2 @key{SPC} 3] @key{RET}}.
31547
31548@kindex C-x * m
31549@pindex read-kbd-macro
31550The @kbd{C-x * m} (@code{read-kbd-macro}) command reads an Emacs ``region''
31551of spelled-out keystrokes and defines it as the current keyboard macro.
31552It is a convenient way to define a keyboard macro that has been stored
31553in a file, or to define a macro without executing it at the same time.
31554
31555@node Conditionals in Macros, Loops in Macros, Naming Keyboard Macros, Keyboard Macros
31556@subsection Conditionals in Keyboard Macros
31557
31558@noindent
31559@kindex Z [
31560@kindex Z ]
31561@pindex calc-kbd-if
31562@pindex calc-kbd-else
31563@pindex calc-kbd-else-if
31564@pindex calc-kbd-end-if
31565@cindex Conditional structures
31566The @kbd{Z [} (@code{calc-kbd-if}) and @kbd{Z ]} (@code{calc-kbd-end-if})
31567commands allow you to put simple tests in a keyboard macro. When Calc
31568sees the @kbd{Z [}, it pops an object from the stack and, if the object is
31569a non-zero value, continues executing keystrokes. But if the object is
31570zero, or if it is not provably nonzero, Calc skips ahead to the matching
31571@kbd{Z ]} keystroke. @xref{Logical Operations}, for a set of commands for
31572performing tests which conveniently produce 1 for true and 0 for false.
31573
31574For example, @kbd{@key{RET} 0 a < Z [ n Z ]} implements an absolute-value
31575function in the form of a keyboard macro. This macro duplicates the
31576number on the top of the stack, pushes zero and compares using @kbd{a <}
31577(@code{calc-less-than}), then, if the number was less than zero,
31578executes @kbd{n} (@code{calc-change-sign}). Otherwise, the change-sign
31579command is skipped.
31580
31581To program this macro, type @kbd{C-x (}, type the above sequence of
31582keystrokes, then type @kbd{C-x )}. Note that the keystrokes will be
31583executed while you are making the definition as well as when you later
31584re-execute the macro by typing @kbd{X}. Thus you should make sure a
31585suitable number is on the stack before defining the macro so that you
31586don't get a stack-underflow error during the definition process.
31587
31588Conditionals can be nested arbitrarily. However, there should be exactly
31589one @kbd{Z ]} for each @kbd{Z [} in a keyboard macro.
31590
31591@kindex Z :
31592The @kbd{Z :} (@code{calc-kbd-else}) command allows you to choose between
31593two keystroke sequences. The general format is @kbd{@var{cond} Z [
31594@var{then-part} Z : @var{else-part} Z ]}. If @var{cond} is true
31595(i.e., if the top of stack contains a non-zero number after @var{cond}
31596has been executed), the @var{then-part} will be executed and the
31597@var{else-part} will be skipped. Otherwise, the @var{then-part} will
31598be skipped and the @var{else-part} will be executed.
31599
31600@kindex Z |
31601The @kbd{Z |} (@code{calc-kbd-else-if}) command allows you to choose
31602between any number of alternatives. For example,
31603@kbd{@var{cond1} Z [ @var{part1} Z : @var{cond2} Z | @var{part2} Z :
31604@var{part3} Z ]} will execute @var{part1} if @var{cond1} is true,
31605otherwise it will execute @var{part2} if @var{cond2} is true, otherwise
31606it will execute @var{part3}.
31607
31608More precisely, @kbd{Z [} pops a number and conditionally skips to the
31609next matching @kbd{Z :} or @kbd{Z ]} key. @w{@kbd{Z ]}} has no effect when
31610actually executed. @kbd{Z :} skips to the next matching @kbd{Z ]}.
31611@kbd{Z |} pops a number and conditionally skips to the next matching
31612@kbd{Z :} or @kbd{Z ]}; thus, @kbd{Z [} and @kbd{Z |} are functionally
31613equivalent except that @kbd{Z [} participates in nesting but @kbd{Z |}
31614does not.
31615
31616Calc's conditional and looping constructs work by scanning the
31617keyboard macro for occurrences of character sequences like @samp{Z:}
31618and @samp{Z]}. One side-effect of this is that if you use these
31619constructs you must be careful that these character pairs do not
31620occur by accident in other parts of the macros. Since Calc rarely
31621uses shift-@kbd{Z} for any purpose except as a prefix character, this
31622is not likely to be a problem. Another side-effect is that it will
31623not work to define your own custom key bindings for these commands.
31624Only the standard shift-@kbd{Z} bindings will work correctly.
31625
31626@kindex Z C-g
31627If Calc gets stuck while skipping characters during the definition of a
31628macro, type @kbd{Z C-g} to cancel the definition. (Typing plain @kbd{C-g}
31629actually adds a @kbd{C-g} keystroke to the macro.)
31630
31631@node Loops in Macros, Local Values in Macros, Conditionals in Macros, Keyboard Macros
31632@subsection Loops in Keyboard Macros
31633
31634@noindent
31635@kindex Z <
31636@kindex Z >
31637@pindex calc-kbd-repeat
31638@pindex calc-kbd-end-repeat
31639@cindex Looping structures
31640@cindex Iterative structures
31641The @kbd{Z <} (@code{calc-kbd-repeat}) and @kbd{Z >}
31642(@code{calc-kbd-end-repeat}) commands pop a number from the stack,
31643which must be an integer, then repeat the keystrokes between the brackets
31644the specified number of times. If the integer is zero or negative, the
31645body is skipped altogether. For example, @kbd{1 @key{TAB} Z < 2 * Z >}
31646computes two to a nonnegative integer power. First, we push 1 on the
31647stack and then swap the integer argument back to the top. The @kbd{Z <}
31648pops that argument leaving the 1 back on top of the stack. Then, we
31649repeat a multiply-by-two step however many times.
31650
31651Once again, the keyboard macro is executed as it is being entered.
31652In this case it is especially important to set up reasonable initial
31653conditions before making the definition: Suppose the integer 1000 just
31654happened to be sitting on the stack before we typed the above definition!
31655Another approach is to enter a harmless dummy definition for the macro,
31656then go back and edit in the real one with a @kbd{Z E} command. Yet
31657another approach is to type the macro as written-out keystroke names
31658in a buffer, then use @kbd{C-x * m} (@code{read-kbd-macro}) to read the
31659macro.
31660
31661@kindex Z /
31662@pindex calc-break
31663The @kbd{Z /} (@code{calc-kbd-break}) command allows you to break out
31664of a keyboard macro loop prematurely. It pops an object from the stack;
31665if that object is true (a non-zero number), control jumps out of the
31666innermost enclosing @kbd{Z <} @dots{} @kbd{Z >} loop and continues
31667after the @kbd{Z >}. If the object is false, the @kbd{Z /} has no
31668effect. Thus @kbd{@var{cond} Z /} is similar to @samp{if (@var{cond}) break;}
31669in the C language.
31670
31671@kindex Z (
31672@kindex Z )
31673@pindex calc-kbd-for
31674@pindex calc-kbd-end-for
31675The @kbd{Z (} (@code{calc-kbd-for}) and @kbd{Z )} (@code{calc-kbd-end-for})
31676commands are similar to @kbd{Z <} and @kbd{Z >}, except that they make the
31677value of the counter available inside the loop. The general layout is
31678@kbd{@var{init} @var{final} Z ( @var{body} @var{step} Z )}. The @kbd{Z (}
31679command pops initial and final values from the stack. It then creates
31680a temporary internal counter and initializes it with the value @var{init}.
31681The @kbd{Z (} command then repeatedly pushes the counter value onto the
31682stack and executes @var{body} and @var{step}, adding @var{step} to the
31683counter each time until the loop finishes.
31684
31685@cindex Summations (by keyboard macros)
31686By default, the loop finishes when the counter becomes greater than (or
31687less than) @var{final}, assuming @var{initial} is less than (greater
31688than) @var{final}. If @var{initial} is equal to @var{final}, the body
31689executes exactly once. The body of the loop always executes at least
31690once. For example, @kbd{0 1 10 Z ( 2 ^ + 1 Z )} computes the sum of the
31691squares of the integers from 1 to 10, in steps of 1.
31692
31693If you give a numeric prefix argument of 1 to @kbd{Z (}, the loop is
31694forced to use upward-counting conventions. In this case, if @var{initial}
31695is greater than @var{final} the body will not be executed at all.
31696Note that @var{step} may still be negative in this loop; the prefix
31697argument merely constrains the loop-finished test. Likewise, a prefix
31698argument of @mathit{-1} forces downward-counting conventions.
31699
31700@kindex Z @{
31701@kindex Z @}
31702@pindex calc-kbd-loop
31703@pindex calc-kbd-end-loop
31704The @kbd{Z @{} (@code{calc-kbd-loop}) and @kbd{Z @}}
31705(@code{calc-kbd-end-loop}) commands are similar to @kbd{Z <} and
31706@kbd{Z >}, except that they do not pop a count from the stack---they
31707effectively create an infinite loop. Every @kbd{Z @{} @dots{} @kbd{Z @}}
31708loop ought to include at least one @kbd{Z /} to make sure the loop
31709doesn't run forever. (If any error message occurs which causes Emacs
31710to beep, the keyboard macro will also be halted; this is a standard
31711feature of Emacs. You can also generally press @kbd{C-g} to halt a
31712running keyboard macro, although not all versions of Unix support
31713this feature.)
31714
31715The conditional and looping constructs are not actually tied to
31716keyboard macros, but they are most often used in that context.
31717For example, the keystrokes @kbd{10 Z < 23 @key{RET} Z >} push
31718ten copies of 23 onto the stack. This can be typed ``live'' just
31719as easily as in a macro definition.
31720
31721@xref{Conditionals in Macros}, for some additional notes about
31722conditional and looping commands.
31723
31724@node Local Values in Macros, Queries in Macros, Loops in Macros, Keyboard Macros
31725@subsection Local Values in Macros
31726
31727@noindent
31728@cindex Local variables
31729@cindex Restoring saved modes
31730Keyboard macros sometimes want to operate under known conditions
31731without affecting surrounding conditions. For example, a keyboard
31732macro may wish to turn on Fraction mode, or set a particular
31733precision, independent of the user's normal setting for those
31734modes.
31735
31736@kindex Z `
31737@kindex Z '
31738@pindex calc-kbd-push
31739@pindex calc-kbd-pop
31740Macros also sometimes need to use local variables. Assignments to
31741local variables inside the macro should not affect any variables
31742outside the macro. The @kbd{Z `} (@code{calc-kbd-push}) and @kbd{Z '}
31743(@code{calc-kbd-pop}) commands give you both of these capabilities.
31744
31745When you type @kbd{Z `} (with a backquote or accent grave character),
31746the values of various mode settings are saved away. The ten ``quick''
31747variables @code{q0} through @code{q9} are also saved. When
31748you type @w{@kbd{Z '}} (with an apostrophe), these values are restored.
31749Pairs of @kbd{Z `} and @kbd{Z '} commands may be nested.
31750
31751If a keyboard macro halts due to an error in between a @kbd{Z `} and
31752a @kbd{Z '}, the saved values will be restored correctly even though
31753the macro never reaches the @kbd{Z '} command. Thus you can use
31754@kbd{Z `} and @kbd{Z '} without having to worry about what happens
31755in exceptional conditions.
31756
31757If you type @kbd{Z `} ``live'' (not in a keyboard macro), Calc puts
31758you into a ``recursive edit.'' You can tell you are in a recursive
31759edit because there will be extra square brackets in the mode line,
31760as in @samp{[(Calculator)]}. These brackets will go away when you
31761type the matching @kbd{Z '} command. The modes and quick variables
31762will be saved and restored in just the same way as if actual keyboard
31763macros were involved.
31764
31765The modes saved by @kbd{Z `} and @kbd{Z '} are the current precision
31766and binary word size, the angular mode (Deg, Rad, or HMS), the
31767simplification mode, Algebraic mode, Symbolic mode, Infinite mode,
31768Matrix or Scalar mode, Fraction mode, and the current complex mode
31769(Polar or Rectangular). The ten ``quick'' variables' values (or lack
31770thereof) are also saved.
31771
31772Most mode-setting commands act as toggles, but with a numeric prefix
31773they force the mode either on (positive prefix) or off (negative
31774or zero prefix). Since you don't know what the environment might
31775be when you invoke your macro, it's best to use prefix arguments
31776for all mode-setting commands inside the macro.
31777
31778In fact, @kbd{C-u Z `} is like @kbd{Z `} except that it sets the modes
31779listed above to their default values. As usual, the matching @kbd{Z '}
31780will restore the modes to their settings from before the @kbd{C-u Z `}.
31781Also, @w{@kbd{Z `}} with a negative prefix argument resets the algebraic mode
31782to its default (off) but leaves the other modes the same as they were
31783outside the construct.
31784
31785The contents of the stack and trail, values of non-quick variables, and
31786other settings such as the language mode and the various display modes,
31787are @emph{not} affected by @kbd{Z `} and @kbd{Z '}.
31788
31789@node Queries in Macros, , Local Values in Macros, Keyboard Macros
31790@subsection Queries in Keyboard Macros
31791
31792@c @noindent
31793@c @kindex Z =
31794@c @pindex calc-kbd-report
31795@c The @kbd{Z =} (@code{calc-kbd-report}) command displays an informative
31796@c message including the value on the top of the stack. You are prompted
31797@c to enter a string. That string, along with the top-of-stack value,
31798@c is displayed unless @kbd{m w} (@code{calc-working}) has been used
31799@c to turn such messages off.
31800
31801@noindent
31802@kindex Z #
31803@pindex calc-kbd-query
31804The @kbd{Z #} (@code{calc-kbd-query}) command prompts for an algebraic
31805entry which takes its input from the keyboard, even during macro
31806execution. All the normal conventions of algebraic input, including the
31807use of @kbd{$} characters, are supported. The prompt message itself is
31808taken from the top of the stack, and so must be entered (as a string)
31809before the @kbd{Z #} command. (Recall, as a string it can be entered by
31810pressing the @kbd{"} key and will appear as a vector when it is put on
31811the stack. The prompt message is only put on the stack to provide a
31812prompt for the @kbd{Z #} command; it will not play any role in any
31813subsequent calculations.) This command allows your keyboard macros to
31814accept numbers or formulas as interactive input.
31815
40ba43b4 31816As an example,
4009494e
GM
31817@kbd{2 @key{RET} "Power: " @key{RET} Z # 3 @key{RET} ^} will prompt for
31818input with ``Power: '' in the minibuffer, then return 2 to the provided
31819power. (The response to the prompt that's given, 3 in this example,
31820will not be part of the macro.)
31821
31822@xref{Keyboard Macro Query, , , emacs, the Emacs Manual}, for a description of
31823@kbd{C-x q} (@code{kbd-macro-query}), the standard Emacs way to accept
31824keyboard input during a keyboard macro. In particular, you can use
31825@kbd{C-x q} to enter a recursive edit, which allows the user to perform
31826any Calculator operations interactively before pressing @kbd{C-M-c} to
31827return control to the keyboard macro.
31828
31829@node Invocation Macros, Algebraic Definitions, Keyboard Macros, Programming
31830@section Invocation Macros
31831
31832@kindex C-x * z
31833@kindex Z I
31834@pindex calc-user-invocation
31835@pindex calc-user-define-invocation
31836Calc provides one special keyboard macro, called up by @kbd{C-x * z}
31837(@code{calc-user-invocation}), that is intended to allow you to define
31838your own special way of starting Calc. To define this ``invocation
31839macro,'' create the macro in the usual way with @kbd{C-x (} and
31840@kbd{C-x )}, then type @kbd{Z I} (@code{calc-user-define-invocation}).
31841There is only one invocation macro, so you don't need to type any
31842additional letters after @kbd{Z I}. From now on, you can type
31843@kbd{C-x * z} at any time to execute your invocation macro.
31844
31845For example, suppose you find yourself often grabbing rectangles of
31846numbers into Calc and multiplying their columns. You can do this
31847by typing @kbd{C-x * r} to grab, and @kbd{V R : *} to multiply columns.
31848To make this into an invocation macro, just type @kbd{C-x ( C-x * r
31849V R : * C-x )}, then @kbd{Z I}. Then, to multiply a rectangle of data,
31850just mark the data in its buffer in the usual way and type @kbd{C-x * z}.
31851
31852Invocation macros are treated like regular Emacs keyboard macros;
31853all the special features described above for @kbd{Z K}-style macros
31854do not apply. @kbd{C-x * z} is just like @kbd{C-x e}, except that it
31855uses the macro that was last stored by @kbd{Z I}. (In fact, the
31856macro does not even have to have anything to do with Calc!)
31857
31858The @kbd{m m} command saves the last invocation macro defined by
31859@kbd{Z I} along with all the other Calc mode settings.
31860@xref{General Mode Commands}.
31861
31862@node Algebraic Definitions, Lisp Definitions, Invocation Macros, Programming
31863@section Programming with Formulas
31864
31865@noindent
31866@kindex Z F
31867@pindex calc-user-define-formula
31868@cindex Programming with algebraic formulas
31869Another way to create a new Calculator command uses algebraic formulas.
31870The @kbd{Z F} (@code{calc-user-define-formula}) command stores the
31871formula at the top of the stack as the definition for a key. This
31872command prompts for five things: The key, the command name, the function
31873name, the argument list, and the behavior of the command when given
31874non-numeric arguments.
31875
31876For example, suppose we type @kbd{' a+2b @key{RET}} to push the formula
31877@samp{a + 2*b} onto the stack. We now type @kbd{Z F m} to define this
31878formula on the @kbd{z m} key sequence. The next prompt is for a command
31879name, beginning with @samp{calc-}, which should be the long (@kbd{M-x}) form
31880for the new command. If you simply press @key{RET}, a default name like
31881@code{calc-User-m} will be constructed. In our example, suppose we enter
31882@kbd{spam @key{RET}} to define the new command as @code{calc-spam}.
31883
31884If you want to give the formula a long-style name only, you can press
31885@key{SPC} or @key{RET} when asked which single key to use. For example
31886@kbd{Z F @key{RET} spam @key{RET}} defines the new command as
31887@kbd{M-x calc-spam}, with no keyboard equivalent.
31888
31889The third prompt is for an algebraic function name. The default is to
31890use the same name as the command name but without the @samp{calc-}
31891prefix. (If this is of the form @samp{User-m}, the hyphen is removed so
31892it won't be taken for a minus sign in algebraic formulas.)
40ba43b4 31893This is the name you will use if you want to enter your
4009494e
GM
31894new function in an algebraic formula. Suppose we enter @kbd{yow @key{RET}}.
31895Then the new function can be invoked by pushing two numbers on the
31896stack and typing @kbd{z m} or @kbd{x spam}, or by entering the algebraic
31897formula @samp{yow(x,y)}.
31898
31899The fourth prompt is for the function's argument list. This is used to
31900associate values on the stack with the variables that appear in the formula.
31901The default is a list of all variables which appear in the formula, sorted
31902into alphabetical order. In our case, the default would be @samp{(a b)}.
31903This means that, when the user types @kbd{z m}, the Calculator will remove
31904two numbers from the stack, substitute these numbers for @samp{a} and
31905@samp{b} (respectively) in the formula, then simplify the formula and
31906push the result on the stack. In other words, @kbd{10 @key{RET} 100 z m}
31907would replace the 10 and 100 on the stack with the number 210, which is
31908@expr{a + 2 b} with @expr{a=10} and @expr{b=100}. Likewise, the formula
31909@samp{yow(10, 100)} will be evaluated by substituting @expr{a=10} and
31910@expr{b=100} in the definition.
31911
31912You can rearrange the order of the names before pressing @key{RET} to
31913control which stack positions go to which variables in the formula. If
31914you remove a variable from the argument list, that variable will be left
31915in symbolic form by the command. Thus using an argument list of @samp{(b)}
31916for our function would cause @kbd{10 z m} to replace the 10 on the stack
31917with the formula @samp{a + 20}. If we had used an argument list of
31918@samp{(b a)}, the result with inputs 10 and 100 would have been 120.
31919
31920You can also put a nameless function on the stack instead of just a
31921formula, as in @samp{<a, b : a + 2 b>}. @xref{Specifying Operators}.
31922In this example, the command will be defined by the formula @samp{a + 2 b}
31923using the argument list @samp{(a b)}.
31924
31925The final prompt is a y-or-n question concerning what to do if symbolic
31926arguments are given to your function. If you answer @kbd{y}, then
31927executing @kbd{z m} (using the original argument list @samp{(a b)}) with
31928arguments @expr{10} and @expr{x} will leave the function in symbolic
31929form, i.e., @samp{yow(10,x)}. On the other hand, if you answer @kbd{n},
31930then the formula will always be expanded, even for non-constant
31931arguments: @samp{10 + 2 x}. If you never plan to feed algebraic
31932formulas to your new function, it doesn't matter how you answer this
31933question.
31934
31935If you answered @kbd{y} to this question you can still cause a function
31936call to be expanded by typing @kbd{a "} (@code{calc-expand-formula}).
31937Also, Calc will expand the function if necessary when you take a
31938derivative or integral or solve an equation involving the function.
31939
31940@kindex Z G
31941@pindex calc-get-user-defn
31942Once you have defined a formula on a key, you can retrieve this formula
31943with the @kbd{Z G} (@code{calc-user-define-get-defn}) command. Press a
31944key, and this command pushes the formula that was used to define that
31945key onto the stack. Actually, it pushes a nameless function that
31946specifies both the argument list and the defining formula. You will get
31947an error message if the key is undefined, or if the key was not defined
31948by a @kbd{Z F} command.
31949
31950The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
31951been defined by a formula uses a variant of the @code{calc-edit} command
31952to edit the defining formula. Press @kbd{C-c C-c} to finish editing and
31953store the new formula back in the definition, or kill the buffer with
31954@kbd{C-x k} to
31955cancel the edit. (The argument list and other properties of the
31956definition are unchanged; to adjust the argument list, you can use
31957@kbd{Z G} to grab the function onto the stack, edit with @kbd{`}, and
31958then re-execute the @kbd{Z F} command.)
31959
31960As usual, the @kbd{Z P} command records your definition permanently.
31961In this case it will permanently record all three of the relevant
31962definitions: the key, the command, and the function.
31963
31964You may find it useful to turn off the default simplifications with
31965@kbd{m O} (@code{calc-no-simplify-mode}) when entering a formula to be
31966used as a function definition. For example, the formula @samp{deriv(a^2,v)}
31967which might be used to define a new function @samp{dsqr(a,v)} will be
31968``simplified'' to 0 immediately upon entry since @code{deriv} considers
31969@expr{a} to be constant with respect to @expr{v}. Turning off
31970default simplifications cures this problem: The definition will be stored
31971in symbolic form without ever activating the @code{deriv} function. Press
31972@kbd{m D} to turn the default simplifications back on afterwards.
31973
31974@node Lisp Definitions, , Algebraic Definitions, Programming
31975@section Programming with Lisp
31976
31977@noindent
31978The Calculator can be programmed quite extensively in Lisp. All you
31979do is write a normal Lisp function definition, but with @code{defmath}
31980in place of @code{defun}. This has the same form as @code{defun}, but it
31981automagically replaces calls to standard Lisp functions like @code{+} and
31982@code{zerop} with calls to the corresponding functions in Calc's own library.
31983Thus you can write natural-looking Lisp code which operates on all of the
31984standard Calculator data types. You can then use @kbd{Z D} if you wish to
31985bind your new command to a @kbd{z}-prefix key sequence. The @kbd{Z E} command
31986will not edit a Lisp-based definition.
31987
31988Emacs Lisp is described in the GNU Emacs Lisp Reference Manual. This section
31989assumes a familiarity with Lisp programming concepts; if you do not know
31990Lisp, you may find keyboard macros or rewrite rules to be an easier way
31991to program the Calculator.
31992
31993This section first discusses ways to write commands, functions, or
31994small programs to be executed inside of Calc. Then it discusses how
31995your own separate programs are able to call Calc from the outside.
31996Finally, there is a list of internal Calc functions and data structures
31997for the true Lisp enthusiast.
31998
31999@menu
32000* Defining Functions::
32001* Defining Simple Commands::
32002* Defining Stack Commands::
32003* Argument Qualifiers::
32004* Example Definitions::
32005
32006* Calling Calc from Your Programs::
32007* Internals::
32008@end menu
32009
32010@node Defining Functions, Defining Simple Commands, Lisp Definitions, Lisp Definitions
32011@subsection Defining New Functions
32012
32013@noindent
32014@findex defmath
32015The @code{defmath} function (actually a Lisp macro) is like @code{defun}
32016except that code in the body of the definition can make use of the full
32017range of Calculator data types. The prefix @samp{calcFunc-} is added
32018to the specified name to get the actual Lisp function name. As a simple
32019example,
32020
32021@example
32022(defmath myfact (n)
32023 (if (> n 0)
32024 (* n (myfact (1- n)))
32025 1))
32026@end example
32027
32028@noindent
32029This actually expands to the code,
32030
32031@example
32032(defun calcFunc-myfact (n)
32033 (if (math-posp n)
32034 (math-mul n (calcFunc-myfact (math-add n -1)))
32035 1))
32036@end example
32037
32038@noindent
32039This function can be used in algebraic expressions, e.g., @samp{myfact(5)}.
32040
32041The @samp{myfact} function as it is defined above has the bug that an
32042expression @samp{myfact(a+b)} will be simplified to 1 because the
32043formula @samp{a+b} is not considered to be @code{posp}. A robust
32044factorial function would be written along the following lines:
32045
32046@smallexample
32047(defmath myfact (n)
32048 (if (> n 0)
32049 (* n (myfact (1- n)))
32050 (if (= n 0)
32051 1
32052 nil))) ; this could be simplified as: (and (= n 0) 1)
32053@end smallexample
32054
32055If a function returns @code{nil}, it is left unsimplified by the Calculator
32056(except that its arguments will be simplified). Thus, @samp{myfact(a+1+2)}
32057will be simplified to @samp{myfact(a+3)} but no further. Beware that every
32058time the Calculator reexamines this formula it will attempt to resimplify
32059it, so your function ought to detect the returning-@code{nil} case as
32060efficiently as possible.
32061
32062The following standard Lisp functions are treated by @code{defmath}:
32063@code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^} or
32064@code{expt}, @code{=}, @code{<}, @code{>}, @code{<=}, @code{>=},
32065@code{/=}, @code{1+}, @code{1-}, @code{logand}, @code{logior}, @code{logxor},
32066@code{logandc2}, @code{lognot}. Also, @code{~=} is an abbreviation for
32067@code{math-nearly-equal}, which is useful in implementing Taylor series.
32068
32069For other functions @var{func}, if a function by the name
32070@samp{calcFunc-@var{func}} exists it is used, otherwise if a function by the
32071name @samp{math-@var{func}} exists it is used, otherwise if @var{func} itself
32072is defined as a function it is used, otherwise @samp{calcFunc-@var{func}} is
32073used on the assumption that this is a to-be-defined math function. Also, if
32074the function name is quoted as in @samp{('integerp a)} the function name is
32075always used exactly as written (but not quoted).
32076
32077Variable names have @samp{var-} prepended to them unless they appear in
32078the function's argument list or in an enclosing @code{let}, @code{let*},
32079@code{for}, or @code{foreach} form,
32080or their names already contain a @samp{-} character. Thus a reference to
32081@samp{foo} is the same as a reference to @samp{var-foo}.
32082
32083A few other Lisp extensions are available in @code{defmath} definitions:
32084
32085@itemize @bullet
32086@item
32087The @code{elt} function accepts any number of index variables.
32088Note that Calc vectors are stored as Lisp lists whose first
32089element is the symbol @code{vec}; thus, @samp{(elt v 2)} yields
32090the second element of vector @code{v}, and @samp{(elt m i j)}
32091yields one element of a Calc matrix.
32092
32093@item
32094The @code{setq} function has been extended to act like the Common
32095Lisp @code{setf} function. (The name @code{setf} is recognized as
32096a synonym of @code{setq}.) Specifically, the first argument of
32097@code{setq} can be an @code{nth}, @code{elt}, @code{car}, or @code{cdr} form,
32098in which case the effect is to store into the specified
32099element of a list. Thus, @samp{(setq (elt m i j) x)} stores @expr{x}
32100into one element of a matrix.
32101
32102@item
32103A @code{for} looping construct is available. For example,
32104@samp{(for ((i 0 10)) body)} executes @code{body} once for each
32105binding of @expr{i} from zero to 10. This is like a @code{let}
32106form in that @expr{i} is temporarily bound to the loop count
32107without disturbing its value outside the @code{for} construct.
32108Nested loops, as in @samp{(for ((i 0 10) (j 0 (1- i) 2)) body)},
32109are also available. For each value of @expr{i} from zero to 10,
32110@expr{j} counts from 0 to @expr{i-1} in steps of two. Note that
32111@code{for} has the same general outline as @code{let*}, except
32112that each element of the header is a list of three or four
32113things, not just two.
32114
32115@item
32116The @code{foreach} construct loops over elements of a list.
32117For example, @samp{(foreach ((x (cdr v))) body)} executes
32118@code{body} with @expr{x} bound to each element of Calc vector
32119@expr{v} in turn. The purpose of @code{cdr} here is to skip over
32120the initial @code{vec} symbol in the vector.
32121
32122@item
32123The @code{break} function breaks out of the innermost enclosing
32124@code{while}, @code{for}, or @code{foreach} loop. If given a
32125value, as in @samp{(break x)}, this value is returned by the
32126loop. (Lisp loops otherwise always return @code{nil}.)
32127
32128@item
32129The @code{return} function prematurely returns from the enclosing
32130function. For example, @samp{(return (+ x y))} returns @expr{x+y}
32131as the value of a function. You can use @code{return} anywhere
32132inside the body of the function.
32133@end itemize
32134
32135Non-integer numbers (and extremely large integers) cannot be included
32136directly into a @code{defmath} definition. This is because the Lisp
32137reader will fail to parse them long before @code{defmath} ever gets control.
32138Instead, use the notation, @samp{:"3.1415"}. In fact, any algebraic
32139formula can go between the quotes. For example,
32140
32141@smallexample
32142(defmath sqexp (x) ; sqexp(x) == sqrt(exp(x)) == exp(x*0.5)
32143 (and (numberp x)
32144 (exp :"x * 0.5")))
32145@end smallexample
32146
32147expands to
32148
32149@smallexample
32150(defun calcFunc-sqexp (x)
32151 (and (math-numberp x)
32152 (calcFunc-exp (math-mul x '(float 5 -1)))))
32153@end smallexample
32154
32155Note the use of @code{numberp} as a guard to ensure that the argument is
32156a number first, returning @code{nil} if not. The exponential function
32157could itself have been included in the expression, if we had preferred:
32158@samp{:"exp(x * 0.5)"}. As another example, the multiplication-and-recursion
32159step of @code{myfact} could have been written
32160
32161@example
32162:"n * myfact(n-1)"
32163@end example
32164
32165A good place to put your @code{defmath} commands is your Calc init file
32166(the file given by @code{calc-settings-file}, typically
dcf7843e 32167@file{~/.emacs.d/calc.el}), which will not be loaded until Calc starts.
4009494e
GM
32168If a file named @file{.emacs} exists in your home directory, Emacs reads
32169and executes the Lisp forms in this file as it starts up. While it may
32170seem reasonable to put your favorite @code{defmath} commands there,
32171this has the unfortunate side-effect that parts of the Calculator must be
32172loaded in to process the @code{defmath} commands whether or not you will
32173actually use the Calculator! If you want to put the @code{defmath}
32174commands there (for example, if you redefine @code{calc-settings-file}
32175to be @file{.emacs}), a better effect can be had by writing
32176
32177@example
32178(put 'calc-define 'thing '(progn
32179 (defmath ... )
32180 (defmath ... )
32181))
32182@end example
32183
32184@noindent
32185@vindex calc-define
32186The @code{put} function adds a @dfn{property} to a symbol. Each Lisp
32187symbol has a list of properties associated with it. Here we add a
32188property with a name of @code{thing} and a @samp{(progn ...)} form as
32189its value. When Calc starts up, and at the start of every Calc command,
32190the property list for the symbol @code{calc-define} is checked and the
32191values of any properties found are evaluated as Lisp forms. The
32192properties are removed as they are evaluated. The property names
32193(like @code{thing}) are not used; you should choose something like the
32194name of your project so as not to conflict with other properties.
32195
32196The net effect is that you can put the above code in your @file{.emacs}
32197file and it will not be executed until Calc is loaded. Or, you can put
32198that same code in another file which you load by hand either before or
32199after Calc itself is loaded.
32200
32201The properties of @code{calc-define} are evaluated in the same order
32202that they were added. They can assume that the Calc modules @file{calc.el},
32203@file{calc-ext.el}, and @file{calc-macs.el} have been fully loaded, and
32204that the @samp{*Calculator*} buffer will be the current buffer.
32205
32206If your @code{calc-define} property only defines algebraic functions,
32207you can be sure that it will have been evaluated before Calc tries to
32208call your function, even if the file defining the property is loaded
32209after Calc is loaded. But if the property defines commands or key
32210sequences, it may not be evaluated soon enough. (Suppose it defines the
32211new command @code{tweak-calc}; the user can load your file, then type
32212@kbd{M-x tweak-calc} before Calc has had chance to do anything.) To
32213protect against this situation, you can put
32214
32215@example
32216(run-hooks 'calc-check-defines)
32217@end example
32218
32219@findex calc-check-defines
32220@noindent
32221at the end of your file. The @code{calc-check-defines} function is what
32222looks for and evaluates properties on @code{calc-define}; @code{run-hooks}
32223has the advantage that it is quietly ignored if @code{calc-check-defines}
32224is not yet defined because Calc has not yet been loaded.
32225
32226Examples of things that ought to be enclosed in a @code{calc-define}
32227property are @code{defmath} calls, @code{define-key} calls that modify
32228the Calc key map, and any calls that redefine things defined inside Calc.
32229Ordinary @code{defun}s need not be enclosed with @code{calc-define}.
32230
32231@node Defining Simple Commands, Defining Stack Commands, Defining Functions, Lisp Definitions
32232@subsection Defining New Simple Commands
32233
32234@noindent
32235@findex interactive
32236If a @code{defmath} form contains an @code{interactive} clause, it defines
32237a Calculator command. Actually such a @code{defmath} results in @emph{two}
32238function definitions: One, a @samp{calcFunc-} function as was just described,
32239with the @code{interactive} clause removed. Two, a @samp{calc-} function
32240with a suitable @code{interactive} clause and some sort of wrapper to make
32241the command work in the Calc environment.
32242
32243In the simple case, the @code{interactive} clause has the same form as
32244for normal Emacs Lisp commands:
32245
32246@smallexample
32247(defmath increase-precision (delta)
32248 "Increase precision by DELTA." ; This is the "documentation string"
32249 (interactive "p") ; Register this as a M-x-able command
32250 (setq calc-internal-prec (+ calc-internal-prec delta)))
32251@end smallexample
32252
32253This expands to the pair of definitions,
32254
32255@smallexample
32256(defun calc-increase-precision (delta)
32257 "Increase precision by DELTA."
32258 (interactive "p")
32259 (calc-wrapper
32260 (setq calc-internal-prec (math-add calc-internal-prec delta))))
32261
32262(defun calcFunc-increase-precision (delta)
32263 "Increase precision by DELTA."
32264 (setq calc-internal-prec (math-add calc-internal-prec delta)))
32265@end smallexample
32266
32267@noindent
32268where in this case the latter function would never really be used! Note
32269that since the Calculator stores small integers as plain Lisp integers,
32270the @code{math-add} function will work just as well as the native
32271@code{+} even when the intent is to operate on native Lisp integers.
32272
32273@findex calc-wrapper
32274The @samp{calc-wrapper} call invokes a macro which surrounds the body of
32275the function with code that looks roughly like this:
32276
32277@smallexample
32278(let ((calc-command-flags nil))
32279 (unwind-protect
c57008f6 32280 (save-current-buffer
4009494e
GM
32281 (calc-select-buffer)
32282 @emph{body of function}
32283 @emph{renumber stack}
32284 @emph{clear} Working @emph{message})
32285 @emph{realign cursor and window}
32286 @emph{clear Inverse, Hyperbolic, and Keep Args flags}
32287 @emph{update Emacs mode line}))
32288@end smallexample
32289
32290@findex calc-select-buffer
32291The @code{calc-select-buffer} function selects the @samp{*Calculator*}
32292buffer if necessary, say, because the command was invoked from inside
32293the @samp{*Calc Trail*} window.
32294
32295@findex calc-set-command-flag
32296You can call, for example, @code{(calc-set-command-flag 'no-align)} to
32297set the above-mentioned command flags. Calc routines recognize the
32298following command flags:
32299
32300@table @code
32301@item renum-stack
32302Stack line numbers @samp{1:}, @samp{2:}, and so on must be renumbered
32303after this command completes. This is set by routines like
32304@code{calc-push}.
32305
32306@item clear-message
32307Calc should call @samp{(message "")} if this command completes normally
32308(to clear a ``Working@dots{}'' message out of the echo area).
32309
32310@item no-align
32311Do not move the cursor back to the @samp{.} top-of-stack marker.
32312
32313@item position-point
32314Use the variables @code{calc-position-point-line} and
32315@code{calc-position-point-column} to position the cursor after
32316this command finishes.
32317
32318@item keep-flags
32319Do not clear @code{calc-inverse-flag}, @code{calc-hyperbolic-flag},
32320and @code{calc-keep-args-flag} at the end of this command.
32321
32322@item do-edit
32323Switch to buffer @samp{*Calc Edit*} after this command.
32324
32325@item hold-trail
32326Do not move trail pointer to end of trail when something is recorded
32327there.
32328@end table
32329
32330@kindex Y
32331@kindex Y ?
32332@vindex calc-Y-help-msgs
32333Calc reserves a special prefix key, shift-@kbd{Y}, for user-written
32334extensions to Calc. There are no built-in commands that work with
32335this prefix key; you must call @code{define-key} from Lisp (probably
32336from inside a @code{calc-define} property) to add to it. Initially only
32337@kbd{Y ?} is defined; it takes help messages from a list of strings
32338(initially @code{nil}) in the variable @code{calc-Y-help-msgs}. All
32339other undefined keys except for @kbd{Y} are reserved for use by
32340future versions of Calc.
32341
32342If you are writing a Calc enhancement which you expect to give to
32343others, it is best to minimize the number of @kbd{Y}-key sequences
32344you use. In fact, if you have more than one key sequence you should
32345consider defining three-key sequences with a @kbd{Y}, then a key that
32346stands for your package, then a third key for the particular command
32347within your package.
32348
32349Users may wish to install several Calc enhancements, and it is possible
32350that several enhancements will choose to use the same key. In the
32351example below, a variable @code{inc-prec-base-key} has been defined
32352to contain the key that identifies the @code{inc-prec} package. Its
32353value is initially @code{"P"}, but a user can change this variable
32354if necessary without having to modify the file.
32355
32356Here is a complete file, @file{inc-prec.el}, which makes a @kbd{Y P I}
32357command that increases the precision, and a @kbd{Y P D} command that
32358decreases the precision.
32359
32360@smallexample
32361;;; Increase and decrease Calc precision. Dave Gillespie, 5/31/91.
32362;; (Include copyright or copyleft stuff here.)
32363
32364(defvar inc-prec-base-key "P"
32365 "Base key for inc-prec.el commands.")
32366
32367(put 'calc-define 'inc-prec '(progn
32368
32369(define-key calc-mode-map (format "Y%sI" inc-prec-base-key)
32370 'increase-precision)
32371(define-key calc-mode-map (format "Y%sD" inc-prec-base-key)
32372 'decrease-precision)
32373
32374(setq calc-Y-help-msgs
32375 (cons (format "%s + Inc-prec, Dec-prec" inc-prec-base-key)
32376 calc-Y-help-msgs))
32377
32378(defmath increase-precision (delta)
32379 "Increase precision by DELTA."
32380 (interactive "p")
32381 (setq calc-internal-prec (+ calc-internal-prec delta)))
32382
32383(defmath decrease-precision (delta)
32384 "Decrease precision by DELTA."
32385 (interactive "p")
32386 (setq calc-internal-prec (- calc-internal-prec delta)))
32387
32388)) ; end of calc-define property
32389
32390(run-hooks 'calc-check-defines)
32391@end smallexample
32392
32393@node Defining Stack Commands, Argument Qualifiers, Defining Simple Commands, Lisp Definitions
32394@subsection Defining New Stack-Based Commands
32395
32396@noindent
32397To define a new computational command which takes and/or leaves arguments
32398on the stack, a special form of @code{interactive} clause is used.
32399
32400@example
32401(interactive @var{num} @var{tag})
32402@end example
32403
32404@noindent
32405where @var{num} is an integer, and @var{tag} is a string. The effect is
32406to pop @var{num} values off the stack, resimplify them by calling
32407@code{calc-normalize}, and hand them to your function according to the
32408function's argument list. Your function may include @code{&optional} and
32409@code{&rest} parameters, so long as calling the function with @var{num}
32410parameters is valid.
32411
32412Your function must return either a number or a formula in a form
32413acceptable to Calc, or a list of such numbers or formulas. These value(s)
32414are pushed onto the stack when the function completes. They are also
32415recorded in the Calc Trail buffer on a line beginning with @var{tag},
32416a string of (normally) four characters or less. If you omit @var{tag}
32417or use @code{nil} as a tag, the result is not recorded in the trail.
32418
32419As an example, the definition
32420
32421@smallexample
32422(defmath myfact (n)
32423 "Compute the factorial of the integer at the top of the stack."
32424 (interactive 1 "fact")
32425 (if (> n 0)
32426 (* n (myfact (1- n)))
32427 (and (= n 0) 1)))
32428@end smallexample
32429
32430@noindent
32431is a version of the factorial function shown previously which can be used
32432as a command as well as an algebraic function. It expands to
32433
32434@smallexample
32435(defun calc-myfact ()
32436 "Compute the factorial of the integer at the top of the stack."
32437 (interactive)
32438 (calc-slow-wrapper
32439 (calc-enter-result 1 "fact"
32440 (cons 'calcFunc-myfact (calc-top-list-n 1)))))
32441
32442(defun calcFunc-myfact (n)
32443 "Compute the factorial of the integer at the top of the stack."
32444 (if (math-posp n)
32445 (math-mul n (calcFunc-myfact (math-add n -1)))
32446 (and (math-zerop n) 1)))
32447@end smallexample
32448
32449@findex calc-slow-wrapper
32450The @code{calc-slow-wrapper} function is a version of @code{calc-wrapper}
32451that automatically puts up a @samp{Working...} message before the
32452computation begins. (This message can be turned off by the user
32453with an @kbd{m w} (@code{calc-working}) command.)
32454
32455@findex calc-top-list-n
32456The @code{calc-top-list-n} function returns a list of the specified number
32457of values from the top of the stack. It resimplifies each value by
32458calling @code{calc-normalize}. If its argument is zero it returns an
32459empty list. It does not actually remove these values from the stack.
32460
32461@findex calc-enter-result
32462The @code{calc-enter-result} function takes an integer @var{num} and string
32463@var{tag} as described above, plus a third argument which is either a
32464Calculator data object or a list of such objects. These objects are
32465resimplified and pushed onto the stack after popping the specified number
32466of values from the stack. If @var{tag} is non-@code{nil}, the values
32467being pushed are also recorded in the trail.
32468
32469Note that if @code{calcFunc-myfact} returns @code{nil} this represents
32470``leave the function in symbolic form.'' To return an actual empty list,
32471in the sense that @code{calc-enter-result} will push zero elements back
32472onto the stack, you should return the special value @samp{'(nil)}, a list
32473containing the single symbol @code{nil}.
32474
32475The @code{interactive} declaration can actually contain a limited
32476Emacs-style code string as well which comes just before @var{num} and
32477@var{tag}. Currently the only Emacs code supported is @samp{"p"}, as in
32478
32479@example
32480(defmath foo (a b &optional c)
32481 (interactive "p" 2 "foo")
32482 @var{body})
32483@end example
32484
32485In this example, the command @code{calc-foo} will evaluate the expression
32486@samp{foo(a,b)} if executed with no argument, or @samp{foo(a,b,n)} if
32487executed with a numeric prefix argument of @expr{n}.
32488
32489The other code string allowed is @samp{"m"} (unrelated to the usual @samp{"m"}
32490code as used with @code{defun}). It uses the numeric prefix argument as the
32491number of objects to remove from the stack and pass to the function.
32492In this case, the integer @var{num} serves as a default number of
32493arguments to be used when no prefix is supplied.
32494
32495@node Argument Qualifiers, Example Definitions, Defining Stack Commands, Lisp Definitions
32496@subsection Argument Qualifiers
32497
32498@noindent
32499Anywhere a parameter name can appear in the parameter list you can also use
32500an @dfn{argument qualifier}. Thus the general form of a definition is:
32501
32502@example
32503(defmath @var{name} (@var{param} @var{param...}
32504 &optional @var{param} @var{param...}
32505 &rest @var{param})
32506 @var{body})
32507@end example
32508
32509@noindent
32510where each @var{param} is either a symbol or a list of the form
32511
32512@example
32513(@var{qual} @var{param})
32514@end example
32515
32516The following qualifiers are recognized:
32517
32518@table @samp
32519@item complete
32520@findex complete
32521The argument must not be an incomplete vector, interval, or complex number.
32522(This is rarely needed since the Calculator itself will never call your
32523function with an incomplete argument. But there is nothing stopping your
32524own Lisp code from calling your function with an incomplete argument.)
32525
32526@item integer
32527@findex integer
32528The argument must be an integer. If it is an integer-valued float
32529it will be accepted but converted to integer form. Non-integers and
32530formulas are rejected.
32531
32532@item natnum
32533@findex natnum
32534Like @samp{integer}, but the argument must be non-negative.
32535
32536@item fixnum
32537@findex fixnum
32538Like @samp{integer}, but the argument must fit into a native Lisp integer,
32539which on most systems means less than 2^23 in absolute value. The
32540argument is converted into Lisp-integer form if necessary.
32541
32542@item float
32543@findex float
32544The argument is converted to floating-point format if it is a number or
32545vector. If it is a formula it is left alone. (The argument is never
32546actually rejected by this qualifier.)
32547
32548@item @var{pred}
32549The argument must satisfy predicate @var{pred}, which is one of the
32550standard Calculator predicates. @xref{Predicates}.
32551
32552@item not-@var{pred}
32553The argument must @emph{not} satisfy predicate @var{pred}.
32554@end table
32555
32556For example,
32557
32558@example
32559(defmath foo (a (constp (not-matrixp b)) &optional (float c)
32560 &rest (integer d))
32561 @var{body})
32562@end example
32563
32564@noindent
32565expands to
32566
32567@example
32568(defun calcFunc-foo (a b &optional c &rest d)
32569 (and (math-matrixp b)
32570 (math-reject-arg b 'not-matrixp))
32571 (or (math-constp b)
32572 (math-reject-arg b 'constp))
32573 (and c (setq c (math-check-float c)))
32574 (setq d (mapcar 'math-check-integer d))
32575 @var{body})
32576@end example
32577
32578@noindent
32579which performs the necessary checks and conversions before executing the
32580body of the function.
32581
32582@node Example Definitions, Calling Calc from Your Programs, Argument Qualifiers, Lisp Definitions
32583@subsection Example Definitions
32584
32585@noindent
32586This section includes some Lisp programming examples on a larger scale.
32587These programs make use of some of the Calculator's internal functions;
32588@pxref{Internals}.
32589
32590@menu
32591* Bit Counting Example::
32592* Sine Example::
32593@end menu
32594
32595@node Bit Counting Example, Sine Example, Example Definitions, Example Definitions
32596@subsubsection Bit-Counting
32597
32598@noindent
32599@ignore
32600@starindex
32601@end ignore
32602@tindex bcount
32603Calc does not include a built-in function for counting the number of
32604``one'' bits in a binary integer. It's easy to invent one using @kbd{b u}
32605to convert the integer to a set, and @kbd{V #} to count the elements of
32606that set; let's write a function that counts the bits without having to
32607create an intermediate set.
32608
32609@smallexample
32610(defmath bcount ((natnum n))
32611 (interactive 1 "bcnt")
32612 (let ((count 0))
32613 (while (> n 0)
32614 (if (oddp n)
32615 (setq count (1+ count)))
32616 (setq n (lsh n -1)))
32617 count))
32618@end smallexample
32619
32620@noindent
32621When this is expanded by @code{defmath}, it will become the following
32622Emacs Lisp function:
32623
32624@smallexample
32625(defun calcFunc-bcount (n)
32626 (setq n (math-check-natnum n))
32627 (let ((count 0))
32628 (while (math-posp n)
32629 (if (math-oddp n)
32630 (setq count (math-add count 1)))
32631 (setq n (calcFunc-lsh n -1)))
32632 count))
32633@end smallexample
32634
32635If the input numbers are large, this function involves a fair amount
32636of arithmetic. A binary right shift is essentially a division by two;
32637recall that Calc stores integers in decimal form so bit shifts must
32638involve actual division.
32639
32640To gain a bit more efficiency, we could divide the integer into
32641@var{n}-bit chunks, each of which can be handled quickly because
32642they fit into Lisp integers. It turns out that Calc's arithmetic
32643routines are especially fast when dividing by an integer less than
326441000, so we can set @var{n = 9} bits and use repeated division by 512:
32645
32646@smallexample
32647(defmath bcount ((natnum n))
32648 (interactive 1 "bcnt")
32649 (let ((count 0))
32650 (while (not (fixnump n))
32651 (let ((qr (idivmod n 512)))
32652 (setq count (+ count (bcount-fixnum (cdr qr)))
32653 n (car qr))))
32654 (+ count (bcount-fixnum n))))
32655
32656(defun bcount-fixnum (n)
32657 (let ((count 0))
32658 (while (> n 0)
32659 (setq count (+ count (logand n 1))
32660 n (lsh n -1)))
32661 count))
32662@end smallexample
32663
32664@noindent
32665Note that the second function uses @code{defun}, not @code{defmath}.
32666Because this function deals only with native Lisp integers (``fixnums''),
32667it can use the actual Emacs @code{+} and related functions rather
32668than the slower but more general Calc equivalents which @code{defmath}
32669uses.
32670
32671The @code{idivmod} function does an integer division, returning both
32672the quotient and the remainder at once. Again, note that while it
32673might seem that @samp{(logand n 511)} and @samp{(lsh n -9)} are
32674more efficient ways to split off the bottom nine bits of @code{n},
32675actually they are less efficient because each operation is really
32676a division by 512 in disguise; @code{idivmod} allows us to do the
32677same thing with a single division by 512.
32678
32679@node Sine Example, , Bit Counting Example, Example Definitions
32680@subsubsection The Sine Function
32681
32682@noindent
32683@ignore
32684@starindex
32685@end ignore
32686@tindex mysin
32687A somewhat limited sine function could be defined as follows, using the
40ba43b4 32688well-known Taylor series expansion for
4009494e
GM
32689@texline @math{\sin x}:
32690@infoline @samp{sin(x)}:
32691
32692@smallexample
32693(defmath mysin ((float (anglep x)))
32694 (interactive 1 "mysn")
32695 (setq x (to-radians x)) ; Convert from current angular mode.
32696 (let ((sum x) ; Initial term of Taylor expansion of sin.
32697 newsum
32698 (nfact 1) ; "nfact" equals "n" factorial at all times.
32699 (xnegsqr :"-(x^2)")) ; "xnegsqr" equals -x^2.
32700 (for ((n 3 100 2)) ; Upper limit of 100 is a good precaution.
32701 (working "mysin" sum) ; Display "Working" message, if enabled.
32702 (setq nfact (* nfact (1- n) n)
32703 x (* x xnegsqr)
32704 newsum (+ sum (/ x nfact)))
32705 (if (~= newsum sum) ; If newsum is "nearly equal to" sum,
32706 (break)) ; then we are done.
32707 (setq sum newsum))
32708 sum))
32709@end smallexample
32710
32711The actual @code{sin} function in Calc works by first reducing the problem
32712to a sine or cosine of a nonnegative number less than @cpiover{4}. This
32713ensures that the Taylor series will converge quickly. Also, the calculation
32714is carried out with two extra digits of precision to guard against cumulative
32715round-off in @samp{sum}. Finally, complex arguments are allowed and handled
32716by a separate algorithm.
32717
32718@smallexample
32719(defmath mysin ((float (scalarp x)))
32720 (interactive 1 "mysn")
32721 (setq x (to-radians x)) ; Convert from current angular mode.
32722 (with-extra-prec 2 ; Evaluate with extra precision.
32723 (cond ((complexp x)
32724 (mysin-complex x))
32725 ((< x 0)
32726 (- (mysin-raw (- x))) ; Always call mysin-raw with x >= 0.
32727 (t (mysin-raw x))))))
32728
32729(defmath mysin-raw (x)
32730 (cond ((>= x 7)
32731 (mysin-raw (% x (two-pi)))) ; Now x < 7.
32732 ((> x (pi-over-2))
32733 (- (mysin-raw (- x (pi))))) ; Now -pi/2 <= x <= pi/2.
32734 ((> x (pi-over-4))
32735 (mycos-raw (- x (pi-over-2)))) ; Now -pi/2 <= x <= pi/4.
32736 ((< x (- (pi-over-4)))
32737 (- (mycos-raw (+ x (pi-over-2))))) ; Now -pi/4 <= x <= pi/4,
32738 (t (mysin-series x)))) ; so the series will be efficient.
32739@end smallexample
32740
32741@noindent
32742where @code{mysin-complex} is an appropriate function to handle complex
32743numbers, @code{mysin-series} is the routine to compute the sine Taylor
32744series as before, and @code{mycos-raw} is a function analogous to
32745@code{mysin-raw} for cosines.
32746
32747The strategy is to ensure that @expr{x} is nonnegative before calling
32748@code{mysin-raw}. This function then recursively reduces its argument
32749to a suitable range, namely, plus-or-minus @cpiover{4}. Note that each
32750test, and particularly the first comparison against 7, is designed so
32751that small roundoff errors cannot produce an infinite loop. (Suppose
32752we compared with @samp{(two-pi)} instead; if due to roundoff problems
32753the modulo operator ever returned @samp{(two-pi)} exactly, an infinite
32754recursion could result!) We use modulo only for arguments that will
32755clearly get reduced, knowing that the next rule will catch any reductions
32756that this rule misses.
32757
32758If a program is being written for general use, it is important to code
32759it carefully as shown in this second example. For quick-and-dirty programs,
32760when you know that your own use of the sine function will never encounter
32761a large argument, a simpler program like the first one shown is fine.
32762
32763@node Calling Calc from Your Programs, Internals, Example Definitions, Lisp Definitions
32764@subsection Calling Calc from Your Lisp Programs
32765
32766@noindent
32767A later section (@pxref{Internals}) gives a full description of
32768Calc's internal Lisp functions. It's not hard to call Calc from
32769inside your programs, but the number of these functions can be daunting.
32770So Calc provides one special ``programmer-friendly'' function called
32771@code{calc-eval} that can be made to do just about everything you
32772need. It's not as fast as the low-level Calc functions, but it's
32773much simpler to use!
32774
32775It may seem that @code{calc-eval} itself has a daunting number of
32776options, but they all stem from one simple operation.
32777
32778In its simplest manifestation, @samp{(calc-eval "1+2")} parses the
32779string @code{"1+2"} as if it were a Calc algebraic entry and returns
32780the result formatted as a string: @code{"3"}.
32781
32782Since @code{calc-eval} is on the list of recommended @code{autoload}
32783functions, you don't need to make any special preparations to load
32784Calc before calling @code{calc-eval} the first time. Calc will be
32785loaded and initialized for you.
32786
32787All the Calc modes that are currently in effect will be used when
32788evaluating the expression and formatting the result.
32789
32790@ifinfo
32791@example
32792
32793@end example
32794@end ifinfo
32795@subsubsection Additional Arguments to @code{calc-eval}
32796
32797@noindent
32798If the input string parses to a list of expressions, Calc returns
32799the results separated by @code{", "}. You can specify a different
32800separator by giving a second string argument to @code{calc-eval}:
32801@samp{(calc-eval "1+2,3+4" ";")} returns @code{"3;7"}.
32802
32803The ``separator'' can also be any of several Lisp symbols which
32804request other behaviors from @code{calc-eval}. These are discussed
32805one by one below.
32806
32807You can give additional arguments to be substituted for
32808@samp{$}, @samp{$$}, and so on in the main expression. For
32809example, @samp{(calc-eval "$/$$" nil "7" "1+1")} evaluates the
32810expression @code{"7/(1+1)"} to yield the result @code{"3.5"}
32811(assuming Fraction mode is not in effect). Note the @code{nil}
32812used as a placeholder for the item-separator argument.
32813
32814@ifinfo
32815@example
32816
32817@end example
32818@end ifinfo
32819@subsubsection Error Handling
32820
32821@noindent
32822If @code{calc-eval} encounters an error, it returns a list containing
32823the character position of the error, plus a suitable message as a
32824string. Note that @samp{1 / 0} is @emph{not} an error by Calc's
32825standards; it simply returns the string @code{"1 / 0"} which is the
32826division left in symbolic form. But @samp{(calc-eval "1/")} will
32827return the list @samp{(2 "Expected a number")}.
32828
32829If you bind the variable @code{calc-eval-error} to @code{t}
32830using a @code{let} form surrounding the call to @code{calc-eval},
32831errors instead call the Emacs @code{error} function which aborts
32832to the Emacs command loop with a beep and an error message.
32833
32834If you bind this variable to the symbol @code{string}, error messages
32835are returned as strings instead of lists. The character position is
32836ignored.
32837
32838As a courtesy to other Lisp code which may be using Calc, be sure
32839to bind @code{calc-eval-error} using @code{let} rather than changing
32840it permanently with @code{setq}.
32841
32842@ifinfo
32843@example
32844
32845@end example
32846@end ifinfo
32847@subsubsection Numbers Only
32848
32849@noindent
32850Sometimes it is preferable to treat @samp{1 / 0} as an error
32851rather than returning a symbolic result. If you pass the symbol
32852@code{num} as the second argument to @code{calc-eval}, results
32853that are not constants are treated as errors. The error message
32854reported is the first @code{calc-why} message if there is one,
32855or otherwise ``Number expected.''
32856
32857A result is ``constant'' if it is a number, vector, or other
32858object that does not include variables or function calls. If it
32859is a vector, the components must themselves be constants.
32860
32861@ifinfo
32862@example
32863
32864@end example
32865@end ifinfo
32866@subsubsection Default Modes
32867
32868@noindent
32869If the first argument to @code{calc-eval} is a list whose first
32870element is a formula string, then @code{calc-eval} sets all the
32871various Calc modes to their default values while the formula is
32872evaluated and formatted. For example, the precision is set to 12
32873digits, digit grouping is turned off, and the Normal language
32874mode is used.
32875
32876This same principle applies to the other options discussed below.
32877If the first argument would normally be @var{x}, then it can also
32878be the list @samp{(@var{x})} to use the default mode settings.
32879
32880If there are other elements in the list, they are taken as
32881variable-name/value pairs which override the default mode
32882settings. Look at the documentation at the front of the
32883@file{calc.el} file to find the names of the Lisp variables for
32884the various modes. The mode settings are restored to their
32885original values when @code{calc-eval} is done.
32886
32887For example, @samp{(calc-eval '("$+$$" calc-internal-prec 8) 'num a b)}
32888computes the sum of two numbers, requiring a numeric result, and
32889using default mode settings except that the precision is 8 instead
32890of the default of 12.
32891
32892It's usually best to use this form of @code{calc-eval} unless your
32893program actually considers the interaction with Calc's mode settings
32894to be a feature. This will avoid all sorts of potential ``gotchas'';
32895consider what happens with @samp{(calc-eval "sqrt(2)" 'num)}
32896when the user has left Calc in Symbolic mode or No-Simplify mode.
32897
32898As another example, @samp{(equal (calc-eval '("$<$$") nil a b) "1")}
32899checks if the number in string @expr{a} is less than the one in
32900string @expr{b}. Without using a list, the integer 1 might
32901come out in a variety of formats which would be hard to test for
32902conveniently: @code{"1"}, @code{"8#1"}, @code{"00001"}. (But
32903see ``Predicates'' mode, below.)
32904
32905@ifinfo
32906@example
32907
32908@end example
32909@end ifinfo
32910@subsubsection Raw Numbers
32911
32912@noindent
32913Normally all input and output for @code{calc-eval} is done with strings.
32914You can do arithmetic with, say, @samp{(calc-eval "$+$$" nil a b)}
32915in place of @samp{(+ a b)}, but this is very inefficient since the
32916numbers must be converted to and from string format as they are passed
32917from one @code{calc-eval} to the next.
32918
32919If the separator is the symbol @code{raw}, the result will be returned
32920as a raw Calc data structure rather than a string. You can read about
32921how these objects look in the following sections, but usually you can
32922treat them as ``black box'' objects with no important internal
32923structure.
32924
32925There is also a @code{rawnum} symbol, which is a combination of
32926@code{raw} (returning a raw Calc object) and @code{num} (signaling
32927an error if that object is not a constant).
32928
32929You can pass a raw Calc object to @code{calc-eval} in place of a
32930string, either as the formula itself or as one of the @samp{$}
32931arguments. Thus @samp{(calc-eval "$+$$" 'raw a b)} is an
32932addition function that operates on raw Calc objects. Of course
32933in this case it would be easier to call the low-level @code{math-add}
32934function in Calc, if you can remember its name.
32935
32936In particular, note that a plain Lisp integer is acceptable to Calc
32937as a raw object. (All Lisp integers are accepted on input, but
32938integers of more than six decimal digits are converted to ``big-integer''
32939form for output. @xref{Data Type Formats}.)
32940
32941When it comes time to display the object, just use @samp{(calc-eval a)}
32942to format it as a string.
32943
32944It is an error if the input expression evaluates to a list of
32945values. The separator symbol @code{list} is like @code{raw}
32946except that it returns a list of one or more raw Calc objects.
32947
32948Note that a Lisp string is not a valid Calc object, nor is a list
32949containing a string. Thus you can still safely distinguish all the
32950various kinds of error returns discussed above.
32951
32952@ifinfo
32953@example
32954
32955@end example
32956@end ifinfo
32957@subsubsection Predicates
32958
32959@noindent
32960If the separator symbol is @code{pred}, the result of the formula is
32961treated as a true/false value; @code{calc-eval} returns @code{t} or
32962@code{nil}, respectively. A value is considered ``true'' if it is a
32963non-zero number, or false if it is zero or if it is not a number.
32964
32965For example, @samp{(calc-eval "$<$$" 'pred a b)} tests whether
32966one value is less than another.
32967
32968As usual, it is also possible for @code{calc-eval} to return one of
32969the error indicators described above. Lisp will interpret such an
32970indicator as ``true'' if you don't check for it explicitly. If you
32971wish to have an error register as ``false'', use something like
32972@samp{(eq (calc-eval ...) t)}.
32973
32974@ifinfo
32975@example
32976
32977@end example
32978@end ifinfo
32979@subsubsection Variable Values
32980
32981@noindent
32982Variables in the formula passed to @code{calc-eval} are not normally
32983replaced by their values. If you wish this, you can use the
32984@code{evalv} function (@pxref{Algebraic Manipulation}). For example,
32985if 4 is stored in Calc variable @code{a} (i.e., in Lisp variable
32986@code{var-a}), then @samp{(calc-eval "a+pi")} will return the
32987formula @code{"a + pi"}, but @samp{(calc-eval "evalv(a+pi)")}
32988will return @code{"7.14159265359"}.
32989
32990To store in a Calc variable, just use @code{setq} to store in the
32991corresponding Lisp variable. (This is obtained by prepending
32992@samp{var-} to the Calc variable name.) Calc routines will
32993understand either string or raw form values stored in variables,
32994although raw data objects are much more efficient. For example,
32995to increment the Calc variable @code{a}:
32996
32997@example
32998(setq var-a (calc-eval "evalv(a+1)" 'raw))
32999@end example
33000
33001@ifinfo
33002@example
33003
33004@end example
33005@end ifinfo
33006@subsubsection Stack Access
33007
33008@noindent
33009If the separator symbol is @code{push}, the formula argument is
33010evaluated (with possible @samp{$} expansions, as usual). The
33011result is pushed onto the Calc stack. The return value is @code{nil}
33012(unless there is an error from evaluating the formula, in which
33013case the return value depends on @code{calc-eval-error} in the
33014usual way).
33015
33016If the separator symbol is @code{pop}, the first argument to
33017@code{calc-eval} must be an integer instead of a string. That
33018many values are popped from the stack and thrown away. A negative
33019argument deletes the entry at that stack level. The return value
33020is the number of elements remaining in the stack after popping;
33021@samp{(calc-eval 0 'pop)} is a good way to measure the size of
33022the stack.
33023
33024If the separator symbol is @code{top}, the first argument to
33025@code{calc-eval} must again be an integer. The value at that
33026stack level is formatted as a string and returned. Thus
33027@samp{(calc-eval 1 'top)} returns the top-of-stack value. If the
33028integer is out of range, @code{nil} is returned.
33029
33030The separator symbol @code{rawtop} is just like @code{top} except
33031that the stack entry is returned as a raw Calc object instead of
33032as a string.
33033
33034In all of these cases the first argument can be made a list in
33035order to force the default mode settings, as described above.
33036Thus @samp{(calc-eval '(2 calc-number-radix 16) 'top)} returns the
33037second-to-top stack entry, formatted as a string using the default
33038instead of current display modes, except that the radix is
33039hexadecimal instead of decimal.
33040
33041It is, of course, polite to put the Calc stack back the way you
33042found it when you are done, unless the user of your program is
33043actually expecting it to affect the stack.
33044
33045Note that you do not actually have to switch into the @samp{*Calculator*}
33046buffer in order to use @code{calc-eval}; it temporarily switches into
33047the stack buffer if necessary.
33048
33049@ifinfo
33050@example
33051
33052@end example
33053@end ifinfo
33054@subsubsection Keyboard Macros
33055
33056@noindent
33057If the separator symbol is @code{macro}, the first argument must be a
33058string of characters which Calc can execute as a sequence of keystrokes.
33059This switches into the Calc buffer for the duration of the macro.
33060For example, @samp{(calc-eval "vx5\rVR+" 'macro)} pushes the
33061vector @samp{[1,2,3,4,5]} on the stack and then replaces it
33062with the sum of those numbers. Note that @samp{\r} is the Lisp
33063notation for the carriage-return, @key{RET}, character.
33064
33065If your keyboard macro wishes to pop the stack, @samp{\C-d} is
33066safer than @samp{\177} (the @key{DEL} character) because some
33067installations may have switched the meanings of @key{DEL} and
33068@kbd{C-h}. Calc always interprets @kbd{C-d} as a synonym for
33069``pop-stack'' regardless of key mapping.
33070
33071If you provide a third argument to @code{calc-eval}, evaluation
33072of the keyboard macro will leave a record in the Trail using
33073that argument as a tag string. Normally the Trail is unaffected.
33074
33075The return value in this case is always @code{nil}.
33076
33077@ifinfo
33078@example
33079
33080@end example
33081@end ifinfo
33082@subsubsection Lisp Evaluation
33083
33084@noindent
33085Finally, if the separator symbol is @code{eval}, then the Lisp
33086@code{eval} function is called on the first argument, which must
33087be a Lisp expression rather than a Calc formula. Remember to
33088quote the expression so that it is not evaluated until inside
33089@code{calc-eval}.
33090
33091The difference from plain @code{eval} is that @code{calc-eval}
33092switches to the Calc buffer before evaluating the expression.
33093For example, @samp{(calc-eval '(setq calc-internal-prec 17) 'eval)}
33094will correctly affect the buffer-local Calc precision variable.
33095
33096An alternative would be @samp{(calc-eval '(calc-precision 17) 'eval)}.
33097This is evaluating a call to the function that is normally invoked
33098by the @kbd{p} key, giving it 17 as its ``numeric prefix argument.''
33099Note that this function will leave a message in the echo area as
33100a side effect. Also, all Calc functions switch to the Calc buffer
33101automatically if not invoked from there, so the above call is
33102also equivalent to @samp{(calc-precision 17)} by itself.
33103In all cases, Calc uses @code{save-excursion} to switch back to
33104your original buffer when it is done.
33105
33106As usual the first argument can be a list that begins with a Lisp
33107expression to use default instead of current mode settings.
33108
33109The result of @code{calc-eval} in this usage is just the result
33110returned by the evaluated Lisp expression.
33111
33112@ifinfo
33113@example
33114
33115@end example
33116@end ifinfo
33117@subsubsection Example
33118
33119@noindent
33120@findex convert-temp
33121Here is a sample Emacs command that uses @code{calc-eval}. Suppose
33122you have a document with lots of references to temperatures on the
33123Fahrenheit scale, say ``98.6 F'', and you wish to convert these
33124references to Centigrade. The following command does this conversion.
33125Place the Emacs cursor right after the letter ``F'' and invoke the
33126command to change ``98.6 F'' to ``37 C''. Or, if the temperature is
33127already in Centigrade form, the command changes it back to Fahrenheit.
33128
33129@example
33130(defun convert-temp ()
33131 (interactive)
33132 (save-excursion
33133 (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
33134 (let* ((top1 (match-beginning 1))
33135 (bot1 (match-end 1))
33136 (number (buffer-substring top1 bot1))
33137 (top2 (match-beginning 2))
33138 (bot2 (match-end 2))
33139 (type (buffer-substring top2 bot2)))
33140 (if (equal type "F")
33141 (setq type "C"
33142 number (calc-eval "($ - 32)*5/9" nil number))
33143 (setq type "F"
33144 number (calc-eval "$*9/5 + 32" nil number)))
33145 (goto-char top2)
33146 (delete-region top2 bot2)
33147 (insert-before-markers type)
33148 (goto-char top1)
33149 (delete-region top1 bot1)
33150 (if (string-match "\\.$" number) ; change "37." to "37"
33151 (setq number (substring number 0 -1)))
33152 (insert number))))
33153@end example
33154
33155Note the use of @code{insert-before-markers} when changing between
33156``F'' and ``C'', so that the character winds up before the cursor
33157instead of after it.
33158
33159@node Internals, , Calling Calc from Your Programs, Lisp Definitions
33160@subsection Calculator Internals
33161
33162@noindent
33163This section describes the Lisp functions defined by the Calculator that
33164may be of use to user-written Calculator programs (as described in the
33165rest of this chapter). These functions are shown by their names as they
33166conventionally appear in @code{defmath}. Their full Lisp names are
33167generally gotten by prepending @samp{calcFunc-} or @samp{math-} to their
33168apparent names. (Names that begin with @samp{calc-} are already in
33169their full Lisp form.) You can use the actual full names instead if you
33170prefer them, or if you are calling these functions from regular Lisp.
33171
33172The functions described here are scattered throughout the various
33173Calc component files. Note that @file{calc.el} includes @code{autoload}s
33174for only a few component files; when Calc wants to call an advanced
33175function it calls @samp{(calc-extensions)} first; this function
33176autoloads @file{calc-ext.el}, which in turn autoloads all the functions
33177in the remaining component files.
33178
33179Because @code{defmath} itself uses the extensions, user-written code
33180generally always executes with the extensions already loaded, so
33181normally you can use any Calc function and be confident that it will
33182be autoloaded for you when necessary. If you are doing something
33183special, check carefully to make sure each function you are using is
33184from @file{calc.el} or its components, and call @samp{(calc-extensions)}
33185before using any function based in @file{calc-ext.el} if you can't
33186prove this file will already be loaded.
33187
33188@menu
33189* Data Type Formats::
33190* Interactive Lisp Functions::
33191* Stack Lisp Functions::
33192* Predicates::
33193* Computational Lisp Functions::
33194* Vector Lisp Functions::
33195* Symbolic Lisp Functions::
33196* Formatting Lisp Functions::
33197* Hooks::
33198@end menu
33199
33200@node Data Type Formats, Interactive Lisp Functions, Internals, Internals
33201@subsubsection Data Type Formats
33202
33203@noindent
33204Integers are stored in either of two ways, depending on their magnitude.
33205Integers less than one million in absolute value are stored as standard
33206Lisp integers. This is the only storage format for Calc data objects
33207which is not a Lisp list.
33208
33209Large integers are stored as lists of the form @samp{(bigpos @var{d0}
33210@var{d1} @var{d2} @dots{})} for positive integers 1000000 or more, or
33211@samp{(bigneg @var{d0} @var{d1} @var{d2} @dots{})} for negative integers
33212@mathit{-1000000} or less. Each @var{d} is a base-1000 ``digit,'' a Lisp integer
33213from 0 to 999. The least significant digit is @var{d0}; the last digit,
33214@var{dn}, which is always nonzero, is the most significant digit. For
33215example, the integer @mathit{-12345678} is stored as @samp{(bigneg 678 345 12)}.
33216
33217The distinction between small and large integers is entirely hidden from
33218the user. In @code{defmath} definitions, the Lisp predicate @code{integerp}
33219returns true for either kind of integer, and in general both big and small
33220integers are accepted anywhere the word ``integer'' is used in this manual.
33221If the distinction must be made, native Lisp integers are called @dfn{fixnums}
33222and large integers are called @dfn{bignums}.
33223
33224Fractions are stored as a list of the form, @samp{(frac @var{n} @var{d})}
33225where @var{n} is an integer (big or small) numerator, @var{d} is an
33226integer denominator greater than one, and @var{n} and @var{d} are relatively
33227prime. Note that fractions where @var{d} is one are automatically converted
33228to plain integers by all math routines; fractions where @var{d} is negative
33229are normalized by negating the numerator and denominator.
33230
33231Floating-point numbers are stored in the form, @samp{(float @var{mant}
33232@var{exp})}, where @var{mant} (the ``mantissa'') is an integer less than
33233@samp{10^@var{p}} in absolute value (@var{p} represents the current
33234precision), and @var{exp} (the ``exponent'') is a fixnum. The value of
33235the float is @samp{@var{mant} * 10^@var{exp}}. For example, the number
33236@mathit{-3.14} is stored as @samp{(float -314 -2) = -314*10^-2}. Other constraints
33237are that the number 0.0 is always stored as @samp{(float 0 0)}, and,
33238except for the 0.0 case, the rightmost base-10 digit of @var{mant} is
33239always nonzero. (If the rightmost digit is zero, the number is
33240rearranged by dividing @var{mant} by ten and incrementing @var{exp}.)
33241
33242Rectangular complex numbers are stored in the form @samp{(cplx @var{re}
33243@var{im})}, where @var{re} and @var{im} are each real numbers, either
33244integers, fractions, or floats. The value is @samp{@var{re} + @var{im}i}.
33245The @var{im} part is nonzero; complex numbers with zero imaginary
33246components are converted to real numbers automatically.
33247
33248Polar complex numbers are stored in the form @samp{(polar @var{r}
33249@var{theta})}, where @var{r} is a positive real value and @var{theta}
33250is a real value or HMS form representing an angle. This angle is
33251usually normalized to lie in the interval @samp{(-180 ..@: 180)} degrees,
33252or @samp{(-pi ..@: pi)} radians, according to the current angular mode.
33253If the angle is 0 the value is converted to a real number automatically.
33254(If the angle is 180 degrees, the value is usually also converted to a
33255negative real number.)
33256
33257Hours-minutes-seconds forms are stored as @samp{(hms @var{h} @var{m}
33258@var{s})}, where @var{h} is an integer or an integer-valued float (i.e.,
33259a float with @samp{@var{exp} >= 0}), @var{m} is an integer or integer-valued
33260float in the range @w{@samp{[0 ..@: 60)}}, and @var{s} is any real number
33261in the range @samp{[0 ..@: 60)}.
33262
33263Date forms are stored as @samp{(date @var{n})}, where @var{n} is
33264a real number that counts days since midnight on the morning of
33265January 1, 1 AD. If @var{n} is an integer, this is a pure date
33266form. If @var{n} is a fraction or float, this is a date/time form.
33267
33268Modulo forms are stored as @samp{(mod @var{n} @var{m})}, where @var{m} is a
33269positive real number or HMS form, and @var{n} is a real number or HMS
33270form in the range @samp{[0 ..@: @var{m})}.
33271
33272Error forms are stored as @samp{(sdev @var{x} @var{sigma})}, where @var{x}
33273is the mean value and @var{sigma} is the standard deviation. Each
33274component is either a number, an HMS form, or a symbolic object
33275(a variable or function call). If @var{sigma} is zero, the value is
33276converted to a plain real number. If @var{sigma} is negative or
33277complex, it is automatically normalized to be a positive real.
33278
33279Interval forms are stored as @samp{(intv @var{mask} @var{lo} @var{hi})},
33280where @var{mask} is one of the integers 0, 1, 2, or 3, and @var{lo} and
33281@var{hi} are real numbers, HMS forms, or symbolic objects. The @var{mask}
33282is a binary integer where 1 represents the fact that the interval is
33283closed on the high end, and 2 represents the fact that it is closed on
33284the low end. (Thus 3 represents a fully closed interval.) The interval
33285@w{@samp{(intv 3 @var{x} @var{x})}} is converted to the plain number @var{x};
33286intervals @samp{(intv @var{mask} @var{x} @var{x})} for any other @var{mask}
33287represent empty intervals. If @var{hi} is less than @var{lo}, the interval
33288is converted to a standard empty interval by replacing @var{hi} with @var{lo}.
33289
33290Vectors are stored as @samp{(vec @var{v1} @var{v2} @dots{})}, where @var{v1}
33291is the first element of the vector, @var{v2} is the second, and so on.
33292An empty vector is stored as @samp{(vec)}. A matrix is simply a vector
33293where all @var{v}'s are themselves vectors of equal lengths. Note that
33294Calc vectors are unrelated to the Emacs Lisp ``vector'' type, which is
33295generally unused by Calc data structures.
33296
33297Variables are stored as @samp{(var @var{name} @var{sym})}, where
33298@var{name} is a Lisp symbol whose print name is used as the visible name
33299of the variable, and @var{sym} is a Lisp symbol in which the variable's
33300value is actually stored. Thus, @samp{(var pi var-pi)} represents the
33301special constant @samp{pi}. Almost always, the form is @samp{(var
33302@var{v} var-@var{v})}. If the variable name was entered with @code{#}
33303signs (which are converted to hyphens internally), the form is
33304@samp{(var @var{u} @var{v})}, where @var{u} is a symbol whose name
33305contains @code{#} characters, and @var{v} is a symbol that contains
33306@code{-} characters instead. The value of a variable is the Calc
33307object stored in its @var{sym} symbol's value cell. If the symbol's
33308value cell is void or if it contains @code{nil}, the variable has no
33309value. Special constants have the form @samp{(special-const
33310@var{value})} stored in their value cell, where @var{value} is a formula
33311which is evaluated when the constant's value is requested. Variables
33312which represent units are not stored in any special way; they are units
33313only because their names appear in the units table. If the value
33314cell contains a string, it is parsed to get the variable's value when
33315the variable is used.
33316
33317A Lisp list with any other symbol as the first element is a function call.
33318The symbols @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^},
33319and @code{|} represent special binary operators; these lists are always
33320of the form @samp{(@var{op} @var{lhs} @var{rhs})} where @var{lhs} is the
33321sub-formula on the lefthand side and @var{rhs} is the sub-formula on the
33322right. The symbol @code{neg} represents unary negation; this list is always
33323of the form @samp{(neg @var{arg})}. Any other symbol @var{func} represents a
33324function that would be displayed in function-call notation; the symbol
33325@var{func} is in general always of the form @samp{calcFunc-@var{name}}.
33326The function cell of the symbol @var{func} should contain a Lisp function
33327for evaluating a call to @var{func}. This function is passed the remaining
33328elements of the list (themselves already evaluated) as arguments; such
33329functions should return @code{nil} or call @code{reject-arg} to signify
33330that they should be left in symbolic form, or they should return a Calc
33331object which represents their value, or a list of such objects if they
33332wish to return multiple values. (The latter case is allowed only for
33333functions which are the outer-level call in an expression whose value is
33334about to be pushed on the stack; this feature is considered obsolete
33335and is not used by any built-in Calc functions.)
33336
33337@node Interactive Lisp Functions, Stack Lisp Functions, Data Type Formats, Internals
33338@subsubsection Interactive Functions
33339
33340@noindent
33341The functions described here are used in implementing interactive Calc
33342commands. Note that this list is not exhaustive! If there is an
33343existing command that behaves similarly to the one you want to define,
33344you may find helpful tricks by checking the source code for that command.
33345
33346@defun calc-set-command-flag flag
33347Set the command flag @var{flag}. This is generally a Lisp symbol, but
33348may in fact be anything. The effect is to add @var{flag} to the list
33349stored in the variable @code{calc-command-flags}, unless it is already
33350there. @xref{Defining Simple Commands}.
33351@end defun
33352
33353@defun calc-clear-command-flag flag
33354If @var{flag} appears among the list of currently-set command flags,
33355remove it from that list.
33356@end defun
33357
33358@defun calc-record-undo rec
33359Add the ``undo record'' @var{rec} to the list of steps to take if the
33360current operation should need to be undone. Stack push and pop functions
33361automatically call @code{calc-record-undo}, so the kinds of undo records
33362you might need to create take the form @samp{(set @var{sym} @var{value})},
33363which says that the Lisp variable @var{sym} was changed and had previously
33364contained @var{value}; @samp{(store @var{var} @var{value})} which says that
33365the Calc variable @var{var} (a string which is the name of the symbol that
33366contains the variable's value) was stored and its previous value was
33367@var{value} (either a Calc data object, or @code{nil} if the variable was
33368previously void); or @samp{(eval @var{undo} @var{redo} @var{args} @dots{})},
33369which means that to undo requires calling the function @samp{(@var{undo}
33370@var{args} @dots{})} and, if the undo is later redone, calling
33371@samp{(@var{redo} @var{args} @dots{})}.
33372@end defun
33373
33374@defun calc-record-why msg args
33375Record the error or warning message @var{msg}, which is normally a string.
33376This message will be replayed if the user types @kbd{w} (@code{calc-why});
33377if the message string begins with a @samp{*}, it is considered important
33378enough to display even if the user doesn't type @kbd{w}. If one or more
33379@var{args} are present, the displayed message will be of the form,
33380@samp{@var{msg}: @var{arg1}, @var{arg2}, @dots{}}, where the arguments are
33381formatted on the assumption that they are either strings or Calc objects of
33382some sort. If @var{msg} is a symbol, it is the name of a Calc predicate
33383(such as @code{integerp} or @code{numvecp}) which the arguments did not
33384satisfy; it is expanded to a suitable string such as ``Expected an
33385integer.'' The @code{reject-arg} function calls @code{calc-record-why}
33386automatically; @pxref{Predicates}.
33387@end defun
33388
33389@defun calc-is-inverse
33390This predicate returns true if the current command is inverse,
33391i.e., if the Inverse (@kbd{I} key) flag was set.
33392@end defun
33393
33394@defun calc-is-hyperbolic
33395This predicate is the analogous function for the @kbd{H} key.
33396@end defun
33397
33398@node Stack Lisp Functions, Predicates, Interactive Lisp Functions, Internals
33399@subsubsection Stack-Oriented Functions
33400
33401@noindent
33402The functions described here perform various operations on the Calc
33403stack and trail. They are to be used in interactive Calc commands.
33404
33405@defun calc-push-list vals n
33406Push the Calc objects in list @var{vals} onto the stack at stack level
33407@var{n}. If @var{n} is omitted it defaults to 1, so that the elements
33408are pushed at the top of the stack. If @var{n} is greater than 1, the
33409elements will be inserted into the stack so that the last element will
33410end up at level @var{n}, the next-to-last at level @var{n}+1, etc.
33411The elements of @var{vals} are assumed to be valid Calc objects, and
33412are not evaluated, rounded, or renormalized in any way. If @var{vals}
33413is an empty list, nothing happens.
33414
33415The stack elements are pushed without any sub-formula selections.
33416You can give an optional third argument to this function, which must
33417be a list the same size as @var{vals} of selections. Each selection
33418must be @code{eq} to some sub-formula of the corresponding formula
33419in @var{vals}, or @code{nil} if that formula should have no selection.
33420@end defun
33421
33422@defun calc-top-list n m
33423Return a list of the @var{n} objects starting at level @var{m} of the
33424stack. If @var{m} is omitted it defaults to 1, so that the elements are
33425taken from the top of the stack. If @var{n} is omitted, it also
33426defaults to 1, so that the top stack element (in the form of a
33427one-element list) is returned. If @var{m} is greater than 1, the
33428@var{m}th stack element will be at the end of the list, the @var{m}+1st
33429element will be next-to-last, etc. If @var{n} or @var{m} are out of
33430range, the command is aborted with a suitable error message. If @var{n}
33431is zero, the function returns an empty list. The stack elements are not
33432evaluated, rounded, or renormalized.
33433
33434If any stack elements contain selections, and selections have not
33435been disabled by the @kbd{j e} (@code{calc-enable-selections}) command,
33436this function returns the selected portions rather than the entire
33437stack elements. It can be given a third ``selection-mode'' argument
33438which selects other behaviors. If it is the symbol @code{t}, then
33439a selection in any of the requested stack elements produces an
33440``invalid operation on selections'' error. If it is the symbol @code{full},
33441the whole stack entry is always returned regardless of selections.
33442If it is the symbol @code{sel}, the selected portion is always returned,
33443or @code{nil} if there is no selection. (This mode ignores the @kbd{j e}
33444command.) If the symbol is @code{entry}, the complete stack entry in
33445list form is returned; the first element of this list will be the whole
33446formula, and the third element will be the selection (or @code{nil}).
33447@end defun
33448
33449@defun calc-pop-stack n m
33450Remove the specified elements from the stack. The parameters @var{n}
33451and @var{m} are defined the same as for @code{calc-top-list}. The return
33452value of @code{calc-pop-stack} is uninteresting.
33453
33454If there are any selected sub-formulas among the popped elements, and
33455@kbd{j e} has not been used to disable selections, this produces an
33456error without changing the stack. If you supply an optional third
33457argument of @code{t}, the stack elements are popped even if they
33458contain selections.
33459@end defun
33460
33461@defun calc-record-list vals tag
33462This function records one or more results in the trail. The @var{vals}
33463are a list of strings or Calc objects. The @var{tag} is the four-character
33464tag string to identify the values. If @var{tag} is omitted, a blank tag
33465will be used.
33466@end defun
33467
33468@defun calc-normalize n
33469This function takes a Calc object and ``normalizes'' it. At the very
33470least this involves re-rounding floating-point values according to the
33471current precision and other similar jobs. Also, unless the user has
33472selected No-Simplify mode (@pxref{Simplification Modes}), this involves
33473actually evaluating a formula object by executing the function calls
33474it contains, and possibly also doing algebraic simplification, etc.
33475@end defun
33476
33477@defun calc-top-list-n n m
33478This function is identical to @code{calc-top-list}, except that it calls
33479@code{calc-normalize} on the values that it takes from the stack. They
33480are also passed through @code{check-complete}, so that incomplete
33481objects will be rejected with an error message. All computational
33482commands should use this in preference to @code{calc-top-list}; the only
33483standard Calc commands that operate on the stack without normalizing
33484are stack management commands like @code{calc-enter} and @code{calc-roll-up}.
33485This function accepts the same optional selection-mode argument as
33486@code{calc-top-list}.
33487@end defun
33488
33489@defun calc-top-n m
33490This function is a convenient form of @code{calc-top-list-n} in which only
33491a single element of the stack is taken and returned, rather than a list
33492of elements. This also accepts an optional selection-mode argument.
33493@end defun
33494
33495@defun calc-enter-result n tag vals
33496This function is a convenient interface to most of the above functions.
33497The @var{vals} argument should be either a single Calc object, or a list
33498of Calc objects; the object or objects are normalized, and the top @var{n}
33499stack entries are replaced by the normalized objects. If @var{tag} is
33500non-@code{nil}, the normalized objects are also recorded in the trail.
33501A typical stack-based computational command would take the form,
33502
33503@smallexample
33504(calc-enter-result @var{n} @var{tag} (cons 'calcFunc-@var{func}
33505 (calc-top-list-n @var{n})))
33506@end smallexample
33507
33508If any of the @var{n} stack elements replaced contain sub-formula
33509selections, and selections have not been disabled by @kbd{j e},
33510this function takes one of two courses of action. If @var{n} is
33511equal to the number of elements in @var{vals}, then each element of
33512@var{vals} is spliced into the corresponding selection; this is what
33513happens when you use the @key{TAB} key, or when you use a unary
33514arithmetic operation like @code{sqrt}. If @var{vals} has only one
33515element but @var{n} is greater than one, there must be only one
33516selection among the top @var{n} stack elements; the element from
33517@var{vals} is spliced into that selection. This is what happens when
33518you use a binary arithmetic operation like @kbd{+}. Any other
33519combination of @var{n} and @var{vals} is an error when selections
33520are present.
33521@end defun
33522
33523@defun calc-unary-op tag func arg
33524This function implements a unary operator that allows a numeric prefix
33525argument to apply the operator over many stack entries. If the prefix
33526argument @var{arg} is @code{nil}, this uses @code{calc-enter-result}
33527as outlined above. Otherwise, it maps the function over several stack
33528elements; @pxref{Prefix Arguments}. For example,
33529
33530@smallexample
33531(defun calc-zeta (arg)
33532 (interactive "P")
33533 (calc-unary-op "zeta" 'calcFunc-zeta arg))
33534@end smallexample
33535@end defun
33536
33537@defun calc-binary-op tag func arg ident unary
33538This function implements a binary operator, analogously to
33539@code{calc-unary-op}. The optional @var{ident} and @var{unary}
33540arguments specify the behavior when the prefix argument is zero or
33541one, respectively. If the prefix is zero, the value @var{ident}
33542is pushed onto the stack, if specified, otherwise an error message
33543is displayed. If the prefix is one, the unary function @var{unary}
33544is applied to the top stack element, or, if @var{unary} is not
33545specified, nothing happens. When the argument is two or more,
33546the binary function @var{func} is reduced across the top @var{arg}
33547stack elements; when the argument is negative, the function is
33548mapped between the next-to-top @mathit{-@var{arg}} stack elements and the
33549top element.
33550@end defun
33551
33552@defun calc-stack-size
33553Return the number of elements on the stack as an integer. This count
33554does not include elements that have been temporarily hidden by stack
33555truncation; @pxref{Truncating the Stack}.
33556@end defun
33557
33558@defun calc-cursor-stack-index n
33559Move the point to the @var{n}th stack entry. If @var{n} is zero, this
33560will be the @samp{.} line. If @var{n} is from 1 to the current stack size,
33561this will be the beginning of the first line of that stack entry's display.
33562If line numbers are enabled, this will move to the first character of the
33563line number, not the stack entry itself.
33564@end defun
33565
33566@defun calc-substack-height n
33567Return the number of lines between the beginning of the @var{n}th stack
33568entry and the bottom of the buffer. If @var{n} is zero, this
33569will be one (assuming no stack truncation). If all stack entries are
33570one line long (i.e., no matrices are displayed), the return value will
33571be equal @var{n}+1 as long as @var{n} is in range. (Note that in Big
33572mode, the return value includes the blank lines that separate stack
33573entries.)
33574@end defun
33575
33576@defun calc-refresh
33577Erase the @code{*Calculator*} buffer and reformat its contents from memory.
33578This must be called after changing any parameter, such as the current
33579display radix, which might change the appearance of existing stack
33580entries. (During a keyboard macro invoked by the @kbd{X} key, refreshing
33581is suppressed, but a flag is set so that the entire stack will be refreshed
33582rather than just the top few elements when the macro finishes.)
33583@end defun
33584
33585@node Predicates, Computational Lisp Functions, Stack Lisp Functions, Internals
33586@subsubsection Predicates
33587
33588@noindent
33589The functions described here are predicates, that is, they return a
33590true/false value where @code{nil} means false and anything else means
33591true. These predicates are expanded by @code{defmath}, for example,
33592from @code{zerop} to @code{math-zerop}. In many cases they correspond
33593to native Lisp functions by the same name, but are extended to cover
33594the full range of Calc data types.
33595
33596@defun zerop x
33597Returns true if @var{x} is numerically zero, in any of the Calc data
33598types. (Note that for some types, such as error forms and intervals,
33599it never makes sense to return true.) In @code{defmath}, the expression
33600@samp{(= x 0)} will automatically be converted to @samp{(math-zerop x)},
33601and @samp{(/= x 0)} will be converted to @samp{(not (math-zerop x))}.
33602@end defun
33603
33604@defun negp x
33605Returns true if @var{x} is negative. This accepts negative real numbers
33606of various types, negative HMS and date forms, and intervals in which
33607all included values are negative. In @code{defmath}, the expression
33608@samp{(< x 0)} will automatically be converted to @samp{(math-negp x)},
33609and @samp{(>= x 0)} will be converted to @samp{(not (math-negp x))}.
33610@end defun
33611
33612@defun posp x
33613Returns true if @var{x} is positive (and non-zero). For complex
33614numbers, none of these three predicates will return true.
33615@end defun
33616
33617@defun looks-negp x
33618Returns true if @var{x} is ``negative-looking.'' This returns true if
33619@var{x} is a negative number, or a formula with a leading minus sign
33620such as @samp{-a/b}. In other words, this is an object which can be
33621made simpler by calling @code{(- @var{x})}.
33622@end defun
33623
33624@defun integerp x
33625Returns true if @var{x} is an integer of any size.
33626@end defun
33627
33628@defun fixnump x
33629Returns true if @var{x} is a native Lisp integer.
33630@end defun
33631
33632@defun natnump x
33633Returns true if @var{x} is a nonnegative integer of any size.
33634@end defun
33635
33636@defun fixnatnump x
33637Returns true if @var{x} is a nonnegative Lisp integer.
33638@end defun
33639
33640@defun num-integerp x
33641Returns true if @var{x} is numerically an integer, i.e., either a
33642true integer or a float with no significant digits to the right of
33643the decimal point.
33644@end defun
33645
33646@defun messy-integerp x
33647Returns true if @var{x} is numerically, but not literally, an integer.
33648A value is @code{num-integerp} if it is @code{integerp} or
33649@code{messy-integerp} (but it is never both at once).
33650@end defun
33651
33652@defun num-natnump x
33653Returns true if @var{x} is numerically a nonnegative integer.
33654@end defun
33655
33656@defun evenp x
33657Returns true if @var{x} is an even integer.
33658@end defun
33659
33660@defun looks-evenp x
33661Returns true if @var{x} is an even integer, or a formula with a leading
33662multiplicative coefficient which is an even integer.
33663@end defun
33664
33665@defun oddp x
33666Returns true if @var{x} is an odd integer.
33667@end defun
33668
33669@defun ratp x
33670Returns true if @var{x} is a rational number, i.e., an integer or a
33671fraction.
33672@end defun
33673
33674@defun realp x
33675Returns true if @var{x} is a real number, i.e., an integer, fraction,
33676or floating-point number.
33677@end defun
33678
33679@defun anglep x
33680Returns true if @var{x} is a real number or HMS form.
33681@end defun
33682
33683@defun floatp x
33684Returns true if @var{x} is a float, or a complex number, error form,
33685interval, date form, or modulo form in which at least one component
33686is a float.
33687@end defun
33688
33689@defun complexp x
33690Returns true if @var{x} is a rectangular or polar complex number
33691(but not a real number).
33692@end defun
33693
33694@defun rect-complexp x
33695Returns true if @var{x} is a rectangular complex number.
33696@end defun
33697
33698@defun polar-complexp x
33699Returns true if @var{x} is a polar complex number.
33700@end defun
33701
33702@defun numberp x
33703Returns true if @var{x} is a real number or a complex number.
33704@end defun
33705
33706@defun scalarp x
33707Returns true if @var{x} is a real or complex number or an HMS form.
33708@end defun
33709
33710@defun vectorp x
33711Returns true if @var{x} is a vector (this simply checks if its argument
33712is a list whose first element is the symbol @code{vec}).
33713@end defun
33714
33715@defun numvecp x
33716Returns true if @var{x} is a number or vector.
33717@end defun
33718
33719@defun matrixp x
33720Returns true if @var{x} is a matrix, i.e., a vector of one or more vectors,
33721all of the same size.
33722@end defun
33723
33724@defun square-matrixp x
33725Returns true if @var{x} is a square matrix.
33726@end defun
33727
33728@defun objectp x
33729Returns true if @var{x} is any numeric Calc object, including real and
33730complex numbers, HMS forms, date forms, error forms, intervals, and
33731modulo forms. (Note that error forms and intervals may include formulas
33732as their components; see @code{constp} below.)
33733@end defun
33734
33735@defun objvecp x
33736Returns true if @var{x} is an object or a vector. This also accepts
33737incomplete objects, but it rejects variables and formulas (except as
33738mentioned above for @code{objectp}).
33739@end defun
33740
33741@defun primp x
33742Returns true if @var{x} is a ``primitive'' or ``atomic'' Calc object,
33743i.e., one whose components cannot be regarded as sub-formulas. This
33744includes variables, and all @code{objectp} types except error forms
33745and intervals.
33746@end defun
33747
33748@defun constp x
33749Returns true if @var{x} is constant, i.e., a real or complex number,
33750HMS form, date form, or error form, interval, or vector all of whose
33751components are @code{constp}.
33752@end defun
33753
33754@defun lessp x y
33755Returns true if @var{x} is numerically less than @var{y}. Returns false
33756if @var{x} is greater than or equal to @var{y}, or if the order is
33757undefined or cannot be determined. Generally speaking, this works
33758by checking whether @samp{@var{x} - @var{y}} is @code{negp}. In
33759@code{defmath}, the expression @samp{(< x y)} will automatically be
33760converted to @samp{(lessp x y)}; expressions involving @code{>}, @code{<=},
33761and @code{>=} are similarly converted in terms of @code{lessp}.
33762@end defun
33763
33764@defun beforep x y
33765Returns true if @var{x} comes before @var{y} in a canonical ordering
33766of Calc objects. If @var{x} and @var{y} are both real numbers, this
33767will be the same as @code{lessp}. But whereas @code{lessp} considers
33768other types of objects to be unordered, @code{beforep} puts any two
33769objects into a definite, consistent order. The @code{beforep}
33770function is used by the @kbd{V S} vector-sorting command, and also
8e7046c3
JB
33771by Calc's algebraic simplifications to put the terms of a product into
33772canonical order: This allows @samp{x y + y x} to be simplified easily to
33773@samp{2 x y}.
4009494e
GM
33774@end defun
33775
33776@defun equal x y
33777This is the standard Lisp @code{equal} predicate; it returns true if
33778@var{x} and @var{y} are structurally identical. This is the usual way
33779to compare numbers for equality, but note that @code{equal} will treat
337800 and 0.0 as different.
33781@end defun
33782
33783@defun math-equal x y
33784Returns true if @var{x} and @var{y} are numerically equal, either because
33785they are @code{equal}, or because their difference is @code{zerop}. In
33786@code{defmath}, the expression @samp{(= x y)} will automatically be
33787converted to @samp{(math-equal x y)}.
33788@end defun
33789
33790@defun equal-int x n
33791Returns true if @var{x} and @var{n} are numerically equal, where @var{n}
33792is a fixnum which is not a multiple of 10. This will automatically be
33793used by @code{defmath} in place of the more general @code{math-equal}
33794whenever possible.
33795@end defun
33796
33797@defun nearly-equal x y
33798Returns true if @var{x} and @var{y}, as floating-point numbers, are
33799equal except possibly in the last decimal place. For example,
33800314.159 and 314.166 are considered nearly equal if the current
33801precision is 6 (since they differ by 7 units), but not if the current
33802precision is 7 (since they differ by 70 units). Most functions which
33803use series expansions use @code{with-extra-prec} to evaluate the
33804series with 2 extra digits of precision, then use @code{nearly-equal}
33805to decide when the series has converged; this guards against cumulative
33806error in the series evaluation without doing extra work which would be
33807lost when the result is rounded back down to the current precision.
33808In @code{defmath}, this can be written @samp{(~= @var{x} @var{y})}.
33809The @var{x} and @var{y} can be numbers of any kind, including complex.
33810@end defun
33811
33812@defun nearly-zerop x y
33813Returns true if @var{x} is nearly zero, compared to @var{y}. This
33814checks whether @var{x} plus @var{y} would by be @code{nearly-equal}
33815to @var{y} itself, to within the current precision, in other words,
33816if adding @var{x} to @var{y} would have a negligible effect on @var{y}
33817due to roundoff error. @var{X} may be a real or complex number, but
33818@var{y} must be real.
33819@end defun
33820
33821@defun is-true x
33822Return true if the formula @var{x} represents a true value in
33823Calc, not Lisp, terms. It tests if @var{x} is a non-zero number
33824or a provably non-zero formula.
33825@end defun
33826
33827@defun reject-arg val pred
33828Abort the current function evaluation due to unacceptable argument values.
33829This calls @samp{(calc-record-why @var{pred} @var{val})}, then signals a
33830Lisp error which @code{normalize} will trap. The net effect is that the
33831function call which led here will be left in symbolic form.
33832@end defun
33833
33834@defun inexact-value
33835If Symbolic mode is enabled, this will signal an error that causes
33836@code{normalize} to leave the formula in symbolic form, with the message
33837``Inexact result.'' (This function has no effect when not in Symbolic mode.)
33838Note that if your function calls @samp{(sin 5)} in Symbolic mode, the
33839@code{sin} function will call @code{inexact-value}, which will cause your
33840function to be left unsimplified. You may instead wish to call
33841@samp{(normalize (list 'calcFunc-sin 5))}, which in Symbolic mode will
33842return the formula @samp{sin(5)} to your function.
33843@end defun
33844
33845@defun overflow
33846This signals an error that will be reported as a floating-point overflow.
33847@end defun
33848
33849@defun underflow
33850This signals a floating-point underflow.
33851@end defun
33852
33853@node Computational Lisp Functions, Vector Lisp Functions, Predicates, Internals
33854@subsubsection Computational Functions
33855
33856@noindent
33857The functions described here do the actual computational work of the
33858Calculator. In addition to these, note that any function described in
33859the main body of this manual may be called from Lisp; for example, if
33860the documentation refers to the @code{calc-sqrt} [@code{sqrt}] command,
33861this means @code{calc-sqrt} is an interactive stack-based square-root
33862command and @code{sqrt} (which @code{defmath} expands to @code{calcFunc-sqrt})
33863is the actual Lisp function for taking square roots.
33864
33865The functions @code{math-add}, @code{math-sub}, @code{math-mul},
33866@code{math-div}, @code{math-mod}, and @code{math-neg} are not included
33867in this list, since @code{defmath} allows you to write native Lisp
33868@code{+}, @code{-}, @code{*}, @code{/}, @code{%}, and unary @code{-},
33869respectively, instead.
33870
33871@defun normalize val
33872(Full form: @code{math-normalize}.)
33873Reduce the value @var{val} to standard form. For example, if @var{val}
33874is a fixnum, it will be converted to a bignum if it is too large, and
33875if @var{val} is a bignum it will be normalized by clipping off trailing
33876(i.e., most-significant) zero digits and converting to a fixnum if it is
33877small. All the various data types are similarly converted to their standard
33878forms. Variables are left alone, but function calls are actually evaluated
33879in formulas. For example, normalizing @samp{(+ 2 (calcFunc-abs -4))} will
33880return 6.
33881
33882If a function call fails, because the function is void or has the wrong
33883number of parameters, or because it returns @code{nil} or calls
33884@code{reject-arg} or @code{inexact-result}, @code{normalize} returns
33885the formula still in symbolic form.
33886
33887If the current simplification mode is ``none'' or ``numeric arguments
33888only,'' @code{normalize} will act appropriately. However, the more
33889powerful simplification modes (like Algebraic Simplification) are
33890not handled by @code{normalize}. They are handled by @code{calc-normalize},
33891which calls @code{normalize} and possibly some other routines, such
33892as @code{simplify} or @code{simplify-units}. Programs generally will
33893never call @code{calc-normalize} except when popping or pushing values
33894on the stack.
33895@end defun
33896
33897@defun evaluate-expr expr
33898Replace all variables in @var{expr} that have values with their values,
33899then use @code{normalize} to simplify the result. This is what happens
33900when you press the @kbd{=} key interactively.
33901@end defun
33902
33903@defmac with-extra-prec n body
33904Evaluate the Lisp forms in @var{body} with precision increased by @var{n}
33905digits. This is a macro which expands to
33906
33907@smallexample
33908(math-normalize
33909 (let ((calc-internal-prec (+ calc-internal-prec @var{n})))
33910 @var{body}))
33911@end smallexample
33912
33913The surrounding call to @code{math-normalize} causes a floating-point
33914result to be rounded down to the original precision afterwards. This
33915is important because some arithmetic operations assume a number's
33916mantissa contains no more digits than the current precision allows.
33917@end defmac
33918
33919@defun make-frac n d
33920Build a fraction @samp{@var{n}:@var{d}}. This is equivalent to calling
33921@samp{(normalize (list 'frac @var{n} @var{d}))}, but more efficient.
33922@end defun
33923
33924@defun make-float mant exp
33925Build a floating-point value out of @var{mant} and @var{exp}, both
33926of which are arbitrary integers. This function will return a
33927properly normalized float value, or signal an overflow or underflow
33928if @var{exp} is out of range.
33929@end defun
33930
33931@defun make-sdev x sigma
33932Build an error form out of @var{x} and the absolute value of @var{sigma}.
33933If @var{sigma} is zero, the result is the number @var{x} directly.
33934If @var{sigma} is negative or complex, its absolute value is used.
33935If @var{x} or @var{sigma} is not a valid type of object for use in
33936error forms, this calls @code{reject-arg}.
33937@end defun
33938
33939@defun make-intv mask lo hi
33940Build an interval form out of @var{mask} (which is assumed to be an
33941integer from 0 to 3), and the limits @var{lo} and @var{hi}. If
33942@var{lo} is greater than @var{hi}, an empty interval form is returned.
33943This calls @code{reject-arg} if @var{lo} or @var{hi} is unsuitable.
33944@end defun
33945
33946@defun sort-intv mask lo hi
33947Build an interval form, similar to @code{make-intv}, except that if
33948@var{lo} is less than @var{hi} they are simply exchanged, and the
33949bits of @var{mask} are swapped accordingly.
33950@end defun
33951
33952@defun make-mod n m
33953Build a modulo form out of @var{n} and the modulus @var{m}. Since modulo
33954forms do not allow formulas as their components, if @var{n} or @var{m}
33955is not a real number or HMS form the result will be a formula which
33956is a call to @code{makemod}, the algebraic version of this function.
33957@end defun
33958
33959@defun float x
33960Convert @var{x} to floating-point form. Integers and fractions are
33961converted to numerically equivalent floats; components of complex
33962numbers, vectors, HMS forms, date forms, error forms, intervals, and
33963modulo forms are recursively floated. If the argument is a variable
33964or formula, this calls @code{reject-arg}.
33965@end defun
33966
33967@defun compare x y
33968Compare the numbers @var{x} and @var{y}, and return @mathit{-1} if
33969@samp{(lessp @var{x} @var{y})}, 1 if @samp{(lessp @var{y} @var{x})},
339700 if @samp{(math-equal @var{x} @var{y})}, or 2 if the order is
33971undefined or cannot be determined.
33972@end defun
33973
33974@defun numdigs n
33975Return the number of digits of integer @var{n}, effectively
33976@samp{ceil(log10(@var{n}))}, but much more efficient. Zero is
33977considered to have zero digits.
33978@end defun
33979
33980@defun scale-int x n
33981Shift integer @var{x} left @var{n} decimal digits, or right @mathit{-@var{n}}
33982digits with truncation toward zero.
33983@end defun
33984
33985@defun scale-rounding x n
33986Like @code{scale-int}, except that a right shift rounds to the nearest
33987integer rather than truncating.
33988@end defun
33989
33990@defun fixnum n
33991Return the integer @var{n} as a fixnum, i.e., a native Lisp integer.
33992If @var{n} is outside the permissible range for Lisp integers (usually
3399324 binary bits) the result is undefined.
33994@end defun
33995
33996@defun sqr x
33997Compute the square of @var{x}; short for @samp{(* @var{x} @var{x})}.
33998@end defun
33999
34000@defun quotient x y
34001Divide integer @var{x} by integer @var{y}; return an integer quotient
34002and discard the remainder. If @var{x} or @var{y} is negative, the
34003direction of rounding is undefined.
34004@end defun
34005
34006@defun idiv x y
34007Perform an integer division; if @var{x} and @var{y} are both nonnegative
34008integers, this uses the @code{quotient} function, otherwise it computes
34009@samp{floor(@var{x}/@var{y})}. Thus the result is well-defined but
34010slower than for @code{quotient}.
34011@end defun
34012
34013@defun imod x y
34014Divide integer @var{x} by integer @var{y}; return the integer remainder
34015and discard the quotient. Like @code{quotient}, this works only for
34016integer arguments and is not well-defined for negative arguments.
34017For a more well-defined result, use @samp{(% @var{x} @var{y})}.
34018@end defun
34019
34020@defun idivmod x y
34021Divide integer @var{x} by integer @var{y}; return a cons cell whose
34022@code{car} is @samp{(quotient @var{x} @var{y})} and whose @code{cdr}
34023is @samp{(imod @var{x} @var{y})}.
34024@end defun
34025
34026@defun pow x y
34027Compute @var{x} to the power @var{y}. In @code{defmath} code, this can
34028also be written @samp{(^ @var{x} @var{y})} or
34029@w{@samp{(expt @var{x} @var{y})}}.
34030@end defun
34031
34032@defun abs-approx x
34033Compute a fast approximation to the absolute value of @var{x}. For
34034example, for a rectangular complex number the result is the sum of
34035the absolute values of the components.
34036@end defun
34037
34038@findex e
34039@findex gamma-const
34040@findex ln-2
34041@findex ln-10
34042@findex phi
34043@findex pi-over-2
34044@findex pi-over-4
34045@findex pi-over-180
34046@findex sqrt-two-pi
34047@findex sqrt-e
34048@findex two-pi
34049@defun pi
34050The function @samp{(pi)} computes @samp{pi} to the current precision.
34051Other related constant-generating functions are @code{two-pi},
34052@code{pi-over-2}, @code{pi-over-4}, @code{pi-over-180}, @code{sqrt-two-pi},
34053@code{e}, @code{sqrt-e}, @code{ln-2}, @code{ln-10}, @code{phi} and
34054@code{gamma-const}. Each function returns a floating-point value in the
34055current precision, and each uses caching so that all calls after the
34056first are essentially free.
34057@end defun
34058
34059@defmac math-defcache @var{func} @var{initial} @var{form}
34060This macro, usually used as a top-level call like @code{defun} or
34061@code{defvar}, defines a new cached constant analogous to @code{pi}, etc.
34062It defines a function @code{func} which returns the requested value;
34063if @var{initial} is non-@code{nil} it must be a @samp{(float @dots{})}
34064form which serves as an initial value for the cache. If @var{func}
34065is called when the cache is empty or does not have enough digits to
34066satisfy the current precision, the Lisp expression @var{form} is evaluated
34067with the current precision increased by four, and the result minus its
34068two least significant digits is stored in the cache. For example,
34069calling @samp{(pi)} with a precision of 30 computes @samp{pi} to 34
34070digits, rounds it down to 32 digits for future use, then rounds it
34071again to 30 digits for use in the present request.
34072@end defmac
34073
34074@findex half-circle
34075@findex quarter-circle
34076@defun full-circle symb
34077If the current angular mode is Degrees or HMS, this function returns the
34078integer 360. In Radians mode, this function returns either the
34079corresponding value in radians to the current precision, or the formula
34080@samp{2*pi}, depending on the Symbolic mode. There are also similar
34081function @code{half-circle} and @code{quarter-circle}.
34082@end defun
34083
34084@defun power-of-2 n
34085Compute two to the integer power @var{n}, as a (potentially very large)
34086integer. Powers of two are cached, so only the first call for a
34087particular @var{n} is expensive.
34088@end defun
34089
34090@defun integer-log2 n
34091Compute the base-2 logarithm of @var{n}, which must be an integer which
34092is a power of two. If @var{n} is not a power of two, this function will
34093return @code{nil}.
34094@end defun
34095
34096@defun div-mod a b m
34097Divide @var{a} by @var{b}, modulo @var{m}. This returns @code{nil} if
34098there is no solution, or if any of the arguments are not integers.
34099@end defun
34100
34101@defun pow-mod a b m
34102Compute @var{a} to the power @var{b}, modulo @var{m}. If @var{a},
34103@var{b}, and @var{m} are integers, this uses an especially efficient
34104algorithm. Otherwise, it simply computes @samp{(% (^ a b) m)}.
34105@end defun
34106
34107@defun isqrt n
34108Compute the integer square root of @var{n}. This is the square root
34109of @var{n} rounded down toward zero, i.e., @samp{floor(sqrt(@var{n}))}.
34110If @var{n} is itself an integer, the computation is especially efficient.
34111@end defun
34112
34113@defun to-hms a ang
34114Convert the argument @var{a} into an HMS form. If @var{ang} is specified,
34115it is the angular mode in which to interpret @var{a}, either @code{deg}
34116or @code{rad}. Otherwise, the current angular mode is used. If @var{a}
34117is already an HMS form it is returned as-is.
34118@end defun
34119
34120@defun from-hms a ang
34121Convert the HMS form @var{a} into a real number. If @var{ang} is specified,
34122it is the angular mode in which to express the result, otherwise the
34123current angular mode is used. If @var{a} is already a real number, it
34124is returned as-is.
34125@end defun
34126
34127@defun to-radians a
34128Convert the number or HMS form @var{a} to radians from the current
34129angular mode.
34130@end defun
34131
34132@defun from-radians a
34133Convert the number @var{a} from radians to the current angular mode.
34134If @var{a} is a formula, this returns the formula @samp{deg(@var{a})}.
34135@end defun
34136
34137@defun to-radians-2 a
34138Like @code{to-radians}, except that in Symbolic mode a degrees to
34139radians conversion yields a formula like @samp{@var{a}*pi/180}.
34140@end defun
34141
34142@defun from-radians-2 a
34143Like @code{from-radians}, except that in Symbolic mode a radians to
34144degrees conversion yields a formula like @samp{@var{a}*180/pi}.
34145@end defun
34146
34147@defun random-digit
34148Produce a random base-1000 digit in the range 0 to 999.
34149@end defun
34150
34151@defun random-digits n
34152Produce a random @var{n}-digit integer; this will be an integer
34153in the interval @samp{[0, 10^@var{n})}.
34154@end defun
34155
34156@defun random-float
34157Produce a random float in the interval @samp{[0, 1)}.
34158@end defun
34159
34160@defun prime-test n iters
34161Determine whether the integer @var{n} is prime. Return a list which has
34162one of these forms: @samp{(nil @var{f})} means the number is non-prime
34163because it was found to be divisible by @var{f}; @samp{(nil)} means it
34164was found to be non-prime by table look-up (so no factors are known);
34165@samp{(nil unknown)} means it is definitely non-prime but no factors
34166are known because @var{n} was large enough that Fermat's probabilistic
34167test had to be used; @samp{(t)} means the number is definitely prime;
34168and @samp{(maybe @var{i} @var{p})} means that Fermat's test, after @var{i}
34169iterations, is @var{p} percent sure that the number is prime. The
34170@var{iters} parameter is the number of Fermat iterations to use, in the
34171case that this is necessary. If @code{prime-test} returns ``maybe,''
34172you can call it again with the same @var{n} to get a greater certainty;
34173@code{prime-test} remembers where it left off.
34174@end defun
34175
34176@defun to-simple-fraction f
34177If @var{f} is a floating-point number which can be represented exactly
34178as a small rational number. return that number, else return @var{f}.
34179For example, 0.75 would be converted to 3:4. This function is very
34180fast.
34181@end defun
34182
34183@defun to-fraction f tol
34184Find a rational approximation to floating-point number @var{f} to within
34185a specified tolerance @var{tol}; this corresponds to the algebraic
34186function @code{frac}, and can be rather slow.
34187@end defun
34188
34189@defun quarter-integer n
34190If @var{n} is an integer or integer-valued float, this function
34191returns zero. If @var{n} is a half-integer (i.e., an integer plus
34192@mathit{1:2} or 0.5), it returns 2. If @var{n} is a quarter-integer,
34193it returns 1 or 3. If @var{n} is anything else, this function
34194returns @code{nil}.
34195@end defun
34196
34197@node Vector Lisp Functions, Symbolic Lisp Functions, Computational Lisp Functions, Internals
34198@subsubsection Vector Functions
34199
34200@noindent
34201The functions described here perform various operations on vectors and
34202matrices.
34203
34204@defun math-concat x y
34205Do a vector concatenation; this operation is written @samp{@var{x} | @var{y}}
34206in a symbolic formula. @xref{Building Vectors}.
34207@end defun
34208
34209@defun vec-length v
34210Return the length of vector @var{v}. If @var{v} is not a vector, the
34211result is zero. If @var{v} is a matrix, this returns the number of
34212rows in the matrix.
34213@end defun
34214
34215@defun mat-dimens m
34216Determine the dimensions of vector or matrix @var{m}. If @var{m} is not
34217a vector, the result is an empty list. If @var{m} is a plain vector
34218but not a matrix, the result is a one-element list containing the length
34219of the vector. If @var{m} is a matrix with @var{r} rows and @var{c} columns,
34220the result is the list @samp{(@var{r} @var{c})}. Higher-order tensors
34221produce lists of more than two dimensions. Note that the object
34222@samp{[[1, 2, 3], [4, 5]]} is a vector of vectors not all the same size,
34223and is treated by this and other Calc routines as a plain vector of two
34224elements.
34225@end defun
34226
34227@defun dimension-error
34228Abort the current function with a message of ``Dimension error.''
34229The Calculator will leave the function being evaluated in symbolic
34230form; this is really just a special case of @code{reject-arg}.
34231@end defun
34232
34233@defun build-vector args
34234Return a Calc vector with @var{args} as elements.
34235For example, @samp{(build-vector 1 2 3)} returns the Calc vector
34236@samp{[1, 2, 3]}, stored internally as the list @samp{(vec 1 2 3)}.
34237@end defun
34238
34239@defun make-vec obj dims
34240Return a Calc vector or matrix all of whose elements are equal to
34241@var{obj}. For example, @samp{(make-vec 27 3 4)} returns a 3x4 matrix
34242filled with 27's.
34243@end defun
34244
34245@defun row-matrix v
34246If @var{v} is a plain vector, convert it into a row matrix, i.e.,
34247a matrix whose single row is @var{v}. If @var{v} is already a matrix,
34248leave it alone.
34249@end defun
34250
34251@defun col-matrix v
34252If @var{v} is a plain vector, convert it into a column matrix, i.e., a
34253matrix with each element of @var{v} as a separate row. If @var{v} is
34254already a matrix, leave it alone.
34255@end defun
34256
34257@defun map-vec f v
34258Map the Lisp function @var{f} over the Calc vector @var{v}. For example,
34259@samp{(map-vec 'math-floor v)} returns a vector of the floored components
34260of vector @var{v}.
34261@end defun
34262
34263@defun map-vec-2 f a b
34264Map the Lisp function @var{f} over the two vectors @var{a} and @var{b}.
34265If @var{a} and @var{b} are vectors of equal length, the result is a
34266vector of the results of calling @samp{(@var{f} @var{ai} @var{bi})}
34267for each pair of elements @var{ai} and @var{bi}. If either @var{a} or
34268@var{b} is a scalar, it is matched with each value of the other vector.
34269For example, @samp{(map-vec-2 'math-add v 1)} returns the vector @var{v}
34270with each element increased by one. Note that using @samp{'+} would not
34271work here, since @code{defmath} does not expand function names everywhere,
34272just where they are in the function position of a Lisp expression.
34273@end defun
34274
34275@defun reduce-vec f v
34276Reduce the function @var{f} over the vector @var{v}. For example, if
34277@var{v} is @samp{[10, 20, 30, 40]}, this calls @samp{(f (f (f 10 20) 30) 40)}.
34278If @var{v} is a matrix, this reduces over the rows of @var{v}.
34279@end defun
34280
34281@defun reduce-cols f m
34282Reduce the function @var{f} over the columns of matrix @var{m}. For
34283example, if @var{m} is @samp{[[1, 2], [3, 4], [5, 6]]}, the result
34284is a vector of the two elements @samp{(f (f 1 3) 5)} and @samp{(f (f 2 4) 6)}.
34285@end defun
34286
34287@defun mat-row m n
34288Return the @var{n}th row of matrix @var{m}. This is equivalent to
34289@samp{(elt m n)}. For a slower but safer version, use @code{mrow}.
34290(@xref{Extracting Elements}.)
34291@end defun
34292
34293@defun mat-col m n
34294Return the @var{n}th column of matrix @var{m}, in the form of a vector.
34295The arguments are not checked for correctness.
34296@end defun
34297
34298@defun mat-less-row m n
34299Return a copy of matrix @var{m} with its @var{n}th row deleted. The
34300number @var{n} must be in range from 1 to the number of rows in @var{m}.
34301@end defun
34302
34303@defun mat-less-col m n
34304Return a copy of matrix @var{m} with its @var{n}th column deleted.
34305@end defun
34306
34307@defun transpose m
34308Return the transpose of matrix @var{m}.
34309@end defun
34310
34311@defun flatten-vector v
34312Flatten nested vector @var{v} into a vector of scalars. For example,
34313if @var{v} is @samp{[[1, 2, 3], [4, 5]]} the result is @samp{[1, 2, 3, 4, 5]}.
34314@end defun
34315
34316@defun copy-matrix m
34317If @var{m} is a matrix, return a copy of @var{m}. This maps
34318@code{copy-sequence} over the rows of @var{m}; in Lisp terms, each
34319element of the result matrix will be @code{eq} to the corresponding
34320element of @var{m}, but none of the @code{cons} cells that make up
34321the structure of the matrix will be @code{eq}. If @var{m} is a plain
34322vector, this is the same as @code{copy-sequence}.
34323@end defun
34324
34325@defun swap-rows m r1 r2
34326Exchange rows @var{r1} and @var{r2} of matrix @var{m} in-place. In
34327other words, unlike most of the other functions described here, this
34328function changes @var{m} itself rather than building up a new result
34329matrix. The return value is @var{m}, i.e., @samp{(eq (swap-rows m 1 2) m)}
34330is true, with the side effect of exchanging the first two rows of
34331@var{m}.
34332@end defun
34333
34334@node Symbolic Lisp Functions, Formatting Lisp Functions, Vector Lisp Functions, Internals
34335@subsubsection Symbolic Functions
34336
34337@noindent
34338The functions described here operate on symbolic formulas in the
34339Calculator.
34340
34341@defun calc-prepare-selection num
34342Prepare a stack entry for selection operations. If @var{num} is
34343omitted, the stack entry containing the cursor is used; otherwise,
34344it is the number of the stack entry to use. This function stores
34345useful information about the current stack entry into a set of
34346variables. @code{calc-selection-cache-num} contains the number of
34347the stack entry involved (equal to @var{num} if you specified it);
34348@code{calc-selection-cache-entry} contains the stack entry as a
34349list (such as @code{calc-top-list} would return with @code{entry}
34350as the selection mode); and @code{calc-selection-cache-comp} contains
34351a special ``tagged'' composition (@pxref{Formatting Lisp Functions})
34352which allows Calc to relate cursor positions in the buffer with
34353their corresponding sub-formulas.
34354
34355A slight complication arises in the selection mechanism because
34356formulas may contain small integers. For example, in the vector
34357@samp{[1, 2, 1]} the first and last elements are @code{eq} to each
34358other; selections are recorded as the actual Lisp object that
34359appears somewhere in the tree of the whole formula, but storing
34360@code{1} would falsely select both @code{1}'s in the vector. So
34361@code{calc-prepare-selection} also checks the stack entry and
34362replaces any plain integers with ``complex number'' lists of the form
34363@samp{(cplx @var{n} 0)}. This list will be displayed the same as a
34364plain @var{n} and the change will be completely invisible to the
34365user, but it will guarantee that no two sub-formulas of the stack
34366entry will be @code{eq} to each other. Next time the stack entry
34367is involved in a computation, @code{calc-normalize} will replace
34368these lists with plain numbers again, again invisibly to the user.
34369@end defun
34370
34371@defun calc-encase-atoms x
34372This modifies the formula @var{x} to ensure that each part of the
34373formula is a unique atom, using the @samp{(cplx @var{n} 0)} trick
34374described above. This function may use @code{setcar} to modify
34375the formula in-place.
34376@end defun
34377
34378@defun calc-find-selected-part
34379Find the smallest sub-formula of the current formula that contains
34380the cursor. This assumes @code{calc-prepare-selection} has been
34381called already. If the cursor is not actually on any part of the
34382formula, this returns @code{nil}.
34383@end defun
34384
34385@defun calc-change-current-selection selection
34386Change the currently prepared stack element's selection to
34387@var{selection}, which should be @code{eq} to some sub-formula
34388of the stack element, or @code{nil} to unselect the formula.
34389The stack element's appearance in the Calc buffer is adjusted
34390to reflect the new selection.
34391@end defun
34392
34393@defun calc-find-nth-part expr n
34394Return the @var{n}th sub-formula of @var{expr}. This function is used
34395by the selection commands, and (unless @kbd{j b} has been used) treats
34396sums and products as flat many-element formulas. Thus if @var{expr}
34397is @samp{((a + b) - c) + d}, calling @code{calc-find-nth-part} with
34398@var{n} equal to four will return @samp{d}.
34399@end defun
34400
34401@defun calc-find-parent-formula expr part
34402Return the sub-formula of @var{expr} which immediately contains
34403@var{part}. If @var{expr} is @samp{a*b + (c+1)*d} and @var{part}
34404is @code{eq} to the @samp{c+1} term of @var{expr}, then this function
34405will return @samp{(c+1)*d}. If @var{part} turns out not to be a
34406sub-formula of @var{expr}, the function returns @code{nil}. If
34407@var{part} is @code{eq} to @var{expr}, the function returns @code{t}.
34408This function does not take associativity into account.
34409@end defun
34410
34411@defun calc-find-assoc-parent-formula expr part
34412This is the same as @code{calc-find-parent-formula}, except that
34413(unless @kbd{j b} has been used) it continues widening the selection
34414to contain a complete level of the formula. Given @samp{a} from
34415@samp{((a + b) - c) + d}, @code{calc-find-parent-formula} will
34416return @samp{a + b} but @code{calc-find-assoc-parent-formula} will
34417return the whole expression.
34418@end defun
34419
34420@defun calc-grow-assoc-formula expr part
34421This expands sub-formula @var{part} of @var{expr} to encompass a
34422complete level of the formula. If @var{part} and its immediate
34423parent are not compatible associative operators, or if @kbd{j b}
34424has been used, this simply returns @var{part}.
34425@end defun
34426
34427@defun calc-find-sub-formula expr part
34428This finds the immediate sub-formula of @var{expr} which contains
34429@var{part}. It returns an index @var{n} such that
34430@samp{(calc-find-nth-part @var{expr} @var{n})} would return @var{part}.
34431If @var{part} is not a sub-formula of @var{expr}, it returns @code{nil}.
34432If @var{part} is @code{eq} to @var{expr}, it returns @code{t}. This
34433function does not take associativity into account.
34434@end defun
34435
34436@defun calc-replace-sub-formula expr old new
34437This function returns a copy of formula @var{expr}, with the
34438sub-formula that is @code{eq} to @var{old} replaced by @var{new}.
34439@end defun
34440
34441@defun simplify expr
8e7046c3
JB
34442Simplify the expression @var{expr} by applying Calc's algebraic
34443simplifications. This always returns a copy of the expression; the
34444structure @var{expr} points to remains unchanged in memory.
4009494e
GM
34445
34446More precisely, here is what @code{simplify} does: The expression is
34447first normalized and evaluated by calling @code{normalize}. If any
34448@code{AlgSimpRules} have been defined, they are then applied. Then
34449the expression is traversed in a depth-first, bottom-up fashion; at
34450each level, any simplifications that can be made are made until no
34451further changes are possible. Once the entire formula has been
34452traversed in this way, it is compared with the original formula (from
34453before the call to @code{normalize}) and, if it has changed,
34454the entire procedure is repeated (starting with @code{normalize})
34455until no further changes occur. Usually only two iterations are
34456needed:@: one to simplify the formula, and another to verify that no
34457further simplifications were possible.
34458@end defun
34459
34460@defun simplify-extended expr
34461Simplify the expression @var{expr}, with additional rules enabled that
34462help do a more thorough job, while not being entirely ``safe'' in all
34463circumstances. (For example, this mode will simplify @samp{sqrt(x^2)}
34464to @samp{x}, which is only valid when @var{x} is positive.) This is
34465implemented by temporarily binding the variable @code{math-living-dangerously}
34466to @code{t} (using a @code{let} form) and calling @code{simplify}.
34467Dangerous simplification rules are written to check this variable
34468before taking any action.
34469@end defun
34470
34471@defun simplify-units expr
34472Simplify the expression @var{expr}, treating variable names as units
34473whenever possible. This works by binding the variable
34474@code{math-simplifying-units} to @code{t} while calling @code{simplify}.
34475@end defun
34476
34477@defmac math-defsimplify funcs body
34478Register a new simplification rule; this is normally called as a top-level
34479form, like @code{defun} or @code{defmath}. If @var{funcs} is a symbol
34480(like @code{+} or @code{calcFunc-sqrt}), this simplification rule is
34481applied to the formulas which are calls to the specified function. Or,
34482@var{funcs} can be a list of such symbols; the rule applies to all
34483functions on the list. The @var{body} is written like the body of a
34484function with a single argument called @code{expr}. The body will be
34485executed with @code{expr} bound to a formula which is a call to one of
34486the functions @var{funcs}. If the function body returns @code{nil}, or
34487if it returns a result @code{equal} to the original @code{expr}, it is
34488ignored and Calc goes on to try the next simplification rule that applies.
34489If the function body returns something different, that new formula is
34490substituted for @var{expr} in the original formula.
34491
34492At each point in the formula, rules are tried in the order of the
34493original calls to @code{math-defsimplify}; the search stops after the
34494first rule that makes a change. Thus later rules for that same
34495function will not have a chance to trigger until the next iteration
34496of the main @code{simplify} loop.
34497
34498Note that, since @code{defmath} is not being used here, @var{body} must
34499be written in true Lisp code without the conveniences that @code{defmath}
34500provides. If you prefer, you can have @var{body} simply call another
34501function (defined with @code{defmath}) which does the real work.
34502
34503The arguments of a function call will already have been simplified
34504before any rules for the call itself are invoked. Since a new argument
34505list is consed up when this happens, this means that the rule's body is
34506allowed to rearrange the function's arguments destructively if that is
34507convenient. Here is a typical example of a simplification rule:
34508
34509@smallexample
34510(math-defsimplify calcFunc-arcsinh
34511 (or (and (math-looks-negp (nth 1 expr))
34512 (math-neg (list 'calcFunc-arcsinh
34513 (math-neg (nth 1 expr)))))
34514 (and (eq (car-safe (nth 1 expr)) 'calcFunc-sinh)
34515 (or math-living-dangerously
34516 (math-known-realp (nth 1 (nth 1 expr))))
34517 (nth 1 (nth 1 expr)))))
34518@end smallexample
34519
34520This is really a pair of rules written with one @code{math-defsimplify}
34521for convenience; the first replaces @samp{arcsinh(-x)} with
34522@samp{-arcsinh(x)}, and the second, which is safe only for real @samp{x},
34523replaces @samp{arcsinh(sinh(x))} with @samp{x}.
34524@end defmac
34525
34526@defun common-constant-factor expr
34527Check @var{expr} to see if it is a sum of terms all multiplied by the
34528same rational value. If so, return this value. If not, return @code{nil}.
34529For example, if called on @samp{6x + 9y + 12z}, it would return 3, since
345303 is a common factor of all the terms.
34531@end defun
34532
34533@defun cancel-common-factor expr factor
34534Assuming @var{expr} is a sum with @var{factor} as a common factor,
34535divide each term of the sum by @var{factor}. This is done by
34536destructively modifying parts of @var{expr}, on the assumption that
34537it is being used by a simplification rule (where such things are
34538allowed; see above). For example, consider this built-in rule for
34539square roots:
34540
34541@smallexample
34542(math-defsimplify calcFunc-sqrt
34543 (let ((fac (math-common-constant-factor (nth 1 expr))))
34544 (and fac (not (eq fac 1))
34545 (math-mul (math-normalize (list 'calcFunc-sqrt fac))
34546 (math-normalize
34547 (list 'calcFunc-sqrt
34548 (math-cancel-common-factor
34549 (nth 1 expr) fac)))))))
34550@end smallexample
34551@end defun
34552
34553@defun frac-gcd a b
34554Compute a ``rational GCD'' of @var{a} and @var{b}, which must both be
34555rational numbers. This is the fraction composed of the GCD of the
34556numerators of @var{a} and @var{b}, over the GCD of the denominators.
34557It is used by @code{common-constant-factor}. Note that the standard
34558@code{gcd} function uses the LCM to combine the denominators.
34559@end defun
34560
34561@defun map-tree func expr many
34562Try applying Lisp function @var{func} to various sub-expressions of
34563@var{expr}. Initially, call @var{func} with @var{expr} itself as an
34564argument. If this returns an expression which is not @code{equal} to
34565@var{expr}, apply @var{func} again until eventually it does return
34566@var{expr} with no changes. Then, if @var{expr} is a function call,
34567recursively apply @var{func} to each of the arguments. This keeps going
34568until no changes occur anywhere in the expression; this final expression
34569is returned by @code{map-tree}. Note that, unlike simplification rules,
34570@var{func} functions may @emph{not} make destructive changes to
34571@var{expr}. If a third argument @var{many} is provided, it is an
34572integer which says how many times @var{func} may be applied; the
34573default, as described above, is infinitely many times.
34574@end defun
34575
34576@defun compile-rewrites rules
34577Compile the rewrite rule set specified by @var{rules}, which should
34578be a formula that is either a vector or a variable name. If the latter,
34579the compiled rules are saved so that later @code{compile-rules} calls
34580for that same variable can return immediately. If there are problems
34581with the rules, this function calls @code{error} with a suitable
34582message.
34583@end defun
34584
34585@defun apply-rewrites expr crules heads
34586Apply the compiled rewrite rule set @var{crules} to the expression
34587@var{expr}. This will make only one rewrite and only checks at the
34588top level of the expression. The result @code{nil} if no rules
34589matched, or if the only rules that matched did not actually change
34590the expression. The @var{heads} argument is optional; if is given,
34591it should be a list of all function names that (may) appear in
34592@var{expr}. The rewrite compiler tags each rule with the
34593rarest-looking function name in the rule; if you specify @var{heads},
34594@code{apply-rewrites} can use this information to narrow its search
34595down to just a few rules in the rule set.
34596@end defun
34597
34598@defun rewrite-heads expr
34599Compute a @var{heads} list for @var{expr} suitable for use with
34600@code{apply-rewrites}, as discussed above.
34601@end defun
34602
34603@defun rewrite expr rules many
34604This is an all-in-one rewrite function. It compiles the rule set
34605specified by @var{rules}, then uses @code{map-tree} to apply the
34606rules throughout @var{expr} up to @var{many} (default infinity)
34607times.
34608@end defun
34609
34610@defun match-patterns pat vec not-flag
34611Given a Calc vector @var{vec} and an uncompiled pattern set or
34612pattern set variable @var{pat}, this function returns a new vector
34613of all elements of @var{vec} which do (or don't, if @var{not-flag} is
34614non-@code{nil}) match any of the patterns in @var{pat}.
34615@end defun
34616
34617@defun deriv expr var value symb
34618Compute the derivative of @var{expr} with respect to variable @var{var}
34619(which may actually be any sub-expression). If @var{value} is specified,
34620the derivative is evaluated at the value of @var{var}; otherwise, the
34621derivative is left in terms of @var{var}. If the expression contains
34622functions for which no derivative formula is known, new derivative
34623functions are invented by adding primes to the names; @pxref{Calculus}.
ee7683eb 34624However, if @var{symb} is non-@code{nil}, the presence of nondifferentiable
4009494e
GM
34625functions in @var{expr} instead cancels the whole differentiation, and
34626@code{deriv} returns @code{nil} instead.
34627
34628Derivatives of an @var{n}-argument function can be defined by
34629adding a @code{math-derivative-@var{n}} property to the property list
34630of the symbol for the function's derivative, which will be the
34631function name followed by an apostrophe. The value of the property
34632should be a Lisp function; it is called with the same arguments as the
34633original function call that is being differentiated. It should return
34634a formula for the derivative. For example, the derivative of @code{ln}
34635is defined by
34636
34637@smallexample
34638(put 'calcFunc-ln\' 'math-derivative-1
34639 (function (lambda (u) (math-div 1 u))))
34640@end smallexample
34641
34642The two-argument @code{log} function has two derivatives,
34643@smallexample
34644(put 'calcFunc-log\' 'math-derivative-2 ; d(log(x,b)) / dx
34645 (function (lambda (x b) ... )))
34646(put 'calcFunc-log\'2 'math-derivative-2 ; d(log(x,b)) / db
34647 (function (lambda (x b) ... )))
34648@end smallexample
34649@end defun
34650
34651@defun tderiv expr var value symb
34652Compute the total derivative of @var{expr}. This is the same as
34653@code{deriv}, except that variables other than @var{var} are not
34654assumed to be constant with respect to @var{var}.
34655@end defun
34656
34657@defun integ expr var low high
34658Compute the integral of @var{expr} with respect to @var{var}.
34659@xref{Calculus}, for further details.
34660@end defun
34661
34662@defmac math-defintegral funcs body
34663Define a rule for integrating a function or functions of one argument;
34664this macro is very similar in format to @code{math-defsimplify}.
34665The main difference is that here @var{body} is the body of a function
34666with a single argument @code{u} which is bound to the argument to the
34667function being integrated, not the function call itself. Also, the
34668variable of integration is available as @code{math-integ-var}. If
34669evaluation of the integral requires doing further integrals, the body
34670should call @samp{(math-integral @var{x})} to find the integral of
34671@var{x} with respect to @code{math-integ-var}; this function returns
34672@code{nil} if the integral could not be done. Some examples:
34673
34674@smallexample
34675(math-defintegral calcFunc-conj
34676 (let ((int (math-integral u)))
34677 (and int
34678 (list 'calcFunc-conj int))))
34679
34680(math-defintegral calcFunc-cos
34681 (and (equal u math-integ-var)
34682 (math-from-radians-2 (list 'calcFunc-sin u))))
34683@end smallexample
34684
34685In the @code{cos} example, we define only the integral of @samp{cos(x) dx},
34686relying on the general integration-by-substitution facility to handle
34687cosines of more complicated arguments. An integration rule should return
34688@code{nil} if it can't do the integral; if several rules are defined for
34689the same function, they are tried in order until one returns a non-@code{nil}
34690result.
34691@end defmac
34692
34693@defmac math-defintegral-2 funcs body
34694Define a rule for integrating a function or functions of two arguments.
34695This is exactly analogous to @code{math-defintegral}, except that @var{body}
34696is written as the body of a function with two arguments, @var{u} and
34697@var{v}.
34698@end defmac
34699
34700@defun solve-for lhs rhs var full
34701Attempt to solve the equation @samp{@var{lhs} = @var{rhs}} by isolating
34702the variable @var{var} on the lefthand side; return the resulting righthand
34703side, or @code{nil} if the equation cannot be solved. The variable
34704@var{var} must appear at least once in @var{lhs} or @var{rhs}. Note that
34705the return value is a formula which does not contain @var{var}; this is
34706different from the user-level @code{solve} and @code{finv} functions,
34707which return a rearranged equation or a functional inverse, respectively.
34708If @var{full} is non-@code{nil}, a full solution including dummy signs
34709and dummy integers will be produced. User-defined inverses are provided
34710as properties in a manner similar to derivatives:
34711
34712@smallexample
34713(put 'calcFunc-ln 'math-inverse
34714 (function (lambda (x) (list 'calcFunc-exp x))))
34715@end smallexample
34716
34717This function can call @samp{(math-solve-get-sign @var{x})} to create
34718a new arbitrary sign variable, returning @var{x} times that sign, and
34719@samp{(math-solve-get-int @var{x})} to create a new arbitrary integer
34720variable multiplied by @var{x}. These functions simply return @var{x}
34721if the caller requested a non-``full'' solution.
34722@end defun
34723
34724@defun solve-eqn expr var full
34725This version of @code{solve-for} takes an expression which will
34726typically be an equation or inequality. (If it is not, it will be
34727interpreted as the equation @samp{@var{expr} = 0}.) It returns an
34728equation or inequality, or @code{nil} if no solution could be found.
34729@end defun
34730
34731@defun solve-system exprs vars full
34732This function solves a system of equations. Generally, @var{exprs}
34733and @var{vars} will be vectors of equal length.
34734@xref{Solving Systems of Equations}, for other options.
34735@end defun
34736
34737@defun expr-contains expr var
34738Returns a non-@code{nil} value if @var{var} occurs as a subexpression
34739of @var{expr}.
34740
34741This function might seem at first to be identical to
34742@code{calc-find-sub-formula}. The key difference is that
34743@code{expr-contains} uses @code{equal} to test for matches, whereas
34744@code{calc-find-sub-formula} uses @code{eq}. In the formula
34745@samp{f(a, a)}, the two @samp{a}s will be @code{equal} but not
34746@code{eq} to each other.
34747@end defun
34748
34749@defun expr-contains-count expr var
34750Returns the number of occurrences of @var{var} as a subexpression
34751of @var{expr}, or @code{nil} if there are no occurrences.
34752@end defun
34753
34754@defun expr-depends expr var
34755Returns true if @var{expr} refers to any variable the occurs in @var{var}.
34756In other words, it checks if @var{expr} and @var{var} have any variables
34757in common.
34758@end defun
34759
34760@defun expr-contains-vars expr
34761Return true if @var{expr} contains any variables, or @code{nil} if @var{expr}
34762contains only constants and functions with constant arguments.
34763@end defun
34764
34765@defun expr-subst expr old new
34766Returns a copy of @var{expr}, with all occurrences of @var{old} replaced
34767by @var{new}. This treats @code{lambda} forms specially with respect
34768to the dummy argument variables, so that the effect is always to return
34769@var{expr} evaluated at @var{old} = @var{new}.
34770@end defun
34771
34772@defun multi-subst expr old new
34773This is like @code{expr-subst}, except that @var{old} and @var{new}
34774are lists of expressions to be substituted simultaneously. If one
34775list is shorter than the other, trailing elements of the longer list
34776are ignored.
34777@end defun
34778
34779@defun expr-weight expr
34780Returns the ``weight'' of @var{expr}, basically a count of the total
34781number of objects and function calls that appear in @var{expr}. For
34782``primitive'' objects, this will be one.
34783@end defun
34784
34785@defun expr-height expr
34786Returns the ``height'' of @var{expr}, which is the deepest level to
34787which function calls are nested. (Note that @samp{@var{a} + @var{b}}
34788counts as a function call.) For primitive objects, this returns zero.
34789@end defun
34790
34791@defun polynomial-p expr var
34792Check if @var{expr} is a polynomial in variable (or sub-expression)
34793@var{var}. If so, return the degree of the polynomial, that is, the
34794highest power of @var{var} that appears in @var{expr}. For example,
34795for @samp{(x^2 + 3)^3 + 4} this would return 6. This function returns
34796@code{nil} unless @var{expr}, when expanded out by @kbd{a x}
34797(@code{calc-expand}), would consist of a sum of terms in which @var{var}
34798appears only raised to nonnegative integer powers. Note that if
34799@var{var} does not occur in @var{expr}, then @var{expr} is considered
34800a polynomial of degree 0.
34801@end defun
34802
34803@defun is-polynomial expr var degree loose
34804Check if @var{expr} is a polynomial in variable or sub-expression
34805@var{var}, and, if so, return a list representation of the polynomial
34806where the elements of the list are coefficients of successive powers of
34807@var{var}: @samp{@var{a} + @var{b} x + @var{c} x^3} would produce the
34808list @samp{(@var{a} @var{b} 0 @var{c})}, and @samp{(x + 1)^2} would
34809produce the list @samp{(1 2 1)}. The highest element of the list will
34810be non-zero, with the special exception that if @var{expr} is the
34811constant zero, the returned value will be @samp{(0)}. Return @code{nil}
34812if @var{expr} is not a polynomial in @var{var}. If @var{degree} is
34813specified, this will not consider polynomials of degree higher than that
34814value. This is a good precaution because otherwise an input of
34815@samp{(x+1)^1000} will cause a huge coefficient list to be built. If
34816@var{loose} is non-@code{nil}, then a looser definition of a polynomial
34817is used in which coefficients are no longer required not to depend on
34818@var{var}, but are only required not to take the form of polynomials
34819themselves. For example, @samp{sin(x) x^2 + cos(x)} is a loose
34820polynomial with coefficients @samp{((calcFunc-cos x) 0 (calcFunc-sin
34821x))}. The result will never be @code{nil} in loose mode, since any
34822expression can be interpreted as a ``constant'' loose polynomial.
34823@end defun
34824
34825@defun polynomial-base expr pred
34826Check if @var{expr} is a polynomial in any variable that occurs in it;
34827if so, return that variable. (If @var{expr} is a multivariate polynomial,
34828this chooses one variable arbitrarily.) If @var{pred} is specified, it should
34829be a Lisp function which is called as @samp{(@var{pred} @var{subexpr})},
34830and which should return true if @code{mpb-top-expr} (a global name for
34831the original @var{expr}) is a suitable polynomial in @var{subexpr}.
34832The default predicate uses @samp{(polynomial-p mpb-top-expr @var{subexpr})};
34833you can use @var{pred} to specify additional conditions. Or, you could
34834have @var{pred} build up a list of every suitable @var{subexpr} that
34835is found.
34836@end defun
34837
34838@defun poly-simplify poly
34839Simplify polynomial coefficient list @var{poly} by (destructively)
34840clipping off trailing zeros.
34841@end defun
34842
34843@defun poly-mix a ac b bc
34844Mix two polynomial lists @var{a} and @var{b} (in the form returned by
34845@code{is-polynomial}) in a linear combination with coefficient expressions
34846@var{ac} and @var{bc}. The result is a (not necessarily simplified)
34847polynomial list representing @samp{@var{ac} @var{a} + @var{bc} @var{b}}.
34848@end defun
34849
34850@defun poly-mul a b
34851Multiply two polynomial coefficient lists @var{a} and @var{b}. The
34852result will be in simplified form if the inputs were simplified.
34853@end defun
34854
34855@defun build-polynomial-expr poly var
34856Construct a Calc formula which represents the polynomial coefficient
34857list @var{poly} applied to variable @var{var}. The @kbd{a c}
34858(@code{calc-collect}) command uses @code{is-polynomial} to turn an
34859expression into a coefficient list, then @code{build-polynomial-expr}
34860to turn the list back into an expression in regular form.
34861@end defun
34862
34863@defun check-unit-name var
34864Check if @var{var} is a variable which can be interpreted as a unit
34865name. If so, return the units table entry for that unit. This
34866will be a list whose first element is the unit name (not counting
34867prefix characters) as a symbol and whose second element is the
34868Calc expression which defines the unit. (Refer to the Calc sources
34869for details on the remaining elements of this list.) If @var{var}
34870is not a variable or is not a unit name, return @code{nil}.
34871@end defun
34872
34873@defun units-in-expr-p expr sub-exprs
34874Return true if @var{expr} contains any variables which can be
34875interpreted as units. If @var{sub-exprs} is @code{t}, the entire
34876expression is searched. If @var{sub-exprs} is @code{nil}, this
34877checks whether @var{expr} is directly a units expression.
34878@end defun
34879
34880@defun single-units-in-expr-p expr
34881Check whether @var{expr} contains exactly one units variable. If so,
34882return the units table entry for the variable. If @var{expr} does
34883not contain any units, return @code{nil}. If @var{expr} contains
34884two or more units, return the symbol @code{wrong}.
34885@end defun
34886
34887@defun to-standard-units expr which
34888Convert units expression @var{expr} to base units. If @var{which}
34889is @code{nil}, use Calc's native base units. Otherwise, @var{which}
34890can specify a units system, which is a list of two-element lists,
34891where the first element is a Calc base symbol name and the second
34892is an expression to substitute for it.
34893@end defun
34894
34895@defun remove-units expr
34896Return a copy of @var{expr} with all units variables replaced by ones.
34897This expression is generally normalized before use.
34898@end defun
34899
34900@defun extract-units expr
34901Return a copy of @var{expr} with everything but units variables replaced
34902by ones.
34903@end defun
34904
34905@node Formatting Lisp Functions, Hooks, Symbolic Lisp Functions, Internals
34906@subsubsection I/O and Formatting Functions
34907
34908@noindent
34909The functions described here are responsible for parsing and formatting
34910Calc numbers and formulas.
34911
34912@defun calc-eval str sep arg1 arg2 @dots{}
34913This is the simplest interface to the Calculator from another Lisp program.
34914@xref{Calling Calc from Your Programs}.
34915@end defun
34916
34917@defun read-number str
34918If string @var{str} contains a valid Calc number, either integer,
34919fraction, float, or HMS form, this function parses and returns that
34920number. Otherwise, it returns @code{nil}.
34921@end defun
34922
34923@defun read-expr str
34924Read an algebraic expression from string @var{str}. If @var{str} does
34925not have the form of a valid expression, return a list of the form
34926@samp{(error @var{pos} @var{msg})} where @var{pos} is an integer index
34927into @var{str} of the general location of the error, and @var{msg} is
34928a string describing the problem.
34929@end defun
34930
34931@defun read-exprs str
34932Read a list of expressions separated by commas, and return it as a
34933Lisp list. If an error occurs in any expressions, an error list as
34934shown above is returned instead.
34935@end defun
34936
34937@defun calc-do-alg-entry initial prompt no-norm
34938Read an algebraic formula or formulas using the minibuffer. All
34939conventions of regular algebraic entry are observed. The return value
34940is a list of Calc formulas; there will be more than one if the user
34941entered a list of values separated by commas. The result is @code{nil}
34942if the user presses Return with a blank line. If @var{initial} is
34943given, it is a string which the minibuffer will initially contain.
34944If @var{prompt} is given, it is the prompt string to use; the default
34945is ``Algebraic:''. If @var{no-norm} is @code{t}, the formulas will
34946be returned exactly as parsed; otherwise, they will be passed through
34947@code{calc-normalize} first.
34948
34949To support the use of @kbd{$} characters in the algebraic entry, use
34950@code{let} to bind @code{calc-dollar-values} to a list of the values
34951to be substituted for @kbd{$}, @kbd{$$}, and so on, and bind
34952@code{calc-dollar-used} to 0. Upon return, @code{calc-dollar-used}
34953will have been changed to the highest number of consecutive @kbd{$}s
34954that actually appeared in the input.
34955@end defun
34956
34957@defun format-number a
34958Convert the real or complex number or HMS form @var{a} to string form.
34959@end defun
34960
34961@defun format-flat-expr a prec
34962Convert the arbitrary Calc number or formula @var{a} to string form,
34963in the style used by the trail buffer and the @code{calc-edit} command.
34964This is a simple format designed
34965mostly to guarantee the string is of a form that can be re-parsed by
34966@code{read-expr}. Most formatting modes, such as digit grouping,
34967complex number format, and point character, are ignored to ensure the
34968result will be re-readable. The @var{prec} parameter is normally 0; if
34969you pass a large integer like 1000 instead, the expression will be
34970surrounded by parentheses unless it is a plain number or variable name.
34971@end defun
34972
34973@defun format-nice-expr a width
34974This is like @code{format-flat-expr} (with @var{prec} equal to 0),
34975except that newlines will be inserted to keep lines down to the
34976specified @var{width}, and vectors that look like matrices or rewrite
34977rules are written in a pseudo-matrix format. The @code{calc-edit}
34978command uses this when only one stack entry is being edited.
34979@end defun
34980
34981@defun format-value a width
34982Convert the Calc number or formula @var{a} to string form, using the
34983format seen in the stack buffer. Beware the string returned may
34984not be re-readable by @code{read-expr}, for example, because of digit
34985grouping. Multi-line objects like matrices produce strings that
34986contain newline characters to separate the lines. The @var{w}
34987parameter, if given, is the target window size for which to format
34988the expressions. If @var{w} is omitted, the width of the Calculator
34989window is used.
34990@end defun
34991
34992@defun compose-expr a prec
34993Format the Calc number or formula @var{a} according to the current
34994language mode, returning a ``composition.'' To learn about the
34995structure of compositions, see the comments in the Calc source code.
34996You can specify the format of a given type of function call by putting
34997a @code{math-compose-@var{lang}} property on the function's symbol,
34998whose value is a Lisp function that takes @var{a} and @var{prec} as
34999arguments and returns a composition. Here @var{lang} is a language
35000mode name, one of @code{normal}, @code{big}, @code{c}, @code{pascal},
35001@code{fortran}, @code{tex}, @code{eqn}, @code{math}, or @code{maple}.
35002In Big mode, Calc actually tries @code{math-compose-big} first, then
35003tries @code{math-compose-normal}. If this property does not exist,
35004or if the function returns @code{nil}, the function is written in the
35005normal function-call notation for that language.
35006@end defun
35007
35008@defun composition-to-string c w
35009Convert a composition structure returned by @code{compose-expr} into
35010a string. Multi-line compositions convert to strings containing
35011newline characters. The target window size is given by @var{w}.
35012The @code{format-value} function basically calls @code{compose-expr}
35013followed by @code{composition-to-string}.
35014@end defun
35015
35016@defun comp-width c
35017Compute the width in characters of composition @var{c}.
35018@end defun
35019
35020@defun comp-height c
35021Compute the height in lines of composition @var{c}.
35022@end defun
35023
35024@defun comp-ascent c
35025Compute the portion of the height of composition @var{c} which is on or
35026above the baseline. For a one-line composition, this will be one.
35027@end defun
35028
35029@defun comp-descent c
35030Compute the portion of the height of composition @var{c} which is below
35031the baseline. For a one-line composition, this will be zero.
35032@end defun
35033
35034@defun comp-first-char c
35035If composition @var{c} is a ``flat'' composition, return the first
35036(leftmost) character of the composition as an integer. Otherwise,
35037return @code{nil}.
35038@end defun
35039
35040@defun comp-last-char c
35041If composition @var{c} is a ``flat'' composition, return the last
35042(rightmost) character, otherwise return @code{nil}.
35043@end defun
35044
35045@comment @node Lisp Variables, Hooks, Formatting Lisp Functions, Internals
35046@comment @subsubsection Lisp Variables
35047@comment
35048@comment @noindent
35049@comment (This section is currently unfinished.)
35050
35051@node Hooks, , Formatting Lisp Functions, Internals
35052@subsubsection Hooks
35053
35054@noindent
35055Hooks are variables which contain Lisp functions (or lists of functions)
35056which are called at various times. Calc defines a number of hooks
35057that help you to customize it in various ways. Calc uses the Lisp
35058function @code{run-hooks} to invoke the hooks shown below. Several
35059other customization-related variables are also described here.
35060
35061@defvar calc-load-hook
35062This hook is called at the end of @file{calc.el}, after the file has
35063been loaded, before any functions in it have been called, but after
35064@code{calc-mode-map} and similar variables have been set up.
35065@end defvar
35066
35067@defvar calc-ext-load-hook
35068This hook is called at the end of @file{calc-ext.el}.
35069@end defvar
35070
35071@defvar calc-start-hook
35072This hook is called as the last step in a @kbd{M-x calc} command.
35073At this point, the Calc buffer has been created and initialized if
35074necessary, the Calc window and trail window have been created,
35075and the ``Welcome to Calc'' message has been displayed.
35076@end defvar
35077
35078@defvar calc-mode-hook
35079This hook is called when the Calc buffer is being created. Usually
35080this will only happen once per Emacs session. The hook is called
35081after Emacs has switched to the new buffer, the mode-settings file
35082has been read if necessary, and all other buffer-local variables
35083have been set up. After this hook returns, Calc will perform a
35084@code{calc-refresh} operation, set up the mode line display, then
35085evaluate any deferred @code{calc-define} properties that have not
35086been evaluated yet.
35087@end defvar
35088
35089@defvar calc-trail-mode-hook
35090This hook is called when the Calc Trail buffer is being created.
35091It is called as the very last step of setting up the Trail buffer.
35092Like @code{calc-mode-hook}, this will normally happen only once
35093per Emacs session.
35094@end defvar
35095
35096@defvar calc-end-hook
35097This hook is called by @code{calc-quit}, generally because the user
35098presses @kbd{q} or @kbd{C-x * c} while in Calc. The Calc buffer will
35099be the current buffer. The hook is called as the very first
35100step, before the Calc window is destroyed.
35101@end defvar
35102
35103@defvar calc-window-hook
35104If this hook is non-@code{nil}, it is called to create the Calc window.
35105Upon return, this new Calc window should be the current window.
35106(The Calc buffer will already be the current buffer when the
35107hook is called.) If the hook is not defined, Calc will
35108generally use @code{split-window}, @code{set-window-buffer},
35109and @code{select-window} to create the Calc window.
35110@end defvar
35111
35112@defvar calc-trail-window-hook
35113If this hook is non-@code{nil}, it is called to create the Calc Trail
35114window. The variable @code{calc-trail-buffer} will contain the buffer
35115which the window should use. Unlike @code{calc-window-hook}, this hook
35116must @emph{not} switch into the new window.
35117@end defvar
35118
35119@defvar calc-embedded-mode-hook
35120This hook is called the first time that Embedded mode is entered.
35121@end defvar
35122
35123@defvar calc-embedded-new-buffer-hook
35124This hook is called each time that Embedded mode is entered in a
35125new buffer.
35126@end defvar
35127
35128@defvar calc-embedded-new-formula-hook
35129This hook is called each time that Embedded mode is enabled for a
35130new formula.
35131@end defvar
35132
35133@defvar calc-edit-mode-hook
35134This hook is called by @code{calc-edit} (and the other ``edit''
35135commands) when the temporary editing buffer is being created.
35136The buffer will have been selected and set up to be in
35137@code{calc-edit-mode}, but will not yet have been filled with
35138text. (In fact it may still have leftover text from a previous
35139@code{calc-edit} command.)
35140@end defvar
35141
35142@defvar calc-mode-save-hook
35143This hook is called by the @code{calc-save-modes} command,
35144after Calc's own mode features have been inserted into the
35145Calc init file and just before the ``End of mode settings''
35146message is inserted.
35147@end defvar
35148
35149@defvar calc-reset-hook
35150This hook is called after @kbd{C-x * 0} (@code{calc-reset}) has
35151reset all modes. The Calc buffer will be the current buffer.
35152@end defvar
35153
35154@defvar calc-other-modes
35155This variable contains a list of strings. The strings are
35156concatenated at the end of the modes portion of the Calc
35157mode line (after standard modes such as ``Deg'', ``Inv'' and
35158``Hyp''). Each string should be a short, single word followed
35159by a space. The variable is @code{nil} by default.
35160@end defvar
35161
35162@defvar calc-mode-map
35163This is the keymap that is used by Calc mode. The best time
35164to adjust it is probably in a @code{calc-mode-hook}. If the
35165Calc extensions package (@file{calc-ext.el}) has not yet been
35166loaded, many of these keys will be bound to @code{calc-missing-key},
35167which is a command that loads the extensions package and
35168``retypes'' the key. If your @code{calc-mode-hook} rebinds
35169one of these keys, it will probably be overridden when the
35170extensions are loaded.
35171@end defvar
35172
35173@defvar calc-digit-map
35174This is the keymap that is used during numeric entry. Numeric
35175entry uses the minibuffer, but this map binds every non-numeric
35176key to @code{calcDigit-nondigit} which generally calls
35177@code{exit-minibuffer} and ``retypes'' the key.
35178@end defvar
35179
35180@defvar calc-alg-ent-map
35181This is the keymap that is used during algebraic entry. This is
35182mostly a copy of @code{minibuffer-local-map}.
35183@end defvar
35184
35185@defvar calc-store-var-map
35186This is the keymap that is used during entry of variable names for
35187commands like @code{calc-store} and @code{calc-recall}. This is
35188mostly a copy of @code{minibuffer-local-completion-map}.
35189@end defvar
35190
35191@defvar calc-edit-mode-map
35192This is the (sparse) keymap used by @code{calc-edit} and other
35193temporary editing commands. It binds @key{RET}, @key{LFD},
35194and @kbd{C-c C-c} to @code{calc-edit-finish}.
35195@end defvar
35196
35197@defvar calc-mode-var-list
35198This is a list of variables which are saved by @code{calc-save-modes}.
35199Each entry is a list of two items, the variable (as a Lisp symbol)
35200and its default value. When modes are being saved, each variable
35201is compared with its default value (using @code{equal}) and any
35202non-default variables are written out.
35203@end defvar
35204
35205@defvar calc-local-var-list
35206This is a list of variables which should be buffer-local to the
35207Calc buffer. Each entry is a variable name (as a Lisp symbol).
35208These variables also have their default values manipulated by
35209the @code{calc} and @code{calc-quit} commands; @pxref{Multiple Calculators}.
35210Since @code{calc-mode-hook} is called after this list has been
35211used the first time, your hook should add a variable to the
35212list and also call @code{make-local-variable} itself.
35213@end defvar
35214
35215@node Copying, GNU Free Documentation License, Programming, Top
35216@appendix GNU GENERAL PUBLIC LICENSE
35217@include gpl.texi
35218
35219@node GNU Free Documentation License, Customizing Calc, Copying, Top
35220@appendix GNU Free Documentation License
35221@include doclicense.texi
35222
35223@node Customizing Calc, Reporting Bugs, GNU Free Documentation License, Top
35224@appendix Customizing Calc
35225
35226The usual prefix for Calc is the key sequence @kbd{C-x *}. If you wish
35227to use a different prefix, you can put
35228
35229@example
35230(global-set-key "NEWPREFIX" 'calc-dispatch)
35231@end example
35232
35233@noindent
40ba43b4 35234in your .emacs file.
4009494e
GM
35235(@xref{Key Bindings,,Customizing Key Bindings,emacs,
35236The GNU Emacs Manual}, for more information on binding keys.)
35237A convenient way to start Calc is with @kbd{C-x * *}; to make it equally
35238convenient for users who use a different prefix, the prefix can be
35239followed by @kbd{=}, @kbd{&}, @kbd{#}, @kbd{\}, @kbd{/}, @kbd{+} or
35240@kbd{-} as well as @kbd{*} to start Calc, and so in many cases the last
35241character of the prefix can simply be typed twice.
35242
35243Calc is controlled by many variables, most of which can be reset
35244from within Calc. Some variables are less involved with actual
677c1109 35245calculation and can be set outside of Calc using Emacs's
4009494e
GM
35246customization facilities. These variables are listed below.
35247Typing @kbd{M-x customize-variable RET @var{variable-name} RET}
35248will bring up a buffer in which the variable's value can be redefined.
35249Typing @kbd{M-x customize-group RET calc RET} will bring up a buffer which
35250contains all of Calc's customizable variables. (These variables can
35251also be reset by putting the appropriate lines in your .emacs file;
35252@xref{Init File, ,Init File, emacs, The GNU Emacs Manual}.)
35253
35254Some of the customizable variables are regular expressions. A regular
35255expression is basically a pattern that Calc can search for.
35256See @ref{Regexp Search,, Regular Expression Search, emacs, The GNU Emacs Manual}
35257to see how regular expressions work.
35258
35259@defvar calc-settings-file
35260The variable @code{calc-settings-file} holds the file name in
35261which commands like @kbd{m m} and @kbd{Z P} store ``permanent''
40ba43b4 35262definitions.
4009494e
GM
35263If @code{calc-settings-file} is not your user init file (typically
35264@file{~/.emacs}) and if the variable @code{calc-loaded-settings-file} is
35265@code{nil}, then Calc will automatically load your settings file (if it
35266exists) the first time Calc is invoked.
35267
dcf7843e
JB
35268The default value for this variable is @code{"~/.emacs.d/calc.el"}
35269unless the file @file{~/.calc.el} exists, in which case the default
35270value will be @code{"~/.calc.el"}.
4009494e
GM
35271@end defvar
35272
35273@defvar calc-gnuplot-name
35274See @ref{Graphics}.@*
35275The variable @code{calc-gnuplot-name} should be the name of the
35276GNUPLOT program (a string). If you have GNUPLOT installed on your
35277system but Calc is unable to find it, you may need to set this
35278variable. You may also need to set some Lisp variables to show Calc how
35279to run GNUPLOT on your system, see @ref{Devices, ,Graphical Devices} .
35280The default value of @code{calc-gnuplot-name} is @code{"gnuplot"}.
35281@end defvar
35282
35283@defvar calc-gnuplot-plot-command
35284@defvarx calc-gnuplot-print-command
35285See @ref{Devices, ,Graphical Devices}.@*
35286The variables @code{calc-gnuplot-plot-command} and
35287@code{calc-gnuplot-print-command} represent system commands to
35288display and print the output of GNUPLOT, respectively. These may be
35289@code{nil} if no command is necessary, or strings which can include
35290@samp{%s} to signify the name of the file to be displayed or printed.
35291Or, these variables may contain Lisp expressions which are evaluated
35292to display or print the output.
35293
35294The default value of @code{calc-gnuplot-plot-command} is @code{nil},
35295and the default value of @code{calc-gnuplot-print-command} is
35296@code{"lp %s"}.
35297@end defvar
35298
35299@defvar calc-language-alist
35300See @ref{Basic Embedded Mode}.@*
35301The variable @code{calc-language-alist} controls the languages that
35302Calc will associate with major modes. When Calc embedded mode is
35303enabled, it will try to use the current major mode to
35304determine what language should be used. (This can be overridden using
35305Calc's mode changing commands, @xref{Mode Settings in Embedded Mode}.)
35306The variable @code{calc-language-alist} consists of a list of pairs of
40ba43b4 35307the form @code{(@var{MAJOR-MODE} . @var{LANGUAGE})}; for example,
4009494e
GM
35308@code{(latex-mode . latex)} is one such pair. If Calc embedded is
35309activated in a buffer whose major mode is @var{MAJOR-MODE}, it will set itself
35310to use the language @var{LANGUAGE}.
35311
35312The default value of @code{calc-language-alist} is
35313@example
35314 ((latex-mode . latex)
35315 (tex-mode . tex)
35316 (plain-tex-mode . tex)
35317 (context-mode . tex)
35318 (nroff-mode . eqn)
35319 (pascal-mode . pascal)
35320 (c-mode . c)
35321 (c++-mode . c)
35322 (fortran-mode . fortran)
35323 (f90-mode . fortran))
35324@end example
35325@end defvar
35326
35327@defvar calc-embedded-announce-formula
35328@defvarx calc-embedded-announce-formula-alist
35329See @ref{Customizing Embedded Mode}.@*
35330The variable @code{calc-embedded-announce-formula} helps determine
35331what formulas @kbd{C-x * a} will activate in a buffer. It is a
35332regular expression, and when activating embedded formulas with
35333@kbd{C-x * a}, it will tell Calc that what follows is a formula to be
35334activated. (Calc also uses other patterns to find formulas, such as
40ba43b4 35335@samp{=>} and @samp{:=}.)
4009494e
GM
35336
35337The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, which checks
35338for @samp{%Embed} followed by any number of lines beginning with
35339@samp{%} and a space.
35340
35341The variable @code{calc-embedded-announce-formula-alist} is used to
35342set @code{calc-embedded-announce-formula} to different regular
35343expressions depending on the major mode of the editing buffer.
35344It consists of a list of pairs of the form @code{(@var{MAJOR-MODE} .
35345@var{REGEXP})}, and its default value is
35346@example
35347 ((c++-mode . "//Embed\n\\(// .*\n\\)*")
35348 (c-mode . "/\\*Embed\\*/\n\\(/\\* .*\\*/\n\\)*")
35349 (f90-mode . "!Embed\n\\(! .*\n\\)*")
35350 (fortran-mode . "C Embed\n\\(C .*\n\\)*")
35351 (html-helper-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
35352 (html-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
35353 (nroff-mode . "\\\\\"Embed\n\\(\\\\\" .*\n\\)*")
35354 (pascal-mode . "@{Embed@}\n\\(@{.*@}\n\\)*")
35355 (sgml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
35356 (xml-mode . "<!-- Embed -->\n\\(<!-- .* -->\n\\)*")
35357 (texinfo-mode . "@@c Embed\n\\(@@c .*\n\\)*"))
35358@end example
35359Any major modes added to @code{calc-embedded-announce-formula-alist}
40ba43b4 35360should also be added to @code{calc-embedded-open-close-plain-alist}
4009494e
GM
35361and @code{calc-embedded-open-close-mode-alist}.
35362@end defvar
35363
35364@defvar calc-embedded-open-formula
35365@defvarx calc-embedded-close-formula
35366@defvarx calc-embedded-open-close-formula-alist
35367See @ref{Customizing Embedded Mode}.@*
35368The variables @code{calc-embedded-open-formula} and
8dc6104d 35369@code{calc-embedded-close-formula} control the region that Calc will
4009494e 35370activate as a formula when Embedded mode is entered with @kbd{C-x * e}.
40ba43b4 35371They are regular expressions;
4009494e
GM
35372Calc normally scans backward and forward in the buffer for the
35373nearest text matching these regular expressions to be the ``formula
35374delimiters''.
35375
35376The simplest delimiters are blank lines. Other delimiters that
35377Embedded mode understands by default are:
35378@enumerate
35379@item
c1dabff0 35380The @TeX{} and @LaTeX{} math delimiters @samp{$ $}, @samp{$$ $$},
4009494e
GM
35381@samp{\[ \]}, and @samp{\( \)};
35382@item
35383Lines beginning with @samp{\begin} and @samp{\end} (except matrix delimiters);
35384@item
35385Lines beginning with @samp{@@} (Texinfo delimiters).
35386@item
35387Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
35388@item
35389Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
35390@end enumerate
35391
35392The variable @code{calc-embedded-open-close-formula-alist} is used to
35393set @code{calc-embedded-open-formula} and
35394@code{calc-embedded-close-formula} to different regular
35395expressions depending on the major mode of the editing buffer.
40ba43b4 35396It consists of a list of lists of the form
4009494e
GM
35397@code{(@var{MAJOR-MODE} @var{OPEN-FORMULA-REGEXP}
35398@var{CLOSE-FORMULA-REGEXP})}, and its default value is
35399@code{nil}.
35400@end defvar
35401
4a65fb7a
JB
35402@defvar calc-embedded-word-regexp
35403@defvarx calc-embedded-word-regexp-alist
4009494e 35404See @ref{Customizing Embedded Mode}.@*
4a65fb7a
JB
35405The variable @code{calc-embedded-word-regexp} determines the expression
35406that Calc will activate when Embedded mode is entered with @kbd{C-x *
35407w}. It is a regular expressions.
35408
35409The default value of @code{calc-embedded-word-regexp} is
35410@code{"[-+]?[0-9]+\\(\\.[0-9]+\\)?\\([eE][-+]?[0-9]+\\)?"}.
35411
35412The variable @code{calc-embedded-word-regexp-alist} is used to
35413set @code{calc-embedded-word-regexp} to a different regular
35414expression depending on the major mode of the editing buffer.
40ba43b4 35415It consists of a list of lists of the form
4a65fb7a 35416@code{(@var{MAJOR-MODE} @var{WORD-REGEXP})}, and its default value is
4009494e
GM
35417@code{nil}.
35418@end defvar
35419
35420@defvar calc-embedded-open-plain
35421@defvarx calc-embedded-close-plain
35422@defvarx calc-embedded-open-close-plain-alist
35423See @ref{Customizing Embedded Mode}.@*
35424The variables @code{calc-embedded-open-plain} and
35425@code{calc-embedded-open-plain} are used to delimit ``plain''
35426formulas. Note that these are actual strings, not regular
35427expressions, because Calc must be able to write these string into a
35428buffer as well as to recognize them.
35429
40ba43b4
PE
35430The default string for @code{calc-embedded-open-plain} is
35431@code{"%%% "}, note the trailing space. The default string for
4009494e
GM
35432@code{calc-embedded-close-plain} is @code{" %%%\n"}, without
35433the trailing newline here, the first line of a Big mode formula
35434that followed might be shifted over with respect to the other lines.
35435
35436The variable @code{calc-embedded-open-close-plain-alist} is used to
35437set @code{calc-embedded-open-plain} and
35438@code{calc-embedded-close-plain} to different strings
35439depending on the major mode of the editing buffer.
40ba43b4 35440It consists of a list of lists of the form
4009494e
GM
35441@code{(@var{MAJOR-MODE} @var{OPEN-PLAIN-STRING}
35442@var{CLOSE-PLAIN-STRING})}, and its default value is
35443@example
35444 ((c++-mode "// %% " " %%\n")
35445 (c-mode "/* %% " " %% */\n")
35446 (f90-mode "! %% " " %%\n")
35447 (fortran-mode "C %% " " %%\n")
35448 (html-helper-mode "<!-- %% " " %% -->\n")
35449 (html-mode "<!-- %% " " %% -->\n")
35450 (nroff-mode "\\\" %% " " %%\n")
35451 (pascal-mode "@{%% " " %%@}\n")
35452 (sgml-mode "<!-- %% " " %% -->\n")
35453 (xml-mode "<!-- %% " " %% -->\n")
35454 (texinfo-mode "@@c %% " " %%\n"))
35455@end example
35456Any major modes added to @code{calc-embedded-open-close-plain-alist}
35457should also be added to @code{calc-embedded-announce-formula-alist}
35458and @code{calc-embedded-open-close-mode-alist}.
35459@end defvar
35460
35461@defvar calc-embedded-open-new-formula
35462@defvarx calc-embedded-close-new-formula
35463@defvarx calc-embedded-open-close-new-formula-alist
35464See @ref{Customizing Embedded Mode}.@*
35465The variables @code{calc-embedded-open-new-formula} and
35466@code{calc-embedded-close-new-formula} are strings which are
35467inserted before and after a new formula when you type @kbd{C-x * f}.
35468
35469The default value of @code{calc-embedded-open-new-formula} is
35470@code{"\n\n"}. If this string begins with a newline character and the
35471@kbd{C-x * f} is typed at the beginning of a line, @kbd{C-x * f} will skip
35472this first newline to avoid introducing unnecessary blank lines in the
35473file. The default value of @code{calc-embedded-close-new-formula} is
35474also @code{"\n\n"}. The final newline is omitted by @w{@kbd{C-x * f}}
35475if typed at the end of a line. (It follows that if @kbd{C-x * f} is
35476typed on a blank line, both a leading opening newline and a trailing
35477closing newline are omitted.)
35478
35479The variable @code{calc-embedded-open-close-new-formula-alist} is used to
35480set @code{calc-embedded-open-new-formula} and
35481@code{calc-embedded-close-new-formula} to different strings
35482depending on the major mode of the editing buffer.
40ba43b4 35483It consists of a list of lists of the form
4009494e
GM
35484@code{(@var{MAJOR-MODE} @var{OPEN-NEW-FORMULA-STRING}
35485@var{CLOSE-NEW-FORMULA-STRING})}, and its default value is
35486@code{nil}.
35487@end defvar
35488
35489@defvar calc-embedded-open-mode
35490@defvarx calc-embedded-close-mode
35491@defvarx calc-embedded-open-close-mode-alist
35492See @ref{Customizing Embedded Mode}.@*
35493The variables @code{calc-embedded-open-mode} and
35494@code{calc-embedded-close-mode} are strings which Calc will place before
35495and after any mode annotations that it inserts. Calc never scans for
35496these strings; Calc always looks for the annotation itself, so it is not
35497necessary to add them to user-written annotations.
35498
35499The default value of @code{calc-embedded-open-mode} is @code{"% "}
35500and the default value of @code{calc-embedded-close-mode} is
40ba43b4 35501@code{"\n"}.
4009494e
GM
35502If you change the value of @code{calc-embedded-close-mode}, it is a good
35503idea still to end with a newline so that mode annotations will appear on
35504lines by themselves.
35505
35506The variable @code{calc-embedded-open-close-mode-alist} is used to
35507set @code{calc-embedded-open-mode} and
35508@code{calc-embedded-close-mode} to different strings
35509expressions depending on the major mode of the editing buffer.
40ba43b4 35510It consists of a list of lists of the form
4009494e
GM
35511@code{(@var{MAJOR-MODE} @var{OPEN-MODE-STRING}
35512@var{CLOSE-MODE-STRING})}, and its default value is
35513@example
35514 ((c++-mode "// " "\n")
35515 (c-mode "/* " " */\n")
35516 (f90-mode "! " "\n")
35517 (fortran-mode "C " "\n")
35518 (html-helper-mode "<!-- " " -->\n")
35519 (html-mode "<!-- " " -->\n")
35520 (nroff-mode "\\\" " "\n")
35521 (pascal-mode "@{ " " @}\n")
35522 (sgml-mode "<!-- " " -->\n")
35523 (xml-mode "<!-- " " -->\n")
35524 (texinfo-mode "@@c " "\n"))
35525@end example
35526Any major modes added to @code{calc-embedded-open-close-mode-alist}
35527should also be added to @code{calc-embedded-announce-formula-alist}
35528and @code{calc-embedded-open-close-plain-alist}.
35529@end defvar
35530
d71990a1
JB
35531@defvar calc-lu-power-reference
35532@defvarx calc-lu-field-reference
2e78df6b 35533See @ref{Logarithmic Units}.@*
d71990a1
JB
35534The variables @code{calc-lu-power-reference} and
35535@code{calc-lu-field-reference} are unit expressions (written as
2e78df6b
JB
35536strings) which Calc will use as reference quantities for logarithmic
35537units.
35538
d71990a1
JB
35539The default value of @code{calc-lu-power-reference} is @code{"mW"}
35540and the default value of @code{calc-lu-field-reference} is
40ba43b4 35541@code{"20 uPa"}.
2e78df6b
JB
35542@end defvar
35543
05a29101
JB
35544@defvar calc-note-threshold
35545See @ref{Musical Notes}.@*
35546The variable @code{calc-note-threshold} is a number (written as a
35547string) which determines how close (in cents) a frequency needs to be
35548to a note to be recognized as that note.
35549
35550The default value of @code{calc-note-threshold} is 1.
35551@end defvar
35552
2c695727
JB
35553@defvar calc-highlight-selections-with-faces
35554@defvarx calc-selected-face
35555@defvarx calc-nonselected-face
443c2c03 35556See @ref{Displaying Selections}.@*
40ba43b4 35557The variable @code{calc-highlight-selections-with-faces}
2c695727 35558determines how selected sub-formulas are distinguished.
40ba43b4 35559If @code{calc-highlight-selections-with-faces} is nil, then
2c695727
JB
35560a selected sub-formula is distinguished either by changing every
35561character not part of the sub-formula with a dot or by changing every
40ba43b4 35562character in the sub-formula with a @samp{#} sign.
2c695727
JB
35563If @code{calc-highlight-selections-with-faces} is t,
35564then a selected sub-formula is distinguished either by displaying the
40ba43b4 35565non-selected portion of the formula with @code{calc-nonselected-face}
2c695727 35566or by displaying the selected sub-formula with
443c2c03 35567@code{calc-nonselected-face}.
2c695727
JB
35568@end defvar
35569
4009494e
GM
35570@defvar calc-multiplication-has-precedence
35571The variable @code{calc-multiplication-has-precedence} determines
45b778a6
JB
35572whether multiplication has precedence over division in algebraic
35573formulas in normal language modes. If
35574@code{calc-multiplication-has-precedence} is non-@code{nil}, then
35575multiplication has precedence (and, for certain obscure reasons, is
35576right associative), and so for example @samp{a/b*c} will be interpreted
35577as @samp{a/(b*c)}. If @code{calc-multiplication-has-precedence} is
35578@code{nil}, then multiplication has the same precedence as division
35579(and, like division, is left associative), and so for example
4009494e
GM
35580@samp{a/b*c} will be interpreted as @samp{(a/b)*c}. The default value
35581of @code{calc-multiplication-has-precedence} is @code{t}.
35582@end defvar
35583
d14b0029 35584@defvar calc-ensure-consistent-units
09ae5da1
PE
35585When converting units, the variable @code{calc-ensure-consistent-units}
35586determines whether or not the target units need to be consistent with the
d14b0029 35587original units. If @code{calc-ensure-consistent-units} is @code{nil}, then
09ae5da1
PE
35588the target units don't need to have the same dimensions as the original units;
35589for example, converting @samp{100 ft/s} to @samp{m} will produce @samp{30.48 m/s}.
35590If @code{calc-ensure-consistent-units} is non-@code{nil}, then the target units
35591need to have the same dimensions as the original units; for example, converting
35592@samp{100 ft/s} to @samp{m} will result in an error, since @samp{ft/s} and @samp{m}
35593have different dimensions. The default value of @code{calc-ensure-consistent-units}
d14b0029
JB
35594is @code{nil}.
35595@end defvar
35596
ec06459c
JB
35597@defvar calc-undo-length
35598The variable @code{calc-undo-length} determines the number of undo
35599steps that Calc will keep track of when @code{calc-quit} is called.
35600If @code{calc-undo-length} is a non-negative integer, then this is the
35601number of undo steps that will be preserved; if
35602@code{calc-undo-length} has any other value, then all undo steps will
35603be preserved. The default value of @code{calc-undo-length} is @expr{100}.
35604@end defvar
35605
723da6aa
JB
35606@defvar calc-gregorian-switch
35607See @ref{Date Forms}.@*
35608The variable @code{calc-gregorian-switch} is either a list of integers
35609@code{(@var{YEAR} @var{MONTH} @var{DAY})} or @code{nil}.
35610If it is @code{nil}, then Calc's date forms always represent Gregorian dates.
35611Otherwise, @code{calc-gregorian-switch} represents the date that the
35612calendar switches from Julian dates to Gregorian dates;
35613@code{(@var{YEAR} @var{MONTH} @var{DAY})} will be the first Gregorian
35614date. The customization buffer will offer several standard dates to
35615choose from, or the user can enter their own date.
35616
35617The default value of @code{calc-gregorian-switch} is @code{nil}.
35618@end defvar
35619
4009494e
GM
35620@node Reporting Bugs, Summary, Customizing Calc, Top
35621@appendix Reporting Bugs
35622
35623@noindent
35624If you find a bug in Calc, send e-mail to Jay Belanger,
35625
35626@example
35627jay.p.belanger@@gmail.com
35628@end example
35629
35630@noindent
35631There is an automatic command @kbd{M-x report-calc-bug} which helps
35632you to report bugs. This command prompts you for a brief subject
35633line, then leaves you in a mail editing buffer. Type @kbd{C-c C-c} to
35634send your mail. Make sure your subject line indicates that you are
35635reporting a Calc bug; this command sends mail to the maintainer's
35636regular mailbox.
35637
35638If you have suggestions for additional features for Calc, please send
35639them. Some have dared to suggest that Calc is already top-heavy with
35640features; this obviously cannot be the case, so if you have ideas, send
35641them right in.
35642
35643At the front of the source file, @file{calc.el}, is a list of ideas for
35644future work. If any enthusiastic souls wish to take it upon themselves
35645to work on these, please send a message (using @kbd{M-x report-calc-bug})
35646so any efforts can be coordinated.
35647
35648The latest version of Calc is available from Savannah, in the Emacs
b9f978f0 35649repository. See @uref{http://savannah.gnu.org/projects/emacs}.
4009494e
GM
35650
35651@c [summary]
35652@node Summary, Key Index, Reporting Bugs, Top
35653@appendix Calc Summary
35654
35655@noindent
5a83c46e 35656This section includes a complete list of Calc keystroke commands.
4009494e
GM
35657Each line lists the stack entries used by the command (top-of-stack
35658last), the keystrokes themselves, the prompts asked by the command,
35659and the result of the command (also with top-of-stack last).
35660The result is expressed using the equivalent algebraic function.
35661Commands which put no results on the stack show the full @kbd{M-x}
35662command name in that position. Numbers preceding the result or
35663command name refer to notes at the end.
35664
35665Algebraic functions and @kbd{M-x} commands that don't have corresponding
35666keystrokes are not listed in this summary.
35667@xref{Command Index}. @xref{Function Index}.
35668
35669@iftex
35670@begingroup
35671@tex
35672\vskip-2\baselineskip \null
35673\gdef\sumrow#1{\sumrowx#1\relax}%
35674\gdef\sumrowx#1\:#2\:#3\:#4\:#5\:#6\relax{%
35675\leavevmode%
35676{\smallfonts
35677\hbox to5em{\sl\hss#1}%
35678\hbox to5em{\tt#2\hss}%
35679\hbox to4em{\sl#3\hss}%
35680\hbox to5em{\rm\hss#4}%
35681\thinspace%
35682{\tt#5}%
35683{\sl#6}%
35684}}%
35685\gdef\sumlpar{{\rm(}}%
35686\gdef\sumrpar{{\rm)}}%
35687\gdef\sumcomma{{\rm,\thinspace}}%
35688\gdef\sumexcl{{\rm!}}%
35689\gdef\sumbreak{\vskip-2.5\baselineskip\goodbreak}%
35690\gdef\minus#1{{\tt-}}%
35691@end tex
35692@let@:=@sumsep
35693@let@r=@sumrow
35694@catcode`@(=@active @let(=@sumlpar
35695@catcode`@)=@active @let)=@sumrpar
35696@catcode`@,=@active @let,=@sumcomma
35697@catcode`@!=@active @let!=@sumexcl
35698@end iftex
35699@format
35700@iftex
35701@advance@baselineskip-2.5pt
35702@let@c@sumbreak
35703@end iftex
35704@r{ @: C-x * a @: @: 33 @:calc-embedded-activate@:}
35705@r{ @: C-x * b @: @: @:calc-big-or-small@:}
35706@r{ @: C-x * c @: @: @:calc@:}
35707@r{ @: C-x * d @: @: @:calc-embedded-duplicate@:}
35708@r{ @: C-x * e @: @: 34 @:calc-embedded@:}
35709@r{ @: C-x * f @:formula @: @:calc-embedded-new-formula@:}
35710@r{ @: C-x * g @: @: 35 @:calc-grab-region@:}
35711@r{ @: C-x * i @: @: @:calc-info@:}
35712@r{ @: C-x * j @: @: @:calc-embedded-select@:}
35713@r{ @: C-x * k @: @: @:calc-keypad@:}
35714@r{ @: C-x * l @: @: @:calc-load-everything@:}
35715@r{ @: C-x * m @: @: @:read-kbd-macro@:}
35716@r{ @: C-x * n @: @: 4 @:calc-embedded-next@:}
35717@r{ @: C-x * o @: @: @:calc-other-window@:}
35718@r{ @: C-x * p @: @: 4 @:calc-embedded-previous@:}
35719@r{ @: C-x * q @:formula @: @:quick-calc@:}
35720@r{ @: C-x * r @: @: 36 @:calc-grab-rectangle@:}
35721@r{ @: C-x * s @: @: @:calc-info-summary@:}
35722@r{ @: C-x * t @: @: @:calc-tutorial@:}
35723@r{ @: C-x * u @: @: @:calc-embedded-update-formula@:}
35724@r{ @: C-x * w @: @: @:calc-embedded-word@:}
35725@r{ @: C-x * x @: @: @:calc-quit@:}
35726@r{ @: C-x * y @: @:1,28,49 @:calc-copy-to-buffer@:}
35727@r{ @: C-x * z @: @: @:calc-user-invocation@:}
35728@r{ @: C-x * : @: @: 36 @:calc-grab-sum-down@:}
35729@r{ @: C-x * _ @: @: 36 @:calc-grab-sum-across@:}
35730@r{ @: C-x * ` @:editing @: 30 @:calc-embedded-edit@:}
35731@r{ @: C-x * 0 @:(zero) @: @:calc-reset@:}
35732
35733@c
35734@r{ @: 0-9 @:number @: @:@:number}
35735@r{ @: . @:number @: @:@:0.number}
35736@r{ @: _ @:number @: @:-@:number}
35737@r{ @: e @:number @: @:@:1e number}
35738@r{ @: # @:number @: @:@:current-radix@tfn{#}number}
35739@r{ @: P @:(in number) @: @:+/-@:}
35740@r{ @: M @:(in number) @: @:mod@:}
35741@r{ @: @@ ' " @: (in number)@: @:@:HMS form}
35742@r{ @: h m s @: (in number)@: @:@:HMS form}
35743
35744@c
35745@r{ @: ' @:formula @: 37,46 @:@:formula}
35746@r{ @: $ @:formula @: 37,46 @:$@:formula}
35747@r{ @: " @:string @: 37,46 @:@:string}
35748
35749@c
35750@r{ a b@: + @: @: 2 @:add@:(a,b) a+b}
35751@r{ a b@: - @: @: 2 @:sub@:(a,b) a@minus{}b}
35752@r{ a b@: * @: @: 2 @:mul@:(a,b) a b, a*b}
35753@r{ a b@: / @: @: 2 @:div@:(a,b) a/b}
35754@r{ a b@: ^ @: @: 2 @:pow@:(a,b) a^b}
35755@r{ a b@: I ^ @: @: 2 @:nroot@:(a,b) a^(1/b)}
35756@r{ a b@: % @: @: 2 @:mod@:(a,b) a%b}
35757@r{ a b@: \ @: @: 2 @:idiv@:(a,b) a\b}
35758@r{ a b@: : @: @: 2 @:fdiv@:(a,b)}
35759@r{ a b@: | @: @: 2 @:vconcat@:(a,b) a|b}
35760@r{ a b@: I | @: @: @:vconcat@:(b,a) b|a}
35761@r{ a b@: H | @: @: 2 @:append@:(a,b)}
35762@r{ a b@: I H | @: @: @:append@:(b,a)}
35763@r{ a@: & @: @: 1 @:inv@:(a) 1/a}
35764@r{ a@: ! @: @: 1 @:fact@:(a) a!}
35765@r{ a@: = @: @: 1 @:evalv@:(a)}
35766@r{ a@: M-% @: @: @:percent@:(a) a%}
35767
35768@c
8dc6104d
JB
35769@r{ ... a@: @summarykey{RET} @: @: 1 @:@:... a a}
35770@r{ ... a@: @summarykey{SPC} @: @: 1 @:@:... a a}
35771@r{... a b@: @summarykey{TAB} @: @: 3 @:@:... b a}
35772@r{. a b c@: M-@summarykey{TAB} @: @: 3 @:@:... b c a}
35773@r{... a b@: @summarykey{LFD} @: @: 1 @:@:... a b a}
35774@r{ ... a@: @summarykey{DEL} @: @: 1 @:@:...}
35775@r{... a b@: M-@summarykey{DEL} @: @: 1 @:@:... b}
35776@r{ @: M-@summarykey{RET} @: @: 4 @:calc-last-args@:}
4009494e
GM
35777@r{ a@: ` @:editing @: 1,30 @:calc-edit@:}
35778
35779@c
35780@r{ ... a@: C-d @: @: 1 @:@:...}
35781@r{ @: C-k @: @: 27 @:calc-kill@:}
35782@r{ @: C-w @: @: 27 @:calc-kill-region@:}
35783@r{ @: C-y @: @: @:calc-yank@:}
35784@r{ @: C-_ @: @: 4 @:calc-undo@:}
35785@r{ @: M-k @: @: 27 @:calc-copy-as-kill@:}
35786@r{ @: M-w @: @: 27 @:calc-copy-region-as-kill@:}
35787
35788@c
35789@r{ @: [ @: @: @:@:[...}
35790@r{[.. a b@: ] @: @: @:@:[a,b]}
35791@r{ @: ( @: @: @:@:(...}
35792@r{(.. a b@: ) @: @: @:@:(a,b)}
35793@r{ @: , @: @: @:@:vector or rect complex}
35794@r{ @: ; @: @: @:@:matrix or polar complex}
35795@r{ @: .. @: @: @:@:interval}
35796
35797@c
35798@r{ @: ~ @: @: @:calc-num-prefix@:}
35799@r{ @: < @: @: 4 @:calc-scroll-left@:}
35800@r{ @: > @: @: 4 @:calc-scroll-right@:}
35801@r{ @: @{ @: @: 4 @:calc-scroll-down@:}
35802@r{ @: @} @: @: 4 @:calc-scroll-up@:}
35803@r{ @: ? @: @: @:calc-help@:}
35804
35805@c
35806@r{ a@: n @: @: 1 @:neg@:(a) @minus{}a}
35807@r{ @: o @: @: 4 @:calc-realign@:}
35808@r{ @: p @:precision @: 31 @:calc-precision@:}
35809@r{ @: q @: @: @:calc-quit@:}
35810@r{ @: w @: @: @:calc-why@:}
35811@r{ @: x @:command @: @:M-x calc-@:command}
35812@r{ a@: y @: @:1,28,49 @:calc-copy-to-buffer@:}
35813
35814@c
35815@r{ a@: A @: @: 1 @:abs@:(a)}
35816@r{ a b@: B @: @: 2 @:log@:(a,b)}
35817@r{ a b@: I B @: @: 2 @:alog@:(a,b) b^a}
35818@r{ a@: C @: @: 1 @:cos@:(a)}
35819@r{ a@: I C @: @: 1 @:arccos@:(a)}
35820@r{ a@: H C @: @: 1 @:cosh@:(a)}
35821@r{ a@: I H C @: @: 1 @:arccosh@:(a)}
35822@r{ @: D @: @: 4 @:calc-redo@:}
35823@r{ a@: E @: @: 1 @:exp@:(a)}
35824@r{ a@: H E @: @: 1 @:exp10@:(a) 10.^a}
35825@r{ a@: F @: @: 1,11 @:floor@:(a,d)}
35826@r{ a@: I F @: @: 1,11 @:ceil@:(a,d)}
35827@r{ a@: H F @: @: 1,11 @:ffloor@:(a,d)}
35828@r{ a@: I H F @: @: 1,11 @:fceil@:(a,d)}
35829@r{ a@: G @: @: 1 @:arg@:(a)}
35830@r{ @: H @:command @: 32 @:@:Hyperbolic}
35831@r{ @: I @:command @: 32 @:@:Inverse}
35832@r{ a@: J @: @: 1 @:conj@:(a)}
35833@r{ @: K @:command @: 32 @:@:Keep-args}
35834@r{ a@: L @: @: 1 @:ln@:(a)}
35835@r{ a@: H L @: @: 1 @:log10@:(a)}
35836@r{ @: M @: @: @:calc-more-recursion-depth@:}
35837@r{ @: I M @: @: @:calc-less-recursion-depth@:}
35838@r{ a@: N @: @: 5 @:evalvn@:(a)}
f8b91752 35839@r{ @: O @:command @: 32 @:@:Option}
4009494e
GM
35840@r{ @: P @: @: @:@:pi}
35841@r{ @: I P @: @: @:@:gamma}
35842@r{ @: H P @: @: @:@:e}
35843@r{ @: I H P @: @: @:@:phi}
35844@r{ a@: Q @: @: 1 @:sqrt@:(a)}
35845@r{ a@: I Q @: @: 1 @:sqr@:(a) a^2}
35846@r{ a@: R @: @: 1,11 @:round@:(a,d)}
35847@r{ a@: I R @: @: 1,11 @:trunc@:(a,d)}
35848@r{ a@: H R @: @: 1,11 @:fround@:(a,d)}
35849@r{ a@: I H R @: @: 1,11 @:ftrunc@:(a,d)}
35850@r{ a@: S @: @: 1 @:sin@:(a)}
35851@r{ a@: I S @: @: 1 @:arcsin@:(a)}
35852@r{ a@: H S @: @: 1 @:sinh@:(a)}
35853@r{ a@: I H S @: @: 1 @:arcsinh@:(a)}
35854@r{ a@: T @: @: 1 @:tan@:(a)}
35855@r{ a@: I T @: @: 1 @:arctan@:(a)}
35856@r{ a@: H T @: @: 1 @:tanh@:(a)}
35857@r{ a@: I H T @: @: 1 @:arctanh@:(a)}
35858@r{ @: U @: @: 4 @:calc-undo@:}
35859@r{ @: X @: @: 4 @:calc-call-last-kbd-macro@:}
35860
35861@c
35862@r{ a b@: a = @: @: 2 @:eq@:(a,b) a=b}
35863@r{ a b@: a # @: @: 2 @:neq@:(a,b) a!=b}
35864@r{ a b@: a < @: @: 2 @:lt@:(a,b) a<b}
35865@r{ a b@: a > @: @: 2 @:gt@:(a,b) a>b}
35866@r{ a b@: a [ @: @: 2 @:leq@:(a,b) a<=b}
35867@r{ a b@: a ] @: @: 2 @:geq@:(a,b) a>=b}
35868@r{ a b@: a @{ @: @: 2 @:in@:(a,b)}
35869@r{ a b@: a & @: @: 2,45 @:land@:(a,b) a&&b}
35870@r{ a b@: a | @: @: 2,45 @:lor@:(a,b) a||b}
35871@r{ a@: a ! @: @: 1,45 @:lnot@:(a) !a}
35872@r{ a b c@: a : @: @: 45 @:if@:(a,b,c) a?b:c}
35873@r{ a@: a . @: @: 1 @:rmeq@:(a)}
35874@r{ a@: a " @: @: 7,8 @:calc-expand-formula@:}
35875
35876@c
35877@r{ a@: a + @:i, l, h @: 6,38 @:sum@:(a,i,l,h)}
35878@r{ a@: a - @:i, l, h @: 6,38 @:asum@:(a,i,l,h)}
35879@r{ a@: a * @:i, l, h @: 6,38 @:prod@:(a,i,l,h)}
35880@r{ a b@: a _ @: @: 2 @:subscr@:(a,b) a_b}
35881
35882@c
35883@r{ a b@: a \ @: @: 2 @:pdiv@:(a,b)}
35884@r{ a b@: a % @: @: 2 @:prem@:(a,b)}
35885@r{ a b@: a / @: @: 2 @:pdivrem@:(a,b) [q,r]}
35886@r{ a b@: H a / @: @: 2 @:pdivide@:(a,b) q+r/b}
35887
35888@c
35889@r{ a@: a a @: @: 1 @:apart@:(a)}
35890@r{ a@: a b @:old, new @: 38 @:subst@:(a,old,new)}
35891@r{ a@: a c @:v @: 38 @:collect@:(a,v)}
35892@r{ a@: a d @:v @: 4,38 @:deriv@:(a,v)}
35893@r{ a@: H a d @:v @: 4,38 @:tderiv@:(a,v)}
35894@r{ a@: a e @: @: @:esimplify@:(a)}
35895@r{ a@: a f @: @: 1 @:factor@:(a)}
35896@r{ a@: H a f @: @: 1 @:factors@:(a)}
35897@r{ a b@: a g @: @: 2 @:pgcd@:(a,b)}
35898@r{ a@: a i @:v @: 38 @:integ@:(a,v)}
35899@r{ a@: a m @:pats @: 38 @:match@:(a,pats)}
35900@r{ a@: I a m @:pats @: 38 @:matchnot@:(a,pats)}
35901@r{ data x@: a p @: @: 28 @:polint@:(data,x)}
35902@r{ data x@: H a p @: @: 28 @:ratint@:(data,x)}
35903@r{ a@: a n @: @: 1 @:nrat@:(a)}
35904@r{ a@: a r @:rules @:4,8,38 @:rewrite@:(a,rules,n)}
35905@r{ a@: a s @: @: @:simplify@:(a)}
35906@r{ a@: a t @:v, n @: 31,39 @:taylor@:(a,v,n)}
35907@r{ a@: a v @: @: 7,8 @:calc-alg-evaluate@:}
35908@r{ a@: a x @: @: 4,8 @:expand@:(a)}
35909
35910@c
35911@r{ data@: a F @:model, vars @: 48 @:fit@:(m,iv,pv,data)}
35912@r{ data@: I a F @:model, vars @: 48 @:xfit@:(m,iv,pv,data)}
35913@r{ data@: H a F @:model, vars @: 48 @:efit@:(m,iv,pv,data)}
35914@r{ a@: a I @:v, l, h @: 38 @:ninteg@:(a,v,l,h)}
35915@r{ a b@: a M @:op @: 22 @:mapeq@:(op,a,b)}
35916@r{ a b@: I a M @:op @: 22 @:mapeqr@:(op,a,b)}
35917@r{ a b@: H a M @:op @: 22 @:mapeqp@:(op,a,b)}
35918@r{ a g@: a N @:v @: 38 @:minimize@:(a,v,g)}
35919@r{ a g@: H a N @:v @: 38 @:wminimize@:(a,v,g)}
35920@r{ a@: a P @:v @: 38 @:roots@:(a,v)}
35921@r{ a g@: a R @:v @: 38 @:root@:(a,v,g)}
35922@r{ a g@: H a R @:v @: 38 @:wroot@:(a,v,g)}
35923@r{ a@: a S @:v @: 38 @:solve@:(a,v)}
35924@r{ a@: I a S @:v @: 38 @:finv@:(a,v)}
35925@r{ a@: H a S @:v @: 38 @:fsolve@:(a,v)}
35926@r{ a@: I H a S @:v @: 38 @:ffinv@:(a,v)}
35927@r{ a@: a T @:i, l, h @: 6,38 @:table@:(a,i,l,h)}
35928@r{ a g@: a X @:v @: 38 @:maximize@:(a,v,g)}
35929@r{ a g@: H a X @:v @: 38 @:wmaximize@:(a,v,g)}
35930
35931@c
35932@r{ a b@: b a @: @: 9 @:and@:(a,b,w)}
35933@r{ a@: b c @: @: 9 @:clip@:(a,w)}
35934@r{ a b@: b d @: @: 9 @:diff@:(a,b,w)}
35935@r{ a@: b l @: @: 10 @:lsh@:(a,n,w)}
35936@r{ a n@: H b l @: @: 9 @:lsh@:(a,n,w)}
35937@r{ a@: b n @: @: 9 @:not@:(a,w)}
35938@r{ a b@: b o @: @: 9 @:or@:(a,b,w)}
35939@r{ v@: b p @: @: 1 @:vpack@:(v)}
35940@r{ a@: b r @: @: 10 @:rsh@:(a,n,w)}
35941@r{ a n@: H b r @: @: 9 @:rsh@:(a,n,w)}
35942@r{ a@: b t @: @: 10 @:rot@:(a,n,w)}
35943@r{ a n@: H b t @: @: 9 @:rot@:(a,n,w)}
35944@r{ a@: b u @: @: 1 @:vunpack@:(a)}
35945@r{ @: b w @:w @: 9,50 @:calc-word-size@:}
35946@r{ a b@: b x @: @: 9 @:xor@:(a,b,w)}
35947
35948@c
35949@r{c s l p@: b D @: @: @:ddb@:(c,s,l,p)}
35950@r{ r n p@: b F @: @: @:fv@:(r,n,p)}
35951@r{ r n p@: I b F @: @: @:fvb@:(r,n,p)}
35952@r{ r n p@: H b F @: @: @:fvl@:(r,n,p)}
35953@r{ v@: b I @: @: 19 @:irr@:(v)}
35954@r{ v@: I b I @: @: 19 @:irrb@:(v)}
35955@r{ a@: b L @: @: 10 @:ash@:(a,n,w)}
35956@r{ a n@: H b L @: @: 9 @:ash@:(a,n,w)}
35957@r{ r n a@: b M @: @: @:pmt@:(r,n,a)}
35958@r{ r n a@: I b M @: @: @:pmtb@:(r,n,a)}
35959@r{ r n a@: H b M @: @: @:pmtl@:(r,n,a)}
35960@r{ r v@: b N @: @: 19 @:npv@:(r,v)}
35961@r{ r v@: I b N @: @: 19 @:npvb@:(r,v)}
35962@r{ r n p@: b P @: @: @:pv@:(r,n,p)}
35963@r{ r n p@: I b P @: @: @:pvb@:(r,n,p)}
35964@r{ r n p@: H b P @: @: @:pvl@:(r,n,p)}
35965@r{ a@: b R @: @: 10 @:rash@:(a,n,w)}
35966@r{ a n@: H b R @: @: 9 @:rash@:(a,n,w)}
35967@r{ c s l@: b S @: @: @:sln@:(c,s,l)}
35968@r{ n p a@: b T @: @: @:rate@:(n,p,a)}
35969@r{ n p a@: I b T @: @: @:rateb@:(n,p,a)}
35970@r{ n p a@: H b T @: @: @:ratel@:(n,p,a)}
35971@r{c s l p@: b Y @: @: @:syd@:(c,s,l,p)}
35972
35973@r{ r p a@: b # @: @: @:nper@:(r,p,a)}
35974@r{ r p a@: I b # @: @: @:nperb@:(r,p,a)}
35975@r{ r p a@: H b # @: @: @:nperl@:(r,p,a)}
35976@r{ a b@: b % @: @: @:relch@:(a,b)}
35977
35978@c
35979@r{ a@: c c @: @: 5 @:pclean@:(a,p)}
35980@r{ a@: c 0-9 @: @: @:pclean@:(a,p)}
35981@r{ a@: H c c @: @: 5 @:clean@:(a,p)}
35982@r{ a@: H c 0-9 @: @: @:clean@:(a,p)}
35983@r{ a@: c d @: @: 1 @:deg@:(a)}
35984@r{ a@: c f @: @: 1 @:pfloat@:(a)}
35985@r{ a@: H c f @: @: 1 @:float@:(a)}
35986@r{ a@: c h @: @: 1 @:hms@:(a)}
35987@r{ a@: c p @: @: @:polar@:(a)}
35988@r{ a@: I c p @: @: @:rect@:(a)}
35989@r{ a@: c r @: @: 1 @:rad@:(a)}
35990
35991@c
35992@r{ a@: c F @: @: 5 @:pfrac@:(a,p)}
35993@r{ a@: H c F @: @: 5 @:frac@:(a,p)}
35994
35995@c
35996@r{ a@: c % @: @: @:percent@:(a*100)}
35997
35998@c
35999@r{ @: d . @:char @: 50 @:calc-point-char@:}
36000@r{ @: d , @:char @: 50 @:calc-group-char@:}
36001@r{ @: d < @: @: 13,50 @:calc-left-justify@:}
36002@r{ @: d = @: @: 13,50 @:calc-center-justify@:}
36003@r{ @: d > @: @: 13,50 @:calc-right-justify@:}
36004@r{ @: d @{ @:label @: 50 @:calc-left-label@:}
36005@r{ @: d @} @:label @: 50 @:calc-right-label@:}
36006@r{ @: d [ @: @: 4 @:calc-truncate-up@:}
36007@r{ @: d ] @: @: 4 @:calc-truncate-down@:}
36008@r{ @: d " @: @: 12,50 @:calc-display-strings@:}
8dc6104d
JB
36009@r{ @: d @summarykey{SPC} @: @: @:calc-refresh@:}
36010@r{ @: d @summarykey{RET} @: @: 1 @:calc-refresh-top@:}
4009494e
GM
36011
36012@c
36013@r{ @: d 0 @: @: 50 @:calc-decimal-radix@:}
36014@r{ @: d 2 @: @: 50 @:calc-binary-radix@:}
36015@r{ @: d 6 @: @: 50 @:calc-hex-radix@:}
36016@r{ @: d 8 @: @: 50 @:calc-octal-radix@:}
36017
36018@c
36019@r{ @: d b @: @:12,13,50 @:calc-line-breaking@:}
36020@r{ @: d c @: @: 50 @:calc-complex-notation@:}
36021@r{ @: d d @:format @: 50 @:calc-date-notation@:}
36022@r{ @: d e @: @: 5,50 @:calc-eng-notation@:}
36023@r{ @: d f @:num @: 31,50 @:calc-fix-notation@:}
36024@r{ @: d g @: @:12,13,50 @:calc-group-digits@:}
36025@r{ @: d h @:format @: 50 @:calc-hms-notation@:}
36026@r{ @: d i @: @: 50 @:calc-i-notation@:}
36027@r{ @: d j @: @: 50 @:calc-j-notation@:}
36028@r{ @: d l @: @: 12,50 @:calc-line-numbering@:}
36029@r{ @: d n @: @: 5,50 @:calc-normal-notation@:}
36030@r{ @: d o @:format @: 50 @:calc-over-notation@:}
36031@r{ @: d p @: @: 12,50 @:calc-show-plain@:}
36032@r{ @: d r @:radix @: 31,50 @:calc-radix@:}
36033@r{ @: d s @: @: 5,50 @:calc-sci-notation@:}
36034@r{ @: d t @: @: 27 @:calc-truncate-stack@:}
36035@r{ @: d w @: @: 12,13 @:calc-auto-why@:}
36036@r{ @: d z @: @: 12,50 @:calc-leading-zeros@:}
36037
36038@c
36039@r{ @: d B @: @: 50 @:calc-big-language@:}
36040@r{ @: d C @: @: 50 @:calc-c-language@:}
36041@r{ @: d E @: @: 50 @:calc-eqn-language@:}
36042@r{ @: d F @: @: 50 @:calc-fortran-language@:}
36043@r{ @: d M @: @: 50 @:calc-mathematica-language@:}
36044@r{ @: d N @: @: 50 @:calc-normal-language@:}
36045@r{ @: d O @: @: 50 @:calc-flat-language@:}
36046@r{ @: d P @: @: 50 @:calc-pascal-language@:}
36047@r{ @: d T @: @: 50 @:calc-tex-language@:}
36048@r{ @: d L @: @: 50 @:calc-latex-language@:}
36049@r{ @: d U @: @: 50 @:calc-unformatted-language@:}
36050@r{ @: d W @: @: 50 @:calc-maple-language@:}
36051
36052@c
36053@r{ a@: f [ @: @: 4 @:decr@:(a,n)}
36054@r{ a@: f ] @: @: 4 @:incr@:(a,n)}
36055
36056@c
36057@r{ a b@: f b @: @: 2 @:beta@:(a,b)}
36058@r{ a@: f e @: @: 1 @:erf@:(a)}
36059@r{ a@: I f e @: @: 1 @:erfc@:(a)}
36060@r{ a@: f g @: @: 1 @:gamma@:(a)}
36061@r{ a b@: f h @: @: 2 @:hypot@:(a,b)}
36062@r{ a@: f i @: @: 1 @:im@:(a)}
36063@r{ n a@: f j @: @: 2 @:besJ@:(n,a)}
36064@r{ a b@: f n @: @: 2 @:min@:(a,b)}
36065@r{ a@: f r @: @: 1 @:re@:(a)}
36066@r{ a@: f s @: @: 1 @:sign@:(a)}
36067@r{ a b@: f x @: @: 2 @:max@:(a,b)}
36068@r{ n a@: f y @: @: 2 @:besY@:(n,a)}
36069
36070@c
36071@r{ a@: f A @: @: 1 @:abssqr@:(a)}
36072@r{ x a b@: f B @: @: @:betaI@:(x,a,b)}
36073@r{ x a b@: H f B @: @: @:betaB@:(x,a,b)}
36074@r{ a@: f E @: @: 1 @:expm1@:(a)}
36075@r{ a x@: f G @: @: 2 @:gammaP@:(a,x)}
36076@r{ a x@: I f G @: @: 2 @:gammaQ@:(a,x)}
36077@r{ a x@: H f G @: @: 2 @:gammag@:(a,x)}
36078@r{ a x@: I H f G @: @: 2 @:gammaG@:(a,x)}
36079@r{ a b@: f I @: @: 2 @:ilog@:(a,b)}
36080@r{ a b@: I f I @: @: 2 @:alog@:(a,b) b^a}
36081@r{ a@: f L @: @: 1 @:lnp1@:(a)}
36082@r{ a@: f M @: @: 1 @:mant@:(a)}
36083@r{ a@: f Q @: @: 1 @:isqrt@:(a)}
36084@r{ a@: I f Q @: @: 1 @:sqr@:(a) a^2}
36085@r{ a n@: f S @: @: 2 @:scf@:(a,n)}
36086@r{ y x@: f T @: @: @:arctan2@:(y,x)}
36087@r{ a@: f X @: @: 1 @:xpon@:(a)}
36088
36089@c
36090@r{ x y@: g a @: @: 28,40 @:calc-graph-add@:}
36091@r{ @: g b @: @: 12 @:calc-graph-border@:}
36092@r{ @: g c @: @: @:calc-graph-clear@:}
36093@r{ @: g d @: @: 41 @:calc-graph-delete@:}
36094@r{ x y@: g f @: @: 28,40 @:calc-graph-fast@:}
36095@r{ @: g g @: @: 12 @:calc-graph-grid@:}
36096@r{ @: g h @:title @: @:calc-graph-header@:}
36097@r{ @: g j @: @: 4 @:calc-graph-juggle@:}
36098@r{ @: g k @: @: 12 @:calc-graph-key@:}
36099@r{ @: g l @: @: 12 @:calc-graph-log-x@:}
36100@r{ @: g n @:name @: @:calc-graph-name@:}
36101@r{ @: g p @: @: 42 @:calc-graph-plot@:}
36102@r{ @: g q @: @: @:calc-graph-quit@:}
36103@r{ @: g r @:range @: @:calc-graph-range-x@:}
36104@r{ @: g s @: @: 12,13 @:calc-graph-line-style@:}
36105@r{ @: g t @:title @: @:calc-graph-title-x@:}
36106@r{ @: g v @: @: @:calc-graph-view-commands@:}
36107@r{ @: g x @:display @: @:calc-graph-display@:}
36108@r{ @: g z @: @: 12 @:calc-graph-zero-x@:}
36109
36110@c
36111@r{ x y z@: g A @: @: 28,40 @:calc-graph-add-3d@:}
36112@r{ @: g C @:command @: @:calc-graph-command@:}
36113@r{ @: g D @:device @: 43,44 @:calc-graph-device@:}
36114@r{ x y z@: g F @: @: 28,40 @:calc-graph-fast-3d@:}
36115@r{ @: g H @: @: 12 @:calc-graph-hide@:}
36116@r{ @: g K @: @: @:calc-graph-kill@:}
36117@r{ @: g L @: @: 12 @:calc-graph-log-y@:}
36118@r{ @: g N @:number @: 43,51 @:calc-graph-num-points@:}
36119@r{ @: g O @:filename @: 43,44 @:calc-graph-output@:}
36120@r{ @: g P @: @: 42 @:calc-graph-print@:}
36121@r{ @: g R @:range @: @:calc-graph-range-y@:}
36122@r{ @: g S @: @: 12,13 @:calc-graph-point-style@:}
36123@r{ @: g T @:title @: @:calc-graph-title-y@:}
36124@r{ @: g V @: @: @:calc-graph-view-trail@:}
36125@r{ @: g X @:format @: @:calc-graph-geometry@:}
36126@r{ @: g Z @: @: 12 @:calc-graph-zero-y@:}
36127
36128@c
36129@r{ @: g C-l @: @: 12 @:calc-graph-log-z@:}
36130@r{ @: g C-r @:range @: @:calc-graph-range-z@:}
36131@r{ @: g C-t @:title @: @:calc-graph-title-z@:}
36132
36133@c
36134@r{ @: h b @: @: @:calc-describe-bindings@:}
36135@r{ @: h c @:key @: @:calc-describe-key-briefly@:}
36136@r{ @: h f @:function @: @:calc-describe-function@:}
36137@r{ @: h h @: @: @:calc-full-help@:}
36138@r{ @: h i @: @: @:calc-info@:}
36139@r{ @: h k @:key @: @:calc-describe-key@:}
36140@r{ @: h n @: @: @:calc-view-news@:}
36141@r{ @: h s @: @: @:calc-info-summary@:}
36142@r{ @: h t @: @: @:calc-tutorial@:}
36143@r{ @: h v @:var @: @:calc-describe-variable@:}
36144
36145@c
36146@r{ @: j 1-9 @: @: @:calc-select-part@:}
8dc6104d
JB
36147@r{ @: j @summarykey{RET} @: @: 27 @:calc-copy-selection@:}
36148@r{ @: j @summarykey{DEL} @: @: 27 @:calc-del-selection@:}
4009494e
GM
36149@r{ @: j ' @:formula @: 27 @:calc-enter-selection@:}
36150@r{ @: j ` @:editing @: 27,30 @:calc-edit-selection@:}
36151@r{ @: j " @: @: 7,27 @:calc-sel-expand-formula@:}
36152
36153@c
36154@r{ @: j + @:formula @: 27 @:calc-sel-add-both-sides@:}
36155@r{ @: j - @:formula @: 27 @:calc-sel-sub-both-sides@:}
36156@r{ @: j * @:formula @: 27 @:calc-sel-mul-both-sides@:}
36157@r{ @: j / @:formula @: 27 @:calc-sel-div-both-sides@:}
36158@r{ @: j & @: @: 27 @:calc-sel-invert@:}
36159
36160@c
36161@r{ @: j a @: @: 27 @:calc-select-additional@:}
36162@r{ @: j b @: @: 12 @:calc-break-selections@:}
36163@r{ @: j c @: @: @:calc-clear-selections@:}
36164@r{ @: j d @: @: 12,50 @:calc-show-selections@:}
36165@r{ @: j e @: @: 12 @:calc-enable-selections@:}
36166@r{ @: j l @: @: 4,27 @:calc-select-less@:}
36167@r{ @: j m @: @: 4,27 @:calc-select-more@:}
36168@r{ @: j n @: @: 4 @:calc-select-next@:}
36169@r{ @: j o @: @: 4,27 @:calc-select-once@:}
36170@r{ @: j p @: @: 4 @:calc-select-previous@:}
36171@r{ @: j r @:rules @:4,8,27 @:calc-rewrite-selection@:}
36172@r{ @: j s @: @: 4,27 @:calc-select-here@:}
36173@r{ @: j u @: @: 27 @:calc-unselect@:}
36174@r{ @: j v @: @: 7,27 @:calc-sel-evaluate@:}
36175
36176@c
36177@r{ @: j C @: @: 27 @:calc-sel-commute@:}
36178@r{ @: j D @: @: 4,27 @:calc-sel-distribute@:}
36179@r{ @: j E @: @: 27 @:calc-sel-jump-equals@:}
36180@r{ @: j I @: @: 27 @:calc-sel-isolate@:}
36181@r{ @: H j I @: @: 27 @:calc-sel-isolate@: (full)}
36182@r{ @: j L @: @: 4,27 @:calc-commute-left@:}
36183@r{ @: j M @: @: 27 @:calc-sel-merge@:}
36184@r{ @: j N @: @: 27 @:calc-sel-negate@:}
36185@r{ @: j O @: @: 4,27 @:calc-select-once-maybe@:}
36186@r{ @: j R @: @: 4,27 @:calc-commute-right@:}
36187@r{ @: j S @: @: 4,27 @:calc-select-here-maybe@:}
36188@r{ @: j U @: @: 27 @:calc-sel-unpack@:}
36189
36190@c
36191@r{ @: k a @: @: @:calc-random-again@:}
36192@r{ n@: k b @: @: 1 @:bern@:(n)}
36193@r{ n x@: H k b @: @: 2 @:bern@:(n,x)}
36194@r{ n m@: k c @: @: 2 @:choose@:(n,m)}
36195@r{ n m@: H k c @: @: 2 @:perm@:(n,m)}
36196@r{ n@: k d @: @: 1 @:dfact@:(n) n!!}
36197@r{ n@: k e @: @: 1 @:euler@:(n)}
36198@r{ n x@: H k e @: @: 2 @:euler@:(n,x)}
36199@r{ n@: k f @: @: 4 @:prfac@:(n)}
36200@r{ n m@: k g @: @: 2 @:gcd@:(n,m)}
36201@r{ m n@: k h @: @: 14 @:shuffle@:(n,m)}
36202@r{ n m@: k l @: @: 2 @:lcm@:(n,m)}
36203@r{ n@: k m @: @: 1 @:moebius@:(n)}
36204@r{ n@: k n @: @: 4 @:nextprime@:(n)}
36205@r{ n@: I k n @: @: 4 @:prevprime@:(n)}
36206@r{ n@: k p @: @: 4,28 @:calc-prime-test@:}
36207@r{ m@: k r @: @: 14 @:random@:(m)}
36208@r{ n m@: k s @: @: 2 @:stir1@:(n,m)}
36209@r{ n m@: H k s @: @: 2 @:stir2@:(n,m)}
36210@r{ n@: k t @: @: 1 @:totient@:(n)}
36211
36212@c
36213@r{ n p x@: k B @: @: @:utpb@:(x,n,p)}
36214@r{ n p x@: I k B @: @: @:ltpb@:(x,n,p)}
36215@r{ v x@: k C @: @: @:utpc@:(x,v)}
36216@r{ v x@: I k C @: @: @:ltpc@:(x,v)}
36217@r{ n m@: k E @: @: @:egcd@:(n,m)}
36218@r{v1 v2 x@: k F @: @: @:utpf@:(x,v1,v2)}
36219@r{v1 v2 x@: I k F @: @: @:ltpf@:(x,v1,v2)}
36220@r{ m s x@: k N @: @: @:utpn@:(x,m,s)}
36221@r{ m s x@: I k N @: @: @:ltpn@:(x,m,s)}
36222@r{ m x@: k P @: @: @:utpp@:(x,m)}
36223@r{ m x@: I k P @: @: @:ltpp@:(x,m)}
36224@r{ v x@: k T @: @: @:utpt@:(x,v)}
36225@r{ v x@: I k T @: @: @:ltpt@:(x,v)}
36226
2e78df6b 36227@c
d71990a1
JB
36228@r{ a b@: l + @: @: @:lupadd@:(a,b)}
36229@r{ a b@: H l + @: @: @:lufadd@:(a,b)}
36230@r{ a b@: l - @: @: @:lupsub@:(a,b)}
36231@r{ a b@: H l - @: @: @:lufsub@:(a,b)}
36232@r{ a b@: l * @: @: @:lupmul@:(a,b)}
36233@r{ a b@: H l * @: @: @:lufmul@:(a,b)}
36234@r{ a b@: l / @: @: @:lupdiv@:(a,b)}
36235@r{ a b@: H l / @: @: @:lufdiv@:(a,b)}
36236@r{ a@: l d @: @: @:dbpower@:(a)}
36237@r{ a b@: O l d @: @: @:dbpower@:(a,b)}
36238@r{ a@: H l d @: @: @:dbfield@:(a)}
36239@r{ a b@: O H l d @: @: @:dbfield@:(a,b)}
36240@r{ a@: l n @: @: @:nppower@:(a)}
36241@r{ a b@: O l n @: @: @:nppower@:(a,b)}
36242@r{ a@: H l n @: @: @:npfield@:(a)}
36243@r{ a b@: O H l n @: @: @:npfield@:(a,b)}
580b66d8
JB
36244@r{ a@: l q @: @: @:lupquant@:(a)}
36245@r{ a b@: O l q @: @: @:lupquant@:(a,b)}
36246@r{ a@: H l q @: @: @:lufquant@:(a)}
36247@r{ a b@: O H l q @: @: @:lufquant@:(a,b)}
05a29101
JB
36248@r{ a@: l s @: @: @:spn@:(a)}
36249@r{ a@: l m @: @: @:midi@:(a)}
36250@r{ a@: l f @: @: @:freq@:(a)}
2e78df6b 36251
4009494e
GM
36252@c
36253@r{ @: m a @: @: 12,13 @:calc-algebraic-mode@:}
36254@r{ @: m d @: @: @:calc-degrees-mode@:}
36255@r{ @: m e @: @: @:calc-embedded-preserve-modes@:}
36256@r{ @: m f @: @: 12 @:calc-frac-mode@:}
36257@r{ @: m g @: @: 52 @:calc-get-modes@:}
36258@r{ @: m h @: @: @:calc-hms-mode@:}
36259@r{ @: m i @: @: 12,13 @:calc-infinite-mode@:}
36260@r{ @: m m @: @: @:calc-save-modes@:}
36261@r{ @: m p @: @: 12 @:calc-polar-mode@:}
36262@r{ @: m r @: @: @:calc-radians-mode@:}
36263@r{ @: m s @: @: 12 @:calc-symbolic-mode@:}
36264@r{ @: m t @: @: 12 @:calc-total-algebraic-mode@:}
36265@r{ @: m v @: @: 12,13 @:calc-matrix-mode@:}
36266@r{ @: m w @: @: 13 @:calc-working@:}
36267@r{ @: m x @: @: @:calc-always-load-extensions@:}
36268
36269@c
36270@r{ @: m A @: @: 12 @:calc-alg-simplify-mode@:}
36271@r{ @: m B @: @: 12 @:calc-bin-simplify-mode@:}
36272@r{ @: m C @: @: 12 @:calc-auto-recompute@:}
36273@r{ @: m D @: @: @:calc-default-simplify-mode@:}
36274@r{ @: m E @: @: 12 @:calc-ext-simplify-mode@:}
36275@r{ @: m F @:filename @: 13 @:calc-settings-file-name@:}
36276@r{ @: m N @: @: 12 @:calc-num-simplify-mode@:}
36277@r{ @: m O @: @: 12 @:calc-no-simplify-mode@:}
36278@r{ @: m R @: @: 12,13 @:calc-mode-record-mode@:}
36279@r{ @: m S @: @: 12 @:calc-shift-prefix@:}
36280@r{ @: m U @: @: 12 @:calc-units-simplify-mode@:}
36281
538c2573
JB
36282@c
36283@r{ @: r s @:register @: 27 @:calc-copy-to-register@:}
36284@r{ @: r i @:register @: @:calc-insert-register@:}
36285
4009494e
GM
36286@c
36287@r{ @: s c @:var1, var2 @: 29 @:calc-copy-variable@:}
36288@r{ @: s d @:var, decl @: @:calc-declare-variable@:}
36289@r{ @: s e @:var, editing @: 29,30 @:calc-edit-variable@:}
36290@r{ @: s i @:buffer @: @:calc-insert-variables@:}
36291@r{ @: s k @:const, var @: 29 @:calc-copy-special-constant@:}
36292@r{ a b@: s l @:var @: 29 @:@:a (letting var=b)}
36293@r{ a ...@: s m @:op, var @: 22,29 @:calc-store-map@:}
36294@r{ @: s n @:var @: 29,47 @:calc-store-neg@: (v/-1)}
36295@r{ @: s p @:var @: 29 @:calc-permanent-variable@:}
36296@r{ @: s r @:var @: 29 @:@:v (recalled value)}
36297@r{ @: r 0-9 @: @: @:calc-recall-quick@:}
36298@r{ a@: s s @:var @: 28,29 @:calc-store@:}
36299@r{ a@: s 0-9 @: @: @:calc-store-quick@:}
36300@r{ a@: s t @:var @: 29 @:calc-store-into@:}
36301@r{ a@: t 0-9 @: @: @:calc-store-into-quick@:}
36302@r{ @: s u @:var @: 29 @:calc-unstore@:}
36303@r{ a@: s x @:var @: 29 @:calc-store-exchange@:}
36304
36305@c
36306@r{ @: s A @:editing @: 30 @:calc-edit-AlgSimpRules@:}
36307@r{ @: s D @:editing @: 30 @:calc-edit-Decls@:}
36308@r{ @: s E @:editing @: 30 @:calc-edit-EvalRules@:}
36309@r{ @: s F @:editing @: 30 @:calc-edit-FitRules@:}
36310@r{ @: s G @:editing @: 30 @:calc-edit-GenCount@:}
36311@r{ @: s H @:editing @: 30 @:calc-edit-Holidays@:}
36312@r{ @: s I @:editing @: 30 @:calc-edit-IntegLimit@:}
36313@r{ @: s L @:editing @: 30 @:calc-edit-LineStyles@:}
36314@r{ @: s P @:editing @: 30 @:calc-edit-PointStyles@:}
36315@r{ @: s R @:editing @: 30 @:calc-edit-PlotRejects@:}
36316@r{ @: s T @:editing @: 30 @:calc-edit-TimeZone@:}
36317@r{ @: s U @:editing @: 30 @:calc-edit-Units@:}
36318@r{ @: s X @:editing @: 30 @:calc-edit-ExtSimpRules@:}
36319
36320@c
36321@r{ a@: s + @:var @: 29,47 @:calc-store-plus@: (v+a)}
36322@r{ a@: s - @:var @: 29,47 @:calc-store-minus@: (v-a)}
36323@r{ a@: s * @:var @: 29,47 @:calc-store-times@: (v*a)}
36324@r{ a@: s / @:var @: 29,47 @:calc-store-div@: (v/a)}
36325@r{ a@: s ^ @:var @: 29,47 @:calc-store-power@: (v^a)}
36326@r{ a@: s | @:var @: 29,47 @:calc-store-concat@: (v|a)}
36327@r{ @: s & @:var @: 29,47 @:calc-store-inv@: (v^-1)}
36328@r{ @: s [ @:var @: 29,47 @:calc-store-decr@: (v-1)}
36329@r{ @: s ] @:var @: 29,47 @:calc-store-incr@: (v-(-1))}
36330@r{ a b@: s : @: @: 2 @:assign@:(a,b) a @tfn{:=} b}
36331@r{ a@: s = @: @: 1 @:evalto@:(a,b) a @tfn{=>}}
36332
36333@c
36334@r{ @: t [ @: @: 4 @:calc-trail-first@:}
36335@r{ @: t ] @: @: 4 @:calc-trail-last@:}
36336@r{ @: t < @: @: 4 @:calc-trail-scroll-left@:}
36337@r{ @: t > @: @: 4 @:calc-trail-scroll-right@:}
36338@r{ @: t . @: @: 12 @:calc-full-trail-vectors@:}
36339
36340@c
36341@r{ @: t b @: @: 4 @:calc-trail-backward@:}
36342@r{ @: t d @: @: 12,50 @:calc-trail-display@:}
36343@r{ @: t f @: @: 4 @:calc-trail-forward@:}
36344@r{ @: t h @: @: @:calc-trail-here@:}
36345@r{ @: t i @: @: @:calc-trail-in@:}
36346@r{ @: t k @: @: 4 @:calc-trail-kill@:}
36347@r{ @: t m @:string @: @:calc-trail-marker@:}
36348@r{ @: t n @: @: 4 @:calc-trail-next@:}
36349@r{ @: t o @: @: @:calc-trail-out@:}
36350@r{ @: t p @: @: 4 @:calc-trail-previous@:}
36351@r{ @: t r @:string @: @:calc-trail-isearch-backward@:}
36352@r{ @: t s @:string @: @:calc-trail-isearch-forward@:}
36353@r{ @: t y @: @: 4 @:calc-trail-yank@:}
36354
36355@c
36356@r{ d@: t C @:oz, nz @: @:tzconv@:(d,oz,nz)}
36357@r{d oz nz@: t C @:$ @: @:tzconv@:(d,oz,nz)}
36358@r{ d@: t D @: @: 15 @:date@:(d)}
36359@r{ d@: t I @: @: 4 @:incmonth@:(d,n)}
36360@r{ d@: t J @: @: 16 @:julian@:(d,z)}
36361@r{ d@: t M @: @: 17 @:newmonth@:(d,n)}
36362@r{ @: t N @: @: 16 @:now@:(z)}
36363@r{ d@: t P @:1 @: 31 @:year@:(d)}
36364@r{ d@: t P @:2 @: 31 @:month@:(d)}
36365@r{ d@: t P @:3 @: 31 @:day@:(d)}
36366@r{ d@: t P @:4 @: 31 @:hour@:(d)}
36367@r{ d@: t P @:5 @: 31 @:minute@:(d)}
36368@r{ d@: t P @:6 @: 31 @:second@:(d)}
36369@r{ d@: t P @:7 @: 31 @:weekday@:(d)}
36370@r{ d@: t P @:8 @: 31 @:yearday@:(d)}
36371@r{ d@: t P @:9 @: 31 @:time@:(d)}
36372@r{ d@: t U @: @: 16 @:unixtime@:(d,z)}
36373@r{ d@: t W @: @: 17 @:newweek@:(d,w)}
36374@r{ d@: t Y @: @: 17 @:newyear@:(d,n)}
36375
36376@c
36377@r{ a b@: t + @: @: 2 @:badd@:(a,b)}
36378@r{ a b@: t - @: @: 2 @:bsub@:(a,b)}
36379
36380@c
36381@r{ @: u a @: @: 12 @:calc-autorange-units@:}
36382@r{ a@: u b @: @: @:calc-base-units@:}
36383@r{ a@: u c @:units @: 18 @:calc-convert-units@:}
36384@r{ defn@: u d @:unit, descr @: @:calc-define-unit@:}
36385@r{ @: u e @: @: @:calc-explain-units@:}
36386@r{ @: u g @:unit @: @:calc-get-unit-definition@:}
36387@r{ @: u p @: @: @:calc-permanent-units@:}
36388@r{ a@: u r @: @: @:calc-remove-units@:}
36389@r{ a@: u s @: @: @:usimplify@:(a)}
36390@r{ a@: u t @:units @: 18 @:calc-convert-temperature@:}
36391@r{ @: u u @:unit @: @:calc-undefine-unit@:}
36392@r{ @: u v @: @: @:calc-enter-units-table@:}
36393@r{ a@: u x @: @: @:calc-extract-units@:}
36394@r{ a@: u 0-9 @: @: @:calc-quick-units@:}
36395
36396@c
36397@r{ v1 v2@: u C @: @: 20 @:vcov@:(v1,v2)}
36398@r{ v1 v2@: I u C @: @: 20 @:vpcov@:(v1,v2)}
36399@r{ v1 v2@: H u C @: @: 20 @:vcorr@:(v1,v2)}
36400@r{ v@: u G @: @: 19 @:vgmean@:(v)}
36401@r{ a b@: H u G @: @: 2 @:agmean@:(a,b)}
36402@r{ v@: u M @: @: 19 @:vmean@:(v)}
36403@r{ v@: I u M @: @: 19 @:vmeane@:(v)}
36404@r{ v@: H u M @: @: 19 @:vmedian@:(v)}
36405@r{ v@: I H u M @: @: 19 @:vhmean@:(v)}
36406@r{ v@: u N @: @: 19 @:vmin@:(v)}
36407@r{ v@: u S @: @: 19 @:vsdev@:(v)}
36408@r{ v@: I u S @: @: 19 @:vpsdev@:(v)}
36409@r{ v@: H u S @: @: 19 @:vvar@:(v)}
36410@r{ v@: I H u S @: @: 19 @:vpvar@:(v)}
36411@r{ @: u V @: @: @:calc-view-units-table@:}
36412@r{ v@: u X @: @: 19 @:vmax@:(v)}
36413
36414@c
36415@r{ v@: u + @: @: 19 @:vsum@:(v)}
36416@r{ v@: u * @: @: 19 @:vprod@:(v)}
36417@r{ v@: u # @: @: 19 @:vcount@:(v)}
36418
36419@c
36420@r{ @: V ( @: @: 50 @:calc-vector-parens@:}
36421@r{ @: V @{ @: @: 50 @:calc-vector-braces@:}
36422@r{ @: V [ @: @: 50 @:calc-vector-brackets@:}
36423@r{ @: V ] @:ROCP @: 50 @:calc-matrix-brackets@:}
36424@r{ @: V , @: @: 50 @:calc-vector-commas@:}
36425@r{ @: V < @: @: 50 @:calc-matrix-left-justify@:}
36426@r{ @: V = @: @: 50 @:calc-matrix-center-justify@:}
36427@r{ @: V > @: @: 50 @:calc-matrix-right-justify@:}
36428@r{ @: V / @: @: 12,50 @:calc-break-vectors@:}
36429@r{ @: V . @: @: 12,50 @:calc-full-vectors@:}
36430
36431@c
36432@r{ s t@: V ^ @: @: 2 @:vint@:(s,t)}
36433@r{ s t@: V - @: @: 2 @:vdiff@:(s,t)}
36434@r{ s@: V ~ @: @: 1 @:vcompl@:(s)}
36435@r{ s@: V # @: @: 1 @:vcard@:(s)}
36436@r{ s@: V : @: @: 1 @:vspan@:(s)}
36437@r{ s@: V + @: @: 1 @:rdup@:(s)}
36438
36439@c
36440@r{ m@: V & @: @: 1 @:inv@:(m) 1/m}
36441
36442@c
36443@r{ v@: v a @:n @: @:arrange@:(v,n)}
36444@r{ a@: v b @:n @: @:cvec@:(a,n)}
36445@r{ v@: v c @:n >0 @: 21,31 @:mcol@:(v,n)}
36446@r{ v@: v c @:n <0 @: 31 @:mrcol@:(v,-n)}
36447@r{ m@: v c @:0 @: 31 @:getdiag@:(m)}
36448@r{ v@: v d @: @: 25 @:diag@:(v,n)}
36449@r{ v m@: v e @: @: 2 @:vexp@:(v,m)}
36450@r{ v m f@: H v e @: @: 2 @:vexp@:(v,m,f)}
36451@r{ v a@: v f @: @: 26 @:find@:(v,a,n)}
36452@r{ v@: v h @: @: 1 @:head@:(v)}
36453@r{ v@: I v h @: @: 1 @:tail@:(v)}
36454@r{ v@: H v h @: @: 1 @:rhead@:(v)}
36455@r{ v@: I H v h @: @: 1 @:rtail@:(v)}
36456@r{ @: v i @:n @: 31 @:idn@:(1,n)}
36457@r{ @: v i @:0 @: 31 @:idn@:(1)}
36458@r{ h t@: v k @: @: 2 @:cons@:(h,t)}
36459@r{ h t@: H v k @: @: 2 @:rcons@:(h,t)}
36460@r{ v@: v l @: @: 1 @:vlen@:(v)}
36461@r{ v@: H v l @: @: 1 @:mdims@:(v)}
36462@r{ v m@: v m @: @: 2 @:vmask@:(v,m)}
36463@r{ v@: v n @: @: 1 @:rnorm@:(v)}
36464@r{ a b c@: v p @: @: 24 @:calc-pack@:}
36465@r{ v@: v r @:n >0 @: 21,31 @:mrow@:(v,n)}
36466@r{ v@: v r @:n <0 @: 31 @:mrrow@:(v,-n)}
36467@r{ m@: v r @:0 @: 31 @:getdiag@:(m)}
36468@r{ v i j@: v s @: @: @:subvec@:(v,i,j)}
36469@r{ v i j@: I v s @: @: @:rsubvec@:(v,i,j)}
36470@r{ m@: v t @: @: 1 @:trn@:(m)}
36471@r{ v@: v u @: @: 24 @:calc-unpack@:}
36472@r{ v@: v v @: @: 1 @:rev@:(v)}
36473@r{ @: v x @:n @: 31 @:index@:(n)}
36474@r{ n s i@: C-u v x @: @: @:index@:(n,s,i)}
36475
36476@c
36477@r{ v@: V A @:op @: 22 @:apply@:(op,v)}
36478@r{ v1 v2@: V C @: @: 2 @:cross@:(v1,v2)}
36479@r{ m@: V D @: @: 1 @:det@:(m)}
36480@r{ s@: V E @: @: 1 @:venum@:(s)}
36481@r{ s@: V F @: @: 1 @:vfloor@:(s)}
36482@r{ v@: V G @: @: @:grade@:(v)}
36483@r{ v@: I V G @: @: @:rgrade@:(v)}
36484@r{ v@: V H @:n @: 31 @:histogram@:(v,n)}
36485@r{ v w@: H V H @:n @: 31 @:histogram@:(v,w,n)}
36486@r{ v1 v2@: V I @:mop aop @: 22 @:inner@:(mop,aop,v1,v2)}
36487@r{ m@: V J @: @: 1 @:ctrn@:(m)}
5a83c46e 36488@r{ m1 m2@: V K @: @: @:kron@:(m1,m2)}
4009494e
GM
36489@r{ m@: V L @: @: 1 @:lud@:(m)}
36490@r{ v@: V M @:op @: 22,23 @:map@:(op,v)}
36491@r{ v@: V N @: @: 1 @:cnorm@:(v)}
36492@r{ v1 v2@: V O @:op @: 22 @:outer@:(op,v1,v2)}
36493@r{ v@: V R @:op @: 22,23 @:reduce@:(op,v)}
36494@r{ v@: I V R @:op @: 22,23 @:rreduce@:(op,v)}
36495@r{ a n@: H V R @:op @: 22 @:nest@:(op,a,n)}
36496@r{ a@: I H V R @:op @: 22 @:fixp@:(op,a)}
36497@r{ v@: V S @: @: @:sort@:(v)}
36498@r{ v@: I V S @: @: @:rsort@:(v)}
36499@r{ m@: V T @: @: 1 @:tr@:(m)}
36500@r{ v@: V U @:op @: 22 @:accum@:(op,v)}
36501@r{ v@: I V U @:op @: 22 @:raccum@:(op,v)}
36502@r{ a n@: H V U @:op @: 22 @:anest@:(op,a,n)}
36503@r{ a@: I H V U @:op @: 22 @:afixp@:(op,a)}
36504@r{ s t@: V V @: @: 2 @:vunion@:(s,t)}
36505@r{ s t@: V X @: @: 2 @:vxor@:(s,t)}
36506
36507@c
36508@r{ @: Y @: @: @:@:user commands}
36509
36510@c
36511@r{ @: z @: @: @:@:user commands}
36512
36513@c
36514@r{ c@: Z [ @: @: 45 @:calc-kbd-if@:}
36515@r{ c@: Z | @: @: 45 @:calc-kbd-else-if@:}
36516@r{ @: Z : @: @: @:calc-kbd-else@:}
36517@r{ @: Z ] @: @: @:calc-kbd-end-if@:}
36518
36519@c
36520@r{ @: Z @{ @: @: 4 @:calc-kbd-loop@:}
36521@r{ c@: Z / @: @: 45 @:calc-kbd-break@:}
36522@r{ @: Z @} @: @: @:calc-kbd-end-loop@:}
36523@r{ n@: Z < @: @: @:calc-kbd-repeat@:}
36524@r{ @: Z > @: @: @:calc-kbd-end-repeat@:}
36525@r{ n m@: Z ( @: @: @:calc-kbd-for@:}
36526@r{ s@: Z ) @: @: @:calc-kbd-end-for@:}
36527
36528@c
36529@r{ @: Z C-g @: @: @:@:cancel if/loop command}
36530
36531@c
36532@r{ @: Z ` @: @: @:calc-kbd-push@:}
36533@r{ @: Z ' @: @: @:calc-kbd-pop@:}
36534@r{ @: Z # @: @: @:calc-kbd-query@:}
36535
36536@c
36537@r{ comp@: Z C @:func, args @: 50 @:calc-user-define-composition@:}
36538@r{ @: Z D @:key, command @: @:calc-user-define@:}
36539@r{ @: Z E @:key, editing @: 30 @:calc-user-define-edit@:}
36540@r{ defn@: Z F @:k, c, f, a, n@: 28 @:calc-user-define-formula@:}
36541@r{ @: Z G @:key @: @:calc-get-user-defn@:}
36542@r{ @: Z I @: @: @:calc-user-define-invocation@:}
36543@r{ @: Z K @:key, command @: @:calc-user-define-kbd-macro@:}
36544@r{ @: Z P @:key @: @:calc-user-define-permanent@:}
36545@r{ @: Z S @: @: 30 @:calc-edit-user-syntax@:}
36546@r{ @: Z T @: @: 12 @:calc-timing@:}
36547@r{ @: Z U @:key @: @:calc-user-undefine@:}
36548
36549@end format
36550
36551@noindent
36552NOTES
36553
36554@enumerate
36555@c 1
36556@item
36557Positive prefix arguments apply to @expr{n} stack entries.
36558Negative prefix arguments apply to the @expr{-n}th stack entry.
36559A prefix of zero applies to the entire stack. (For @key{LFD} and
36560@kbd{M-@key{DEL}}, the meaning of the sign is reversed.)
36561
36562@c 2
36563@item
36564Positive prefix arguments apply to @expr{n} stack entries.
36565Negative prefix arguments apply to the top stack entry
36566and the next @expr{-n} stack entries.
36567
36568@c 3
36569@item
36570Positive prefix arguments rotate top @expr{n} stack entries by one.
36571Negative prefix arguments rotate the entire stack by @expr{-n}.
36572A prefix of zero reverses the entire stack.
36573
36574@c 4
36575@item
36576Prefix argument specifies a repeat count or distance.
36577
36578@c 5
36579@item
36580Positive prefix arguments specify a precision @expr{p}.
36581Negative prefix arguments reduce the current precision by @expr{-p}.
36582
36583@c 6
36584@item
36585A prefix argument is interpreted as an additional step-size parameter.
36586A plain @kbd{C-u} prefix means to prompt for the step size.
36587
36588@c 7
36589@item
36590A prefix argument specifies simplification level and depth.
8e7046c3 365911=Basic simplifications, 2=Algebraic simplifications, 3=Extended simplifications
4009494e
GM
36592
36593@c 8
36594@item
36595A negative prefix operates only on the top level of the input formula.
36596
36597@c 9
36598@item
36599Positive prefix arguments specify a word size of @expr{w} bits, unsigned.
36600Negative prefix arguments specify a word size of @expr{w} bits, signed.
36601
36602@c 10
36603@item
36604Prefix arguments specify the shift amount @expr{n}. The @expr{w} argument
36605cannot be specified in the keyboard version of this command.
36606
36607@c 11
36608@item
36609From the keyboard, @expr{d} is omitted and defaults to zero.
36610
36611@c 12
36612@item
36613Mode is toggled; a positive prefix always sets the mode, and a negative
36614prefix always clears the mode.
36615
36616@c 13
36617@item
36618Some prefix argument values provide special variations of the mode.
36619
36620@c 14
36621@item
36622A prefix argument, if any, is used for @expr{m} instead of taking
36623@expr{m} from the stack. @expr{M} may take any of these values:
36624@iftex
36625{@advance@tableindent10pt
36626@end iftex
36627@table @asis
36628@item Integer
36629Random integer in the interval @expr{[0 .. m)}.
36630@item Float
36631Random floating-point number in the interval @expr{[0 .. m)}.
36632@item 0.0
36633Gaussian with mean 1 and standard deviation 0.
36634@item Error form
36635Gaussian with specified mean and standard deviation.
36636@item Interval
36637Random integer or floating-point number in that interval.
36638@item Vector
36639Random element from the vector.
36640@end table
36641@iftex
36642}
36643@end iftex
36644
36645@c 15
36646@item
36647A prefix argument from 1 to 6 specifies number of date components
36648to remove from the stack. @xref{Date Conversions}.
36649
36650@c 16
36651@item
36652A prefix argument specifies a time zone; @kbd{C-u} says to take the
36653time zone number or name from the top of the stack. @xref{Time Zones}.
36654
36655@c 17
36656@item
36657A prefix argument specifies a day number (0-6, 0-31, or 0-366).
36658
36659@c 18
36660@item
36661If the input has no units, you will be prompted for both the old and
36662the new units.
36663
36664@c 19
36665@item
36666With a prefix argument, collect that many stack entries to form the
36667input data set. Each entry may be a single value or a vector of values.
36668
36669@c 20
36670@item
40ba43b4 36671With a prefix argument of 1, take a single
4009494e 36672@texline @var{n}@math{\times2}
40ba43b4 36673@infoline @mathit{@var{N}x2}
4009494e
GM
36674matrix from the stack instead of two separate data vectors.
36675
36676@c 21
36677@item
36678The row or column number @expr{n} may be given as a numeric prefix
36679argument instead. A plain @kbd{C-u} prefix says to take @expr{n}
36680from the top of the stack. If @expr{n} is a vector or interval,
36681a subvector/submatrix of the input is created.
36682
36683@c 22
36684@item
36685The @expr{op} prompt can be answered with the key sequence for the
36686desired function, or with @kbd{x} or @kbd{z} followed by a function name,
36687or with @kbd{$} to take a formula from the top of the stack, or with
36688@kbd{'} and a typed formula. In the last two cases, the formula may
36689be a nameless function like @samp{<#1+#2>} or @samp{<x, y : x+y>}, or it
36690may include @kbd{$}, @kbd{$$}, etc. (where @kbd{$} will correspond to the
36691last argument of the created function), or otherwise you will be
36692prompted for an argument list. The number of vectors popped from the
36693stack by @kbd{V M} depends on the number of arguments of the function.
36694
36695@c 23
36696@item
36697One of the mapping direction keys @kbd{_} (horizontal, i.e., map
36698by rows or reduce across), @kbd{:} (vertical, i.e., map by columns or
36699reduce down), or @kbd{=} (map or reduce by rows) may be used before
36700entering @expr{op}; these modify the function name by adding the letter
36701@code{r} for ``rows,'' @code{c} for ``columns,'' @code{a} for ``across,''
36702or @code{d} for ``down.''
36703
36704@c 24
36705@item
36706The prefix argument specifies a packing mode. A nonnegative mode
36707is the number of items (for @kbd{v p}) or the number of levels
36708(for @kbd{v u}). A negative mode is as described below. With no
36709prefix argument, the mode is taken from the top of the stack and
36710may be an integer or a vector of integers.
36711@iftex
36712{@advance@tableindent-20pt
36713@end iftex
36714@table @cite
36715@item -1
36716(@var{2}) Rectangular complex number.
36717@item -2
36718(@var{2}) Polar complex number.
36719@item -3
36720(@var{3}) HMS form.
36721@item -4
36722(@var{2}) Error form.
36723@item -5
36724(@var{2}) Modulo form.
36725@item -6
36726(@var{2}) Closed interval.
36727@item -7
36728(@var{2}) Closed .. open interval.
36729@item -8
36730(@var{2}) Open .. closed interval.
36731@item -9
36732(@var{2}) Open interval.
36733@item -10
36734(@var{2}) Fraction.
36735@item -11
36736(@var{2}) Float with integer mantissa.
36737@item -12
36738(@var{2}) Float with mantissa in @expr{[1 .. 10)}.
36739@item -13
36740(@var{1}) Date form (using date numbers).
36741@item -14
36742(@var{3}) Date form (using year, month, day).
36743@item -15
36744(@var{6}) Date form (using year, month, day, hour, minute, second).
36745@end table
36746@iftex
36747}
36748@end iftex
36749
36750@c 25
36751@item
36752A prefix argument specifies the size @expr{n} of the matrix. With no
36753prefix argument, @expr{n} is omitted and the size is inferred from
36754the input vector.
36755
36756@c 26
36757@item
36758The prefix argument specifies the starting position @expr{n} (default 1).
36759
36760@c 27
36761@item
36762Cursor position within stack buffer affects this command.
36763
36764@c 28
36765@item
36766Arguments are not actually removed from the stack by this command.
36767
36768@c 29
36769@item
36770Variable name may be a single digit or a full name.
36771
36772@c 30
36773@item
40ba43b4 36774Editing occurs in a separate buffer. Press @kbd{C-c C-c} (or
4009494e
GM
36775@key{LFD}, or in some cases @key{RET}) to finish the edit, or kill the
36776buffer with @kbd{C-x k} to cancel the edit. The @key{LFD} key prevents evaluation
36777of the result of the edit.
36778
36779@c 31
36780@item
36781The number prompted for can also be provided as a prefix argument.
36782
36783@c 32
36784@item
36785Press this key a second time to cancel the prefix.
36786
36787@c 33
36788@item
36789With a negative prefix, deactivate all formulas. With a positive
36790prefix, deactivate and then reactivate from scratch.
36791
36792@c 34
36793@item
36794Default is to scan for nearest formula delimiter symbols. With a
36795prefix of zero, formula is delimited by mark and point. With a
36796non-zero prefix, formula is delimited by scanning forward or
36797backward by that many lines.
36798
36799@c 35
36800@item
36801Parse the region between point and mark as a vector. A nonzero prefix
36802parses @var{n} lines before or after point as a vector. A zero prefix
36803parses the current line as a vector. A @kbd{C-u} prefix parses the
36804region between point and mark as a single formula.
36805
36806@c 36
36807@item
36808Parse the rectangle defined by point and mark as a matrix. A positive
36809prefix @var{n} divides the rectangle into columns of width @var{n}.
36810A zero or @kbd{C-u} prefix parses each line as one formula. A negative
36811prefix suppresses special treatment of bracketed portions of a line.
36812
36813@c 37
36814@item
36815A numeric prefix causes the current language mode to be ignored.
36816
36817@c 38
36818@item
36819Responding to a prompt with a blank line answers that and all
36820later prompts by popping additional stack entries.
36821
36822@c 39
36823@item
36824Answer for @expr{v} may also be of the form @expr{v = v_0} or
36825@expr{v - v_0}.
36826
36827@c 40
36828@item
36829With a positive prefix argument, stack contains many @expr{y}'s and one
36830common @expr{x}. With a zero prefix, stack contains a vector of
36831@expr{y}s and a common @expr{x}. With a negative prefix, stack
36832contains many @expr{[x,y]} vectors. (For 3D plots, substitute
36833@expr{z} for @expr{y} and @expr{x,y} for @expr{x}.)
36834
36835@c 41
36836@item
36837With any prefix argument, all curves in the graph are deleted.
36838
36839@c 42
36840@item
36841With a positive prefix, refines an existing plot with more data points.
36842With a negative prefix, forces recomputation of the plot data.
36843
36844@c 43
36845@item
36846With any prefix argument, set the default value instead of the
36847value for this graph.
36848
36849@c 44
36850@item
36851With a negative prefix argument, set the value for the printer.
36852
36853@c 45
36854@item
36855Condition is considered ``true'' if it is a nonzero real or complex
36856number, or a formula whose value is known to be nonzero; it is ``false''
36857otherwise.
36858
36859@c 46
36860@item
36861Several formulas separated by commas are pushed as multiple stack
36862entries. Trailing @kbd{)}, @kbd{]}, @kbd{@}}, @kbd{>}, and @kbd{"}
36863delimiters may be omitted. The notation @kbd{$$$} refers to the value
36864in stack level three, and causes the formula to replace the top three
36865stack levels. The notation @kbd{$3} refers to stack level three without
36866causing that value to be removed from the stack. Use @key{LFD} in place
36867of @key{RET} to prevent evaluation; use @kbd{M-=} in place of @key{RET}
36868to evaluate variables.
36869
36870@c 47
36871@item
36872The variable is replaced by the formula shown on the right. The
36873Inverse flag reverses the order of the operands, e.g., @kbd{I s - x}
40ba43b4 36874assigns
4009494e
GM
36875@texline @math{x \coloneq a-x}.
36876@infoline @expr{x := a-x}.
36877
36878@c 48
36879@item
36880Press @kbd{?} repeatedly to see how to choose a model. Answer the
36881variables prompt with @expr{iv} or @expr{iv;pv} to specify
36882independent and parameter variables. A positive prefix argument
36883takes @mathit{@var{n}+1} vectors from the stack; a zero prefix takes a matrix
36884and a vector from the stack.
36885
36886@c 49
36887@item
36888With a plain @kbd{C-u} prefix, replace the current region of the
36889destination buffer with the yanked text instead of inserting.
36890
36891@c 50
36892@item
36893All stack entries are reformatted; the @kbd{H} prefix inhibits this.
36894The @kbd{I} prefix sets the mode temporarily, redraws the top stack
36895entry, then restores the original setting of the mode.
36896
36897@c 51
36898@item
36899A negative prefix sets the default 3D resolution instead of the
36900default 2D resolution.
36901
36902@c 52
36903@item
36904This grabs a vector of the form [@var{prec}, @var{wsize}, @var{ssize},
36905@var{radix}, @var{flfmt}, @var{ang}, @var{frac}, @var{symb}, @var{polar},
36906@var{matrix}, @var{simp}, @var{inf}]. A prefix argument from 1 to 12
36907grabs the @var{n}th mode value only.
36908@end enumerate
36909
36910@iftex
36911(Space is provided below for you to keep your own written notes.)
36912@page
36913@endgroup
36914@end iftex
36915
36916
36917@c [end-summary]
36918
36919@node Key Index, Command Index, Summary, Top
36920@unnumbered Index of Key Sequences
36921
36922@printindex ky
36923
36924@node Command Index, Function Index, Key Index, Top
36925@unnumbered Index of Calculator Commands
36926
36927Since all Calculator commands begin with the prefix @samp{calc-}, the
36928@kbd{x} key has been provided as a variant of @kbd{M-x} which automatically
36929types @samp{calc-} for you. Thus, @kbd{x last-args} is short for
36930@kbd{M-x calc-last-args}.
36931
36932@printindex pg
36933
36934@node Function Index, Concept Index, Command Index, Top
36935@unnumbered Index of Algebraic Functions
36936
36937This is a list of built-in functions and operators usable in algebraic
36938expressions. Their full Lisp names are derived by adding the prefix
36939@samp{calcFunc-}, as in @code{calcFunc-sqrt}.
36940@iftex
36941All functions except those noted with ``*'' have corresponding
36942Calc keystrokes and can also be found in the Calc Summary.
36943@end iftex
36944
36945@printindex tp
36946
36947@node Concept Index, Variable Index, Function Index, Top
36948@unnumbered Concept Index
36949
36950@printindex cp
36951
36952@node Variable Index, Lisp Function Index, Concept Index, Top
36953@unnumbered Index of Variables
36954
36955The variables in this list that do not contain dashes are accessible
36956as Calc variables. Add a @samp{var-} prefix to get the name of the
36957corresponding Lisp variable.
36958
36959The remaining variables are Lisp variables suitable for @code{setq}ing
36960in your Calc init file or @file{.emacs} file.
36961
36962@printindex vr
36963
36964@node Lisp Function Index, , Variable Index, Top
36965@unnumbered Index of Lisp Math Functions
36966
36967The following functions are meant to be used with @code{defmath}, not
36968@code{defun} definitions. For names that do not start with @samp{calc-},
36969the corresponding full Lisp name is derived by adding a prefix of
36970@samp{math-}.
36971
36972@printindex fn
36973
36974@bye