Fixed typographic error.
[emacs.git] / man / calc.texi
blob5634ec4f07ae98372dd8cc6afb79e48af2f1898f
1 \input texinfo                  @c -*-texinfo-*-
2 @dircategory Emacs
3 @direntry
4 * Calc: (calc).         Advanced desk calculator and mathematical tool.
5 @end direntry
6 @comment %**start of header (This is for running Texinfo on a region.)
7 @c smallbook
8 @setfilename ../info/calc
9 @c [title]
10 @settitle GNU Emacs Calc 2.02 Manual
11 @setchapternewpage odd
12 @comment %**end of header (This is for running Texinfo on a region.)
14 @tex
15 % Some special kludges to make TeX formatting prettier.
16 % Because makeinfo.c exists, we can't just define new commands.
17 % So instead, we take over little-used existing commands.
19 % Suggested by Karl Berry <karl@@freefriends.org>
20 \gdef\!{\mskip-\thinmuskip}
21 % Redefine @cite{text} to act like $text$ in regular TeX.
22 % Info will typeset this same as @samp{text}.
23 \gdef\goodtex{\tex \let\rm\goodrm \let\t\ttfont \turnoffactive}
24 \gdef\goodrm{\fam0\tenrm}
25 \gdef\cite{\goodtex$\citexxx}
26 \gdef\citexxx#1{#1$\Etex}
27 \global\let\oldxrefX=\xrefX
28 \gdef\xrefX[#1]{\begingroup\let\cite=\dfn\oldxrefX[#1]\endgroup}
30 % Redefine @i{text} to be equivalent to @cite{text}, i.e., to use math mode.
31 % This looks the same in TeX but omits the surrounding ` ' in Info.
32 \global\let\i=\cite
34 % Redefine @c{tex-stuff} \n @whatever{info-stuff}.
35 \gdef\c{\futurelet\next\mycxxx}
36 \gdef\mycxxx{%
37   \ifx\next\bgroup \goodtex\let\next\mycxxy
38   \else\ifx\next\mindex \let\next\relax
39   \else\ifx\next\kindex \let\next\relax
40   \else\ifx\next\starindex \let\next\relax \else \let\next\comment
41   \fi\fi\fi\fi \next
43 \gdef\mycxxy#1#2{#1\Etex\mycxxz}
44 \gdef\mycxxz#1{}
45 @end tex
47 @c Fix some things to make math mode work properly.
48 @iftex
49 @textfont0=@tenrm
50 @font@teni=cmmi10 scaled @magstephalf   @textfont1=@teni
51 @font@seveni=cmmi7 scaled @magstephalf  @scriptfont1=@seveni
52 @font@fivei=cmmi5 scaled @magstephalf   @scriptscriptfont1=@fivei
53 @font@tensy=cmsy10 scaled @magstephalf  @textfont2=@tensy
54 @font@sevensy=cmsy7 scaled @magstephalf @scriptfont2=@sevensy
55 @font@fivesy=cmsy5 scaled @magstephalf  @scriptscriptfont2=@fivesy
56 @font@tenex=cmex10 scaled @magstephalf  @textfont3=@tenex
57 @scriptfont3=@tenex  @scriptscriptfont3=@tenex
58 @textfont7=@tentt  @scriptfont7=@tentt  @scriptscriptfont7=@tentt
59 @end iftex
61 @c Fix some other things specifically for this manual.
62 @iftex
63 @finalout
64 @mathcode`@:=`@:  @c Make Calc fractions come out right in math mode
65 @tocindent=.5pc   @c Indent subsections in table of contents less
66 @rightskip=0pt plus 2pt  @c Favor short lines rather than overfull hboxes
67 @tex
68 \gdef\coloneq{\mathrel{\mathord:\mathord=}}
69 \ifdim\parskip>17pt
70   \global\parskip=12pt   % Standard parskip looks a bit too large
71 \fi
72 \gdef\internalBitem{\parskip=7pt\kyhpos=\tableindent\kyvpos=0pt
73 \smallbreak\parsearg\itemzzy}
74 \gdef\itemzzy#1{\itemzzz{#1}\relax\ifvmode\kern-7pt\fi}
75 \gdef\trademark{${}^{\rm TM}$}
76 \gdef\group{%
77   \par\vskip8pt\begingroup
78   \def\Egroup{\egroup\endgroup}%
79   \let\aboveenvbreak=\relax  % so that nothing gets between vtop and first box
80   \def\singlespace{\baselineskip=\singlespaceskip}%
81   \vtop\bgroup
84 %\global\abovedisplayskip=0pt
85 %\global\abovedisplayshortskip=-10pt
86 %\global\belowdisplayskip=7pt
87 %\global\belowdisplayshortskip=2pt
88 \gdef\beforedisplay{\vskip-10pt}
89 \gdef\afterdisplay{\vskip-5pt}
90 \gdef\beforedisplayh{\vskip-25pt}
91 \gdef\afterdisplayh{\vskip-10pt}
93 \gdef\printindex{\parsearg\calcprintindex}
94 \gdef\calcprintindex#1{%
95   \doprintindex{#1}%
96   \openin1 \jobname.#1s
97   \ifeof1{\let\s=\indexskip \csname indexsize#1\endcsname}\fi
98   \closein1
100 \gdef\indexskip{(This page intentionally left blank)\vfill\eject}
101 \gdef\indexsizeky{\s\s\s\s\s\s\s\s}
102 \gdef\indexsizepg{\s\s\s\s\s\s}
103 \gdef\indexsizetp{\s\s\s\s\s\s}
104 \gdef\indexsizecp{\s\s\s\s}
105 \gdef\indexsizevr{}
106 \gdef\indexsizefn{\s\s}
107 \gdef\langle#1\rangle{\it XXX}   % Avoid length mismatch with true expansion
109 % Ensure no indentation at beginning of sections, and avoid club paragraphs.
110 \global\let\calcchapternofonts=\chapternofonts
111 \gdef\chapternofonts{\aftergroup\calcfixclub\calcchapternofonts}
112 \gdef\calcfixclub{\calcclubpenalty=10000\noindent}
113 \global\let\calcdobreak=\dobreak
114 \gdef\dobreak{{\penalty-9999\dimen0=\pagetotal\advance\dimen0by1.5in
115 \ifdim\dimen0>\pagegoal\vfill\eject\fi}\calcdobreak}
117 \gdef\kindex{\def\indexname{ky}\futurelet\next\calcindexer}
118 \gdef\tindex{\def\indexname{tp}\futurelet\next\calcindexer}
119 \gdef\mindex{\let\indexname\relax\futurelet\next\calcindexer}
120 \gdef\calcindexer{\catcode`\ =\active\parsearg\calcindexerxx}
121 \gdef\calcindexerxx#1{%
122   \catcode`\ =10%
123   \ifvmode \indent \fi \setbox0=\lastbox \advance\kyhpos\wd0 \fixoddpages \box0
124   \setbox0=\hbox{\ninett #1}%
125   \calcindexersh{\llap{\hbox to 4em{\bumpoddpages\lower\kyvpos\box0\hss}\hskip\kyhpos}}%
126   \global\let\calcindexersh=\calcindexershow
127   \advance\clubpenalty by 5000%
128   \ifx\indexname\relax \else
129     \singlecodeindexer{#1\indexstar}%
130     \global\def\indexstar{}%
131   \fi
132   \futurelet\next\calcindexerxxx
134 \gdef\indexstar{}
135 \gdef\bumpoddpages{\ifodd\calcpageno\hskip7.3in\fi}
136 %\gdef\bumpoddpages{\hskip7.3in}   % for marginal notes on right side always
137 %\gdef\bumpoddpages{}              % for marginal notes on left side always
138 \gdef\fixoddpages{%
139 \global\calcpageno=\pageno
140 {\dimen0=\pagetotal
141 \advance\dimen0 by2\baselineskip
142 \ifdim\dimen0>\pagegoal
143 \global\advance\calcpageno by 1
144 \vfill\eject\noindent
145 \fi}%
147 \gdef\calcindexershow#1{\smash{#1}\advance\kyvpos by 11pt}
148 \gdef\calcindexernoshow#1{}
149 \global\let\calcindexersh=\calcindexershow
150 \gdef\calcindexerxxx{%
151   \ifx\indexname\relax
152     \ifx\next\kindex \global\let\calcindexersh=\calcindexernoshow \fi
153     \ifx\next\tindex \global\let\calcindexersh=\calcindexernoshow \fi
154   \fi
155   \calcindexerxxxx
157 \gdef\calcindexerxxxx#1{\next}
158 \gdef\indexstarxx{\thinspace{\rm *}}
159 \gdef\starindex{\global\let\indexstar=\indexstarxx}
160 \gdef\calceverypar{%
161 \kyhpos=\leftskip\kyvpos=0pt\clubpenalty=\calcclubpenalty
162 \calcclubpenalty=1000\relax
164 \gdef\idots{{\indrm...}}
165 @end tex
166 @newdimen@kyvpos @kyvpos=0pt
167 @newdimen@kyhpos @kyhpos=0pt
168 @newcount@calcclubpenalty @calcclubpenalty=1000
169 @newcount@calcpageno
170 @newtoks@calcoldeverypar @calcoldeverypar=@everypar
171 @everypar={@calceverypar@the@calcoldeverypar}
172 @ifx@turnoffactive@undefinedzzz@def@turnoffactive{}@fi
173 @ifx@ninett@undefinedzzz@font@ninett=cmtt9@fi
174 @catcode`@\=0 \catcode`\@=11
175 \r@ggedbottomtrue
176 \catcode`\@=0 @catcode`@\=@active
177 @end iftex
179 @ifinfo
180 This file documents Calc, the GNU Emacs calculator.
182 Copyright (C) 1990, 1991 Free Software Foundation, Inc.
184 Permission is granted to make and distribute verbatim copies of this
185 manual provided the copyright notice and this permission notice are
186 preserved on all copies.
188 @ignore
189 Permission is granted to process this file through TeX and print the
190 results, provided the printed document carries copying permission notice
191 identical to this one except for the removal of this paragraph (this
192 paragraph not being relevant to the printed manual).
194 @end ignore
195 Permission is granted to copy and distribute modified versions of this
196 manual under the conditions for verbatim copying, provided also that the
197 section entitled ``GNU General Public License'' is included exactly as
198 in the original, and provided that the entire resulting derived work is
199 distributed under the terms of a permission notice identical to this one.
201 Permission is granted to copy and distribute translations of this manual
202 into another language, under the above conditions for modified versions,
203 except that the section entitled ``GNU General Public License'' may be
204 included in a translation approved by the author instead of in the
205 original English.
206 @end ifinfo
208 @titlepage
209 @sp 6
210 @center @titlefont{Calc Manual}
211 @sp 4
212 @center GNU Emacs Calc Version 2.02
213 @c [volume]
214 @sp 1
215 @center January 1992
216 @sp 5
217 @center Dave Gillespie
218 @center daveg@@synaptics.com
219 @page
221 @vskip 0pt plus 1filll
222 Copyright @copyright{} 1990, 1991 Free Software Foundation, Inc.
224 Permission is granted to make and distribute verbatim copies of
225 this manual provided the copyright notice and this permission notice
226 are preserved on all copies.
228 @ignore
229 Permission is granted to process this file through TeX and print the
230 results, provided the printed document carries copying permission notice
231 identical to this one except for the removal of this paragraph (this
232 paragraph not being relevant to the printed manual).
234 @end ignore
235 Permission is granted to copy and distribute modified versions of this
236 manual under the conditions for verbatim copying, provided also that the
237 section entitled ``GNU General Public License'' is included exactly as
238 in the original, and provided that the entire resulting derived work is
239 distributed under the terms of a permission notice identical to this one.
241 Permission is granted to copy and distribute translations of this manual
242 into another language, under the above conditions for modified versions,
243 except that the section entitled ``GNU General Public License'' may be
244 included in a translation approved by the author instead of in the
245 original English.
246 @end titlepage
248 @c [begin]
249 @ifinfo
250 @node Top, , (dir), (dir)
251 @chapter The GNU Emacs Calculator
253 @noindent
254 @dfn{Calc 2.02} is an advanced desk calculator and mathematical tool
255 that runs as part of the GNU Emacs environment.
257 This manual is divided into three major parts: "Getting Started," the
258 "Calc Tutorial," and the "Calc Reference."  The Tutorial introduces all
259 the major aspects of Calculator use in an easy, hands-on way.  The
260 remainder of the manual is a complete reference to the features of the
261 Calculator.
263 For help in the Emacs Info system (which you are using to read this
264 file), type @kbd{?}.  (You can also type @kbd{h} to run through a
265 longer Info tutorial.)
267 @end ifinfo
268 @menu
269 * Copying::               How you can copy and share Calc.
271 * Getting Started::       General description and overview.
272 * Interactive Tutorial::
273 * Tutorial::              A step-by-step introduction for beginners.
275 * Introduction::          Introduction to the Calc reference manual.
276 * Data Types::            Types of objects manipulated by Calc.
277 * Stack and Trail::       Manipulating the stack and trail buffers.
278 * Mode Settings::         Adjusting display format and other modes.
279 * Arithmetic::            Basic arithmetic functions.
280 * Scientific Functions::  Transcendentals and other scientific functions.
281 * Matrix Functions::      Operations on vectors and matrices.
282 * Algebra::               Manipulating expressions algebraically.
283 * Units::                 Operations on numbers with units.
284 * Store and Recall::      Storing and recalling variables.
285 * Graphics::              Commands for making graphs of data.
286 * Kill and Yank::         Moving data into and out of Calc.
287 * Embedded Mode::         Working with formulas embedded in a file.
288 * Programming::           Calc as a programmable calculator.
290 * Installation::          Installing Calc as a part of GNU Emacs.
291 * Reporting Bugs::        How to report bugs and make suggestions.
293 * Summary::               Summary of Calc commands and functions.
295 * Key Index::             The standard Calc key sequences.
296 * Command Index::         The interactive Calc commands.
297 * Function Index::        Functions (in algebraic formulas).
298 * Concept Index::         General concepts.
299 * Variable Index::        Variables used by Calc (both user and internal).
300 * Lisp Function Index::   Internal Lisp math functions.
301 @end menu
303 @node Copying, Getting Started, Top, Top
304 @unnumbered GNU GENERAL PUBLIC LICENSE
305 @center Version 1, February 1989
307 @display
308 Copyright @copyright{} 1989 Free Software Foundation, Inc.
309 675 Mass Ave, Cambridge, MA 02139, USA
311 Everyone is permitted to copy and distribute verbatim copies
312 of this license document, but changing it is not allowed.
313 @end display
315 @unnumberedsec Preamble
317   The license agreements of most software companies try to keep users
318 at the mercy of those companies.  By contrast, our General Public
319 License is intended to guarantee your freedom to share and change free
320 software---to make sure the software is free for all its users.  The
321 General Public License applies to the Free Software Foundation's
322 software and to any other program whose authors commit to using it.
323 You can use it for your programs, too.
325   When we speak of free software, we are referring to freedom, not
326 price.  Specifically, the General Public License is designed to make
327 sure that you have the freedom to give away or sell copies of free
328 software, that you receive source code or can get it if you want it,
329 that you can change the software or use pieces of it in new free
330 programs; and that you know you can do these things.
332   To protect your rights, we need to make restrictions that forbid
333 anyone to deny you these rights or to ask you to surrender the rights.
334 These restrictions translate to certain responsibilities for you if you
335 distribute copies of the software, or if you modify it.
337   For example, if you distribute copies of a such a program, whether
338 gratis or for a fee, you must give the recipients all the rights that
339 you have.  You must make sure that they, too, receive or can get the
340 source code.  And you must tell them their rights.
342   We protect your rights with two steps: (1) copyright the software, and
343 (2) offer you this license which gives you legal permission to copy,
344 distribute and/or modify the software.
346   Also, for each author's protection and ours, we want to make certain
347 that everyone understands that there is no warranty for this free
348 software.  If the software is modified by someone else and passed on, we
349 want its recipients to know that what they have is not the original, so
350 that any problems introduced by others will not reflect on the original
351 authors' reputations.
353   The precise terms and conditions for copying, distribution and
354 modification follow.
356 @iftex
357 @unnumberedsec TERMS AND CONDITIONS
358 @end iftex
359 @ifinfo
360 @center TERMS AND CONDITIONS
361 @end ifinfo
363 @enumerate
364 @item
365 This License Agreement applies to any program or other work which
366 contains a notice placed by the copyright holder saying it may be
367 distributed under the terms of this General Public License.  The
368 ``Program'', below, refers to any such program or work, and a ``work based
369 on the Program'' means either the Program or any work containing the
370 Program or a portion of it, either verbatim or with modifications.  Each
371 licensee is addressed as ``you''.
373 @item
374 You may copy and distribute verbatim copies of the Program's source
375 code as you receive it, in any medium, provided that you conspicuously and
376 appropriately publish on each copy an appropriate copyright notice and
377 disclaimer of warranty; keep intact all the notices that refer to this
378 General Public License and to the absence of any warranty; and give any
379 other recipients of the Program a copy of this General Public License
380 along with the Program.  You may charge a fee for the physical act of
381 transferring a copy.
383 @item
384 You may modify your copy or copies of the Program or any portion of
385 it, and copy and distribute such modifications under the terms of Paragraph
386 1 above, provided that you also do the following:
388 @itemize @bullet
389 @item
390 cause the modified files to carry prominent notices stating that
391 you changed the files and the date of any change; and
393 @item
394 cause the whole of any work that you distribute or publish, that
395 in whole or in part contains the Program or any part thereof, either
396 with or without modifications, to be licensed at no charge to all
397 third parties under the terms of this General Public License (except
398 that you may choose to grant warranty protection to some or all
399 third parties, at your option).
401 @item
402 If the modified program normally reads commands interactively when
403 run, you must cause it, when started running for such interactive use
404 in the simplest and most usual way, to print or display an
405 announcement including an appropriate copyright notice and a notice
406 that there is no warranty (or else, saying that you provide a
407 warranty) and that users may redistribute the program under these
408 conditions, and telling the user how to view a copy of this General
409 Public License.
411 @item
412 You may charge a fee for the physical act of transferring a
413 copy, and you may at your option offer warranty protection in
414 exchange for a fee.
415 @end itemize
417 Mere aggregation of another independent work with the Program (or its
418 derivative) on a volume of a storage or distribution medium does not bring
419 the other work under the scope of these terms.
421 @item
422 You may copy and distribute the Program (or a portion or derivative of
423 it, under Paragraph 2) in object code or executable form under the terms of
424 Paragraphs 1 and 2 above provided that you also do one of the following:
426 @itemize @bullet
427 @item
428 accompany it with the complete corresponding machine-readable
429 source code, which must be distributed under the terms of
430 Paragraphs 1 and 2 above; or,
432 @item
433 accompany it with a written offer, valid for at least three
434 years, to give any third party free (except for a nominal charge
435 for the cost of distribution) a complete machine-readable copy of the
436 corresponding source code, to be distributed under the terms of
437 Paragraphs 1 and 2 above; or,
439 @item
440 accompany it with the information you received as to where the
441 corresponding source code may be obtained.  (This alternative is
442 allowed only for noncommercial distribution and only if you
443 received the program in object code or executable form alone.)
444 @end itemize
446 Source code for a work means the preferred form of the work for making
447 modifications to it.  For an executable file, complete source code means
448 all the source code for all modules it contains; but, as a special
449 exception, it need not include source code for modules which are standard
450 libraries that accompany the operating system on which the executable
451 file runs, or for standard header files or definitions files that
452 accompany that operating system.
454 @item
455 You may not copy, modify, sublicense, distribute or transfer the
456 Program except as expressly provided under this General Public License.
457 Any attempt otherwise to copy, modify, sublicense, distribute or transfer
458 the Program is void, and will automatically terminate your rights to use
459 the Program under this License.  However, parties who have received
460 copies, or rights to use copies, from you under this General Public
461 License will not have their licenses terminated so long as such parties
462 remain in full compliance.
464 @item
465 By copying, distributing or modifying the Program (or any work based
466 on the Program) you indicate your acceptance of this license to do so,
467 and all its terms and conditions.
469 @item
470 Each time you redistribute the Program (or any work based on the
471 Program), the recipient automatically receives a license from the original
472 licensor to copy, distribute or modify the Program subject to these
473 terms and conditions.  You may not impose any further restrictions on the
474 recipients' exercise of the rights granted herein.
476 @item
477 The Free Software Foundation may publish revised and/or new versions
478 of the General Public License from time to time.  Such new versions will
479 be similar in spirit to the present version, but may differ in detail to
480 address new problems or concerns.
482 Each version is given a distinguishing version number.  If the Program
483 specifies a version number of the license which applies to it and ``any
484 later version'', you have the option of following the terms and conditions
485 either of that version or of any later version published by the Free
486 Software Foundation.  If the Program does not specify a version number of
487 the license, you may choose any version ever published by the Free Software
488 Foundation.
490 @item
491 If you wish to incorporate parts of the Program into other free
492 programs whose distribution conditions are different, write to the author
493 to ask for permission.  For software which is copyrighted by the Free
494 Software Foundation, write to the Free Software Foundation; we sometimes
495 make exceptions for this.  Our decision will be guided by the two goals
496 of preserving the free status of all derivatives of our free software and
497 of promoting the sharing and reuse of software generally.
499 @iftex
500 @heading NO WARRANTY
501 @end iftex
502 @ifinfo
503 @center NO WARRANTY
504 @end ifinfo
506 @item
507 BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
508 FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
509 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
510 PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
511 OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
512 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
513 TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
514 PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
515 REPAIR OR CORRECTION.
517 @item
518 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
519 ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
520 REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
521 INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
522 ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT
523 LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES
524 SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
525 WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
526 ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
527 @end enumerate
529 @node Getting Started, Tutorial, Copying, Top
530 @chapter Getting Started
531 @noindent
532 This chapter provides a general overview of Calc, the GNU Emacs
533 Calculator:  What it is, how to start it and how to exit from it,
534 and what are the various ways that it can be used.
536 @menu
537 * What is Calc::
538 * About This Manual::
539 * Notations Used in This Manual::
540 * Using Calc::
541 * Demonstration of Calc::
542 * History and Acknowledgements::
543 @end menu
545 @node What is Calc, About This Manual, Getting Started, Getting Started
546 @section What is Calc?
548 @noindent
549 @dfn{Calc} is an advanced calculator and mathematical tool that runs as
550 part of the GNU Emacs environment.  Very roughly based on the HP-28/48
551 series of calculators, its many features include:
553 @itemize @bullet
554 @item
555 Choice of algebraic or RPN (stack-based) entry of calculations.
557 @item
558 Arbitrary precision integers and floating-point numbers.
560 @item
561 Arithmetic on rational numbers, complex numbers (rectangular and polar),
562 error forms with standard deviations, open and closed intervals, vectors
563 and matrices, dates and times, infinities, sets, quantities with units,
564 and algebraic formulas.
566 @item
567 Mathematical operations such as logarithms and trigonometric functions.
569 @item
570 Programmer's features (bitwise operations, non-decimal numbers).
572 @item
573 Financial functions such as future value and internal rate of return.
575 @item
576 Number theoretical features such as prime factorization and arithmetic
577 modulo @i{M} for any @i{M}.
579 @item
580 Algebraic manipulation features, including symbolic calculus.
582 @item
583 Moving data to and from regular editing buffers.
585 @item
586 ``Embedded mode'' for manipulating Calc formulas and data directly
587 inside any editing buffer.
589 @item
590 Graphics using GNUPLOT, a versatile (and free) plotting program.
592 @item
593 Easy programming using keyboard macros, algebraic formulas,
594 algebraic rewrite rules, or extended Emacs Lisp.
595 @end itemize
597 Calc tries to include a little something for everyone; as a result it is
598 large and might be intimidating to the first-time user.  If you plan to
599 use Calc only as a traditional desk calculator, all you really need to
600 read is the ``Getting Started'' chapter of this manual and possibly the
601 first few sections of the tutorial.  As you become more comfortable with
602 the program you can learn its additional features.  In terms of efficiency,
603 scope and depth, Calc cannot replace a powerful tool like Mathematica.
604 @c Removed this per RMS' request:
605 @c Mathematica@c{\trademark} @asis{ (tm)}.
606 But Calc has the advantages of convenience, portability, and availability
607 of the source code.  And, of course, it's free!
609 @node About This Manual, Notations Used in This Manual, What is Calc, Getting Started
610 @section About This Manual
612 @noindent
613 This document serves as a complete description of the GNU Emacs
614 Calculator.  It works both as an introduction for novices, and as
615 a reference for experienced users.  While it helps to have some
616 experience with GNU Emacs in order to get the most out of Calc,
617 this manual ought to be readable even if you don't know or use Emacs
618 regularly.
620 @ifinfo
621 The manual is divided into three major parts:@: the ``Getting
622 Started'' chapter you are reading now, the Calc tutorial (chapter 2),
623 and the Calc reference manual (the remaining chapters and appendices).
624 @end ifinfo
625 @iftex
626 The manual is divided into three major parts:@: the ``Getting
627 Started'' chapter you are reading now, the Calc tutorial (chapter 2),
628 and the Calc reference manual (the remaining chapters and appendices).
629 @c [when-split]
630 @c This manual has been printed in two volumes, the @dfn{Tutorial} and the
631 @c @dfn{Reference}.  Both volumes include a copy of the ``Getting Started''
632 @c chapter.
633 @end iftex
635 If you are in a hurry to use Calc, there is a brief ``demonstration''
636 below which illustrates the major features of Calc in just a couple of
637 pages.  If you don't have time to go through the full tutorial, this
638 will show you everything you need to know to begin.
639 @xref{Demonstration of Calc}.
641 The tutorial chapter walks you through the various parts of Calc
642 with lots of hands-on examples and explanations.  If you are new
643 to Calc and you have some time, try going through at least the
644 beginning of the tutorial.  The tutorial includes about 70 exercises
645 with answers.  These exercises give you some guided practice with
646 Calc, as well as pointing out some interesting and unusual ways
647 to use its features.
649 The reference section discusses Calc in complete depth.  You can read
650 the reference from start to finish if you want to learn every aspect
651 of Calc.  Or, you can look in the table of contents or the Concept
652 Index to find the parts of the manual that discuss the things you
653 need to know.
655 @cindex Marginal notes
656 Every Calc keyboard command is listed in the Calc Summary, and also
657 in the Key Index.  Algebraic functions, @kbd{M-x} commands, and
658 variables also have their own indices.  @c{Each}
659 @asis{In the printed manual, each}
660 paragraph that is referenced in the Key or Function Index is marked
661 in the margin with its index entry.
663 @c [fix-ref Help Commands]
664 You can access this manual on-line at any time within Calc by
665 pressing the @kbd{h i} key sequence.  Outside of the Calc window,
666 you can press @kbd{M-# i} to read the manual on-line.  Also, you
667 can jump directly to the Tutorial by pressing @kbd{h t} or @kbd{M-# t},
668 or to the Summary by pressing @kbd{h s} or @kbd{M-# s}.  Within Calc,
669 you can also go to the part of the manual describing any Calc key,
670 function, or variable using @w{@kbd{h k}}, @kbd{h f}, or @kbd{h v},
671 respectively.  @xref{Help Commands}.
673 Printed copies of this manual are also available from the Free Software
674 Foundation.
676 @node Notations Used in This Manual, Demonstration of Calc, About This Manual, Getting Started
677 @section Notations Used in This Manual
679 @noindent
680 This section describes the various notations that are used
681 throughout the Calc manual.
683 In keystroke sequences, uppercase letters mean you must hold down
684 the shift key while typing the letter.  Keys pressed with Control
685 held down are shown as @kbd{C-x}.  Keys pressed with Meta held down
686 are shown as @kbd{M-x}.  Other notations are @key{RET} for the
687 Return key, @key{SPC} for the space bar, @key{TAB} for the Tab key,
688 @key{DEL} for the Delete key, and @key{LFD} for the Line-Feed key.
690 (If you don't have the @key{LFD} or @key{TAB} keys on your keyboard,
691 the @kbd{C-j} and @kbd{C-i} keys are equivalent to them, respectively.
692 If you don't have a Meta key, look for Alt or Extend Char.  You can
693 also press @key{ESC} or @key{C-[} first to get the same effect, so
694 that @kbd{M-x}, @kbd{ESC x}, and @kbd{C-[ x} are all equivalent.)
696 Sometimes the @key{RET} key is not shown when it is ``obvious''
697 that you must press @kbd{RET} to proceed.  For example, the @key{RET}
698 is usually omitted in key sequences like @kbd{M-x calc-keypad @key{RET}}.
700 Commands are generally shown like this:  @kbd{p} (@code{calc-precision})
701 or @kbd{M-# k} (@code{calc-keypad}).  This means that the command is
702 normally used by pressing the @kbd{p} key or @kbd{M-# k} key sequence,
703 but it also has the full-name equivalent shown, e.g., @kbd{M-x calc-precision}.
705 Commands that correspond to functions in algebraic notation
706 are written:  @kbd{C} (@code{calc-cos}) [@code{cos}].  This means
707 the @kbd{C} key is equivalent to @kbd{M-x calc-cos}, and that
708 the corresponding function in an algebraic-style formula would
709 be @samp{cos(@var{x})}.
711 A few commands don't have key equivalents:  @code{calc-sincos}
712 [@code{sincos}].@refill
714 @node Demonstration of Calc, Using Calc, Notations Used in This Manual, Getting Started
715 @section A Demonstration of Calc
717 @noindent
718 @cindex Demonstration of Calc
719 This section will show some typical small problems being solved with
720 Calc.  The focus is more on demonstration than explanation, but
721 everything you see here will be covered more thoroughly in the
722 Tutorial.
724 To begin, start Emacs if necessary (usually the command @code{emacs}
725 does this), and type @kbd{M-# c} (or @kbd{ESC # c}) to start the
726 Calculator.  (@xref{Starting Calc}, if this doesn't work for you.)
728 Be sure to type all the sample input exactly, especially noting the
729 difference between lower-case and upper-case letters.  Remember,
730 @kbd{RET}, @kbd{TAB}, @kbd{DEL}, and @kbd{SPC} are the Return, Tab,
731 Delete, and Space keys.
733 @strong{RPN calculation.}  In RPN, you type the input number(s) first,
734 then the command to operate on the numbers.
736 @noindent
737 Type @kbd{2 RET 3 + Q} to compute @c{$\sqrt{2+3} = 2.2360679775$}
738 @asis{the square root of 2+3, which is 2.2360679775}.
740 @noindent
741 Type @kbd{P 2 ^} to compute @c{$\pi^2 = 9.86960440109$}
742 @asis{the value of `pi' squared, 9.86960440109}.
744 @noindent
745 Type @kbd{TAB} to exchange the order of these two results.
747 @noindent
748 Type @kbd{- I H S} to subtract these results and compute the Inverse
749 Hyperbolic sine of the difference, 2.72996136574.
751 @noindent
752 Type @kbd{DEL} to erase this result.
754 @strong{Algebraic calculation.}  You can also enter calculations using
755 conventional ``algebraic'' notation.  To enter an algebraic formula,
756 use the apostrophe key.
758 @noindent
759 Type @kbd{' sqrt(2+3) RET} to compute @c{$\sqrt{2+3}$}
760 @asis{the square root of 2+3}.
762 @noindent
763 Type @kbd{' pi^2 RET} to enter @c{$\pi^2$}
764 @asis{`pi' squared}.  To evaluate this symbolic
765 formula as a number, type @kbd{=}.
767 @noindent
768 Type @kbd{' arcsinh($ - $$) RET} to subtract the second-most-recent
769 result from the most-recent and compute the Inverse Hyperbolic sine.
771 @strong{Keypad mode.}  If you are using the X window system, press
772 @w{@kbd{M-# k}} to get Keypad mode.  (If you don't use X, skip to
773 the next section.)
775 @noindent
776 Click on the @key{2}, @key{ENTER}, @key{3}, @key{+}, and @key{SQRT}
777 ``buttons'' using your left mouse button.
779 @noindent
780 Click on @key{PI}, @key{2}, and @t{y^x}.
782 @noindent
783 Click on @key{INV}, then @key{ENTER} to swap the two results.
785 @noindent
786 Click on @key{-}, @key{INV}, @key{HYP}, and @key{SIN}.
788 @noindent
789 Click on @key{<-} to erase the result, then click @key{OFF} to turn
790 the Keypad Calculator off.
792 @strong{Grabbing data.}  Type @kbd{M-# x} if necessary to exit Calc.
793 Now select the following numbers as an Emacs region:  ``Mark'' the
794 front of the list by typing control-@kbd{SPC} or control-@kbd{@@} there,
795 then move to the other end of the list.  (Either get this list from
796 the on-line copy of this manual, accessed by @w{@kbd{M-# i}}, or just
797 type these numbers into a scratch file.)  Now type @kbd{M-# g} to
798 ``grab'' these numbers into Calc.
800 @group
801 @example
802 1.23  1.97
803 1.6   2
804 1.19  1.08
805 @end example
806 @end group
808 @noindent
809 The result @samp{[1.23, 1.97, 1.6, 2, 1.19, 1.08]} is a Calc ``vector.''
810 Type @w{@kbd{V R +}} to compute the sum of these numbers.
812 @noindent
813 Type @kbd{U} to Undo this command, then type @kbd{V R *} to compute
814 the product of the numbers.
816 @noindent
817 You can also grab data as a rectangular matrix.  Place the cursor on
818 the upper-leftmost @samp{1} and set the mark, then move to just after
819 the lower-right @samp{8} and press @kbd{M-# r}.
821 @noindent
822 Type @kbd{v t} to transpose this @c{$3\times2$}
823 @asis{3x2} matrix into a @c{$2\times3$}
824 @asis{2x3} matrix.  Type
825 @w{@kbd{v u}} to unpack the rows into two separate vectors.  Now type
826 @w{@kbd{V R + TAB V R +}} to compute the sums of the two original columns.
827 (There is also a special grab-and-sum-columns command, @kbd{M-# :}.)
829 @strong{Units conversion.}  Units are entered algebraically.
830 Type @w{@kbd{' 43 mi/hr RET}} to enter the quantity 43 miles-per-hour.
831 Type @w{@kbd{u c km/hr RET}}.  Type @w{@kbd{u c m/s RET}}.
833 @strong{Date arithmetic.}  Type @kbd{t N} to get the current date and
834 time.  Type @kbd{90 +} to find the date 90 days from now.  Type
835 @kbd{' <25 dec 87> RET} to enter a date, then @kbd{- 7 /} to see how
836 many weeks have passed since then.
838 @strong{Algebra.}  Algebraic entries can also include formulas
839 or equations involving variables.  Type @kbd{@w{' [x + y} = a, x y = 1] RET}
840 to enter a pair of equations involving three variables.
841 (Note the leading apostrophe in this example; also, note that the space
842 between @samp{x y} is required.)  Type @w{@kbd{a S x,y RET}} to solve
843 these equations for the variables @cite{x} and @cite{y}.@refill
845 @noindent
846 Type @kbd{d B} to view the solutions in more readable notation.
847 Type @w{@kbd{d C}} to view them in C language notation, and @kbd{d T}
848 to view them in the notation for the @TeX{} typesetting system.
849 Type @kbd{d N} to return to normal notation.
851 @noindent
852 Type @kbd{7.5}, then @kbd{s l a RET} to let @cite{a = 7.5} in these formulas.
853 (That's a letter @kbd{l}, not a numeral @kbd{1}.)
855 @iftex
856 @strong{Help functions.}  You can read about any command in the on-line
857 manual.  Type @kbd{M-# c} to return to Calc after each of these
858 commands: @kbd{h k t N} to read about the @kbd{t N} command,
859 @kbd{h f sqrt RET} to read about the @code{sqrt} function, and
860 @kbd{h s} to read the Calc summary.
861 @end iftex
862 @ifinfo
863 @strong{Help functions.}  You can read about any command in the on-line
864 manual.  Remember to type the letter @kbd{l}, then @kbd{M-# c}, to
865 return here after each of these commands: @w{@kbd{h k t N}} to read
866 about the @w{@kbd{t N}} command, @kbd{h f sqrt RET} to read about the
867 @code{sqrt} function, and @kbd{h s} to read the Calc summary.
868 @end ifinfo
870 Press @kbd{DEL} repeatedly to remove any leftover results from the stack.
871 To exit from Calc, press @kbd{q} or @kbd{M-# c} again.
873 @node Using Calc, History and Acknowledgements, Demonstration of Calc, Getting Started
874 @section Using Calc
876 @noindent
877 Calc has several user interfaces that are specialized for
878 different kinds of tasks.  As well as Calc's standard interface,
879 there are Quick Mode, Keypad Mode, and Embedded Mode.
881 @c [fix-ref Installation]
882 Calc must be @dfn{installed} before it can be used.  @xref{Installation},
883 for instructions on setting up and installing Calc.  We will assume
884 you or someone on your system has already installed Calc as described
885 there.
887 @menu
888 * Starting Calc::
889 * The Standard Interface::
890 * Quick Mode Overview::
891 * Keypad Mode Overview::
892 * Standalone Operation::
893 * Embedded Mode Overview::
894 * Other M-# Commands::
895 @end menu
897 @node Starting Calc, The Standard Interface, Using Calc, Using Calc
898 @subsection Starting Calc
900 @noindent
901 On most systems, you can type @kbd{M-#} to start the Calculator.
902 The notation @kbd{M-#} is short for Meta-@kbd{#}.  On most
903 keyboards this means holding down the Meta (or Alt) and
904 Shift keys while typing @kbd{3}.
906 @cindex META key
907 Once again, if you don't have a Meta key on your keyboard you can type
908 @key{ESC} first, then @kbd{#}, to accomplish the same thing.  If you
909 don't even have an @key{ESC} key, you can fake it by holding down
910 Control or @key{CTRL} while typing a left square bracket
911 (that's @kbd{C-[} in Emacs notation).@refill
913 @kbd{M-#} is a @dfn{prefix key}; when you press it, Emacs waits for
914 you to press a second key to complete the command.  In this case,
915 you will follow @kbd{M-#} with a letter (upper- or lower-case, it
916 doesn't matter for @kbd{M-#}) that says which Calc interface you
917 want to use.
919 To get Calc's standard interface, type @kbd{M-# c}.  To get
920 Keypad Mode, type @kbd{M-# k}.  Type @kbd{M-# ?} to get a brief
921 list of the available options, and type a second @kbd{?} to get
922 a complete list.
924 To ease typing, @kbd{M-# M-#} (or @kbd{M-# #} if that's easier)
925 also works to start Calc.  It starts the same interface (either
926 @kbd{M-# c} or @w{@kbd{M-# k}}) that you last used, selecting the
927 @kbd{M-# c} interface by default.  (If your installation has
928 a special function key set up to act like @kbd{M-#}, hitting that
929 function key twice is just like hitting @kbd{M-# M-#}.)
931 If @kbd{M-#} doesn't work for you, you can always type explicit
932 commands like @kbd{M-x calc} (for the standard user interface) or
933 @w{@kbd{M-x calc-keypad}} (for Keypad Mode).  First type @kbd{M-x}
934 (that's Meta with the letter @kbd{x}), then, at the prompt,
935 type the full command (like @kbd{calc-keypad}) and press Return.
937 If you type @kbd{M-x calc} and Emacs still doesn't recognize the
938 command (it will say @samp{[No match]} when you try to press
939 @key{RET}), then Calc has not been properly installed.
941 The same commands (like @kbd{M-# c} or @kbd{M-# M-#}) that start
942 the Calculator also turn it off if it is already on.
944 @node The Standard Interface, Quick Mode Overview, Starting Calc, Using Calc
945 @subsection The Standard Calc Interface
947 @noindent
948 @cindex Standard user interface
949 Calc's standard interface acts like a traditional RPN calculator,
950 operated by the normal Emacs keyboard.  When you type @kbd{M-# c}
951 to start the Calculator, the Emacs screen splits into two windows
952 with the file you were editing on top and Calc on the bottom.
954 @group
955 @iftex
956 @advance@hsize20pt
957 @end iftex
958 @smallexample
961 --**-Emacs: myfile             (Fundamental)----All----------------------
962 --- Emacs Calculator Mode ---                   |Emacs Calc Mode v2.00...
963 2:  17.3                                        |    17.3
964 1:  -5                                          |    3
965     .                                           |    2
966                                                 |    4
967                                                 |  * 8
968                                                 |  ->-5
969                                                 |
970 --%%-Calc: 12 Deg       (Calculator)----All----- --%%-Emacs: *Calc Trail*
971 @end smallexample
972 @end group
974 In this figure, the mode-line for @file{myfile} has moved up and the
975 ``Calculator'' window has appeared below it.  As you can see, Calc
976 actually makes two windows side-by-side.  The lefthand one is
977 called the @dfn{stack window} and the righthand one is called the
978 @dfn{trail window.}  The stack holds the numbers involved in the
979 calculation you are currently performing.  The trail holds a complete
980 record of all calculations you have done.  In a desk calculator with
981 a printer, the trail corresponds to the paper tape that records what
982 you do.
984 In this case, the trail shows that four numbers (17.3, 3, 2, and 4)
985 were first entered into the Calculator, then the 2 and 4 were
986 multiplied to get 8, then the 3 and 8 were subtracted to get @i{-5}.
987 (The @samp{>} symbol shows that this was the most recent calculation.)
988 The net result is the two numbers 17.3 and @i{-5} sitting on the stack.
990 Most Calculator commands deal explicitly with the stack only, but
991 there is a set of commands that allow you to search back through
992 the trail and retrieve any previous result.
994 Calc commands use the digits, letters, and punctuation keys.
995 Shifted (i.e., upper-case) letters are different from lowercase
996 letters.  Some letters are @dfn{prefix} keys that begin two-letter
997 commands.  For example, @kbd{e} means ``enter exponent'' and shifted
998 @kbd{E} means @cite{e^x}.  With the @kbd{d} (``display modes'') prefix
999 the letter ``e'' takes on very different meanings:  @kbd{d e} means
1000 ``engineering notation'' and @kbd{d E} means ``@dfn{eqn} language mode.''
1002 There is nothing stopping you from switching out of the Calc
1003 window and back into your editing window, say by using the Emacs
1004 @w{@kbd{C-x o}} (@code{other-window}) command.  When the cursor is
1005 inside a regular window, Emacs acts just like normal.  When the
1006 cursor is in the Calc stack or trail windows, keys are interpreted
1007 as Calc commands.
1009 When you quit by pressing @kbd{M-# c} a second time, the Calculator
1010 windows go away but the actual Stack and Trail are not gone, just
1011 hidden.  When you press @kbd{M-# c} once again you will get the
1012 same stack and trail contents you had when you last used the
1013 Calculator.
1015 The Calculator does not remember its state between Emacs sessions.
1016 Thus if you quit Emacs and start it again, @kbd{M-# c} will give you
1017 a fresh stack and trail.  There is a command (@kbd{m m}) that lets
1018 you save your favorite mode settings between sessions, though.
1019 One of the things it saves is which user interface (standard or
1020 Keypad) you last used; otherwise, a freshly started Emacs will
1021 always treat @kbd{M-# M-#} the same as @kbd{M-# c}.
1023 The @kbd{q} key is another equivalent way to turn the Calculator off.
1025 If you type @kbd{M-# b} first and then @kbd{M-# c}, you get a
1026 full-screen version of Calc (@code{full-calc}) in which the stack and
1027 trail windows are still side-by-side but are now as tall as the whole
1028 Emacs screen.  When you press @kbd{q} or @kbd{M-# c} again to quit,
1029 the file you were editing before reappears.  The @kbd{M-# b} key
1030 switches back and forth between ``big'' full-screen mode and the
1031 normal partial-screen mode.
1033 Finally, @kbd{M-# o} (@code{calc-other-window}) is like @kbd{M-# c}
1034 except that the Calc window is not selected.  The buffer you were
1035 editing before remains selected instead.  @kbd{M-# o} is a handy
1036 way to switch out of Calc momentarily to edit your file; type
1037 @kbd{M-# c} to switch back into Calc when you are done.
1039 @node Quick Mode Overview, Keypad Mode Overview, The Standard Interface, Using Calc
1040 @subsection Quick Mode (Overview)
1042 @noindent
1043 @dfn{Quick Mode} is a quick way to use Calc when you don't need the
1044 full complexity of the stack and trail.  To use it, type @kbd{M-# q}
1045 (@code{quick-calc}) in any regular editing buffer.
1047 Quick Mode is very simple:  It prompts you to type any formula in
1048 standard algebraic notation (like @samp{4 - 2/3}) and then displays
1049 the result at the bottom of the Emacs screen (@i{3.33333333333}
1050 in this case).  You are then back in the same editing buffer you
1051 were in before, ready to continue editing or to type @kbd{M-# q}
1052 again to do another quick calculation.  The result of the calculation
1053 will also be in the Emacs ``kill ring'' so that a @kbd{C-y} command
1054 at this point will yank the result into your editing buffer.
1056 Calc mode settings affect Quick Mode, too, though you will have to
1057 go into regular Calc (with @kbd{M-# c}) to change the mode settings.
1059 @c [fix-ref Quick Calculator mode]
1060 @xref{Quick Calculator}, for further information.
1062 @node Keypad Mode Overview, Standalone Operation, Quick Mode Overview, Using Calc
1063 @subsection Keypad Mode (Overview)
1065 @noindent
1066 @dfn{Keypad Mode} is a mouse-based interface to the Calculator.
1067 It is designed for use with the X window system.  If you don't
1068 have X, you will have to operate keypad mode with your arrow
1069 keys (which is probably more trouble than it's worth).  Keypad
1070 mode is currently not supported under Emacs 19.
1072 Type @kbd{M-# k} to turn Keypad Mode on or off.  Once again you
1073 get two new windows, this time on the righthand side of the screen
1074 instead of at the bottom.  The upper window is the familiar Calc
1075 Stack; the lower window is a picture of a typical calculator keypad.
1077 @tex
1078 \dimen0=\pagetotal%
1079 \advance \dimen0 by 24\baselineskip%
1080 \ifdim \dimen0>\pagegoal \vfill\eject \fi%
1081 \medskip
1082 @end tex
1083 @smallexample
1084                                         |--- Emacs Calculator Mode ---
1085                                         |2:  17.3
1086                                         |1:  -5
1087                                         |    .
1088                                         |--%%-Calc: 12 Deg       (Calcul
1089                                         |----+-----Calc 2.00-----+----1
1090                                         |FLR |CEIL|RND |TRNC|CLN2|FLT |
1091                                         |----+----+----+----+----+----|
1092                                         | LN |EXP |    |ABS |IDIV|MOD |
1093                                         |----+----+----+----+----+----|
1094                                         |SIN |COS |TAN |SQRT|y^x |1/x |
1095                                         |----+----+----+----+----+----|
1096                                         |  ENTER  |+/- |EEX |UNDO| <- |
1097                                         |-----+---+-+--+--+-+---++----|
1098                                         | INV |  7  |  8  |  9  |  /  |
1099                                         |-----+-----+-----+-----+-----|
1100                                         | HYP |  4  |  5  |  6  |  *  |
1101                                         |-----+-----+-----+-----+-----|
1102                                         |EXEC |  1  |  2  |  3  |  -  |
1103                                         |-----+-----+-----+-----+-----|
1104                                         | OFF |  0  |  .  | PI  |  +  |
1105                                         |-----+-----+-----+-----+-----+
1106 @end smallexample
1107 @iftex
1108 @begingroup
1109 @ifdim@hsize=5in
1110 @vskip-3.7in
1111 @advance@hsize-2.2in
1112 @else
1113 @vskip-3.89in
1114 @advance@hsize-3.05in
1115 @advance@vsize.1in
1117 @end iftex
1119 Keypad Mode is much easier for beginners to learn, because there
1120 is no need to memorize lots of obscure key sequences.  But not all
1121 commands in regular Calc are available on the Keypad.  You can
1122 always switch the cursor into the Calc stack window to use
1123 standard Calc commands if you need.  Serious Calc users, though,
1124 often find they prefer the standard interface over Keypad Mode.
1126 To operate the Calculator, just click on the ``buttons'' of the
1127 keypad using your left mouse button.  To enter the two numbers
1128 shown here you would click @w{@kbd{1 7 .@: 3 ENTER 5 +/- ENTER}}; to
1129 add them together you would then click @kbd{+} (to get 12.3 on
1130 the stack).
1132 If you click the right mouse button, the top three rows of the
1133 keypad change to show other sets of commands, such as advanced
1134 math functions, vector operations, and operations on binary
1135 numbers.
1137 @iftex
1138 @endgroup
1139 @end iftex
1140 Because Keypad Mode doesn't use the regular keyboard, Calc leaves
1141 the cursor in your original editing buffer.  You can type in
1142 this buffer in the usual way while also clicking on the Calculator
1143 keypad.  One advantage of Keypad Mode is that you don't need an
1144 explicit command to switch between editing and calculating.
1146 If you press @kbd{M-# b} first, you get a full-screen Keypad Mode
1147 (@code{full-calc-keypad}) with three windows:  The keypad in the lower
1148 left, the stack in the lower right, and the trail on top.
1150 @c [fix-ref Keypad Mode]
1151 @xref{Keypad Mode}, for further information.
1153 @node Standalone Operation, Embedded Mode Overview, Keypad Mode Overview, Using Calc
1154 @subsection Standalone Operation
1156 @noindent
1157 @cindex Standalone Operation
1158 If you are not in Emacs at the moment but you wish to use Calc,
1159 you must start Emacs first.  If all you want is to run Calc, you
1160 can give the commands:
1162 @example
1163 emacs -f full-calc
1164 @end example
1166 @noindent
1169 @example
1170 emacs -f full-calc-keypad
1171 @end example
1173 @noindent
1174 which run a full-screen Calculator (as if by @kbd{M-# b M-# c}) or
1175 a full-screen X-based Calculator (as if by @kbd{M-# b M-# k}).
1176 In standalone operation, quitting the Calculator (by pressing
1177 @kbd{q} or clicking on the keypad @key{EXIT} button) quits Emacs
1178 itself.
1180 @node Embedded Mode Overview, Other M-# Commands, Standalone Operation, Using Calc
1181 @subsection Embedded Mode (Overview)
1183 @noindent
1184 @dfn{Embedded Mode} is a way to use Calc directly from inside an
1185 editing buffer.  Suppose you have a formula written as part of a
1186 document like this:
1188 @group
1189 @smallexample
1190 The derivative of
1192                                    ln(ln(x))
1195 @end smallexample
1196 @end group
1198 @noindent
1199 and you wish to have Calc compute and format the derivative for
1200 you and store this derivative in the buffer automatically.  To
1201 do this with Embedded Mode, first copy the formula down to where
1202 you want the result to be:
1204 @group
1205 @smallexample
1206 The derivative of
1208                                    ln(ln(x))
1212                                    ln(ln(x))
1213 @end smallexample
1214 @end group
1216 Now, move the cursor onto this new formula and press @kbd{M-# e}.
1217 Calc will read the formula (using the surrounding blank lines to
1218 tell how much text to read), then push this formula (invisibly)
1219 onto the Calc stack.  The cursor will stay on the formula in the
1220 editing buffer, but the buffer's mode line will change to look
1221 like the Calc mode line (with mode indicators like @samp{12 Deg}
1222 and so on).  Even though you are still in your editing buffer,
1223 the keyboard now acts like the Calc keyboard, and any new result
1224 you get is copied from the stack back into the buffer.  To take
1225 the derivative, you would type @kbd{a d x @key{RET}}.
1227 @group
1228 @smallexample
1229 The derivative of
1231                                    ln(ln(x))
1235 1 / ln(x) x
1236 @end smallexample
1237 @end group
1239 To make this look nicer, you might want to press @kbd{d =} to center
1240 the formula, and even @kbd{d B} to use ``big'' display mode.
1242 @group
1243 @smallexample
1244 The derivative of
1246                                    ln(ln(x))
1249 % [calc-mode: justify: center]
1250 % [calc-mode: language: big]
1252                                        1
1253                                     -------
1254                                     ln(x) x
1255 @end smallexample
1256 @end group
1258 Calc has added annotations to the file to help it remember the modes
1259 that were used for this formula.  They are formatted like comments
1260 in the @TeX{} typesetting language, just in case you are using @TeX{}.
1261 (In this example @TeX{} is not being used, so you might want to move
1262 these comments up to the top of the file or otherwise put them out
1263 of the way.)
1265 As an extra flourish, we can add an equation number using a
1266 righthand label:  Type @kbd{d @} (1) RET}.
1268 @group
1269 @smallexample
1270 % [calc-mode: justify: center]
1271 % [calc-mode: language: big]
1272 % [calc-mode: right-label: " (1)"]
1274                                        1
1275                                     -------                      (1)
1276                                     ln(x) x
1277 @end smallexample
1278 @end group
1280 To leave Embedded Mode, type @kbd{M-# e} again.  The mode line
1281 and keyboard will revert to the way they were before.  (If you have
1282 actually been trying this as you read along, you'll want to press
1283 @kbd{M-# 0} [with the digit zero] now to reset the modes you changed.)
1285 The related command @kbd{M-# w} operates on a single word, which
1286 generally means a single number, inside text.  It uses any
1287 non-numeric characters rather than blank lines to delimit the
1288 formula it reads.  Here's an example of its use:
1290 @smallexample
1291 A slope of one-third corresponds to an angle of 1 degrees.
1292 @end smallexample
1294 Place the cursor on the @samp{1}, then type @kbd{M-# w} to enable
1295 Embedded Mode on that number.  Now type @kbd{3 /} (to get one-third),
1296 and @kbd{I T} (the Inverse Tangent converts a slope into an angle),
1297 then @w{@kbd{M-# w}} again to exit Embedded mode.
1299 @smallexample
1300 A slope of one-third corresponds to an angle of 18.4349488229 degrees.
1301 @end smallexample
1303 @c [fix-ref Embedded Mode]
1304 @xref{Embedded Mode}, for full details.
1306 @node Other M-# Commands, , Embedded Mode Overview, Using Calc
1307 @subsection Other @kbd{M-#} Commands
1309 @noindent
1310 Two more Calc-related commands are @kbd{M-# g} and @kbd{M-# r},
1311 which ``grab'' data from a selected region of a buffer into the
1312 Calculator.  The region is defined in the usual Emacs way, by
1313 a ``mark'' placed at one end of the region, and the Emacs
1314 cursor or ``point'' placed at the other.
1316 The @kbd{M-# g} command reads the region in the usual left-to-right,
1317 top-to-bottom order.  The result is packaged into a Calc vector
1318 of numbers and placed on the stack.  Calc (in its standard
1319 user interface) is then started.  Type @kbd{v u} if you want
1320 to unpack this vector into separate numbers on the stack.  Also,
1321 @kbd{C-u M-# g} interprets the region as a single number or
1322 formula.
1324 The @kbd{M-# r} command reads a rectangle, with the point and
1325 mark defining opposite corners of the rectangle.  The result
1326 is a matrix of numbers on the Calculator stack.
1328 Complementary to these is @kbd{M-# y}, which ``yanks'' the
1329 value at the top of the Calc stack back into an editing buffer.
1330 If you type @w{@kbd{M-# y}} while in such a buffer, the value is
1331 yanked at the current position.  If you type @kbd{M-# y} while
1332 in the Calc buffer, Calc makes an educated guess as to which
1333 editing buffer you want to use.  The Calc window does not have
1334 to be visible in order to use this command, as long as there
1335 is something on the Calc stack.
1337 Here, for reference, is the complete list of @kbd{M-#} commands.
1338 The shift, control, and meta keys are ignored for the keystroke
1339 following @kbd{M-#}.
1341 @noindent
1342 Commands for turning Calc on and off:
1344 @table @kbd
1345 @item #
1346 Turn Calc on or off, employing the same user interface as last time.
1348 @item C
1349 Turn Calc on or off using its standard bottom-of-the-screen
1350 interface.  If Calc is already turned on but the cursor is not
1351 in the Calc window, move the cursor into the window.
1353 @item O
1354 Same as @kbd{C}, but don't select the new Calc window.  If
1355 Calc is already turned on and the cursor is in the Calc window,
1356 move it out of that window.
1358 @item B
1359 Control whether @kbd{M-# c} and @kbd{M-# k} use the full screen.
1361 @item Q
1362 Use Quick Mode for a single short calculation.
1364 @item K
1365 Turn Calc Keypad mode on or off.
1367 @item E
1368 Turn Calc Embedded mode on or off at the current formula.
1370 @item J
1371 Turn Calc Embedded mode on or off, select the interesting part.
1373 @item W
1374 Turn Calc Embedded mode on or off at the current word (number).
1376 @item Z
1377 Turn Calc on in a user-defined way, as defined by a @kbd{Z I} command.
1379 @item X
1380 Quit Calc; turn off standard, Keypad, or Embedded mode if on.
1381 (This is like @kbd{q} or @key{OFF} inside of Calc.)
1382 @end table
1383 @iftex
1384 @sp 2
1385 @end iftex
1387 @group
1388 @noindent
1389 Commands for moving data into and out of the Calculator:
1391 @table @kbd
1392 @item G
1393 Grab the region into the Calculator as a vector.
1395 @item R
1396 Grab the rectangular region into the Calculator as a matrix.
1398 @item :
1399 Grab the rectangular region and compute the sums of its columns.
1401 @item _
1402 Grab the rectangular region and compute the sums of its rows.
1404 @item Y
1405 Yank a value from the Calculator into the current editing buffer.
1406 @end table
1407 @iftex
1408 @sp 2
1409 @end iftex
1410 @end group
1412 @group
1413 @noindent
1414 Commands for use with Embedded Mode:
1416 @table @kbd
1417 @item A
1418 ``Activate'' the current buffer.  Locate all formulas that
1419 contain @samp{:=} or @samp{=>} symbols and record their locations
1420 so that they can be updated automatically as variables are changed.
1422 @item D
1423 Duplicate the current formula immediately below and select
1424 the duplicate.
1426 @item F
1427 Insert a new formula at the current point.
1429 @item N
1430 Move the cursor to the next active formula in the buffer.
1432 @item P
1433 Move the cursor to the previous active formula in the buffer.
1435 @item U
1436 Update (i.e., as if by the @kbd{=} key) the formula at the current point.
1438 @item `
1439 Edit (as if by @code{calc-edit}) the formula at the current point.
1440 @end table
1441 @iftex
1442 @sp 2
1443 @end iftex
1444 @end group
1446 @group
1447 @noindent
1448 Miscellaneous commands:
1450 @table @kbd
1451 @item I
1452 Run the Emacs Info system to read the Calc manual.
1453 (This is the same as @kbd{h i} inside of Calc.)
1455 @item T
1456 Run the Emacs Info system to read the Calc Tutorial.
1458 @item S
1459 Run the Emacs Info system to read the Calc Summary.
1461 @item L
1462 Load Calc entirely into memory.  (Normally the various parts
1463 are loaded only as they are needed.)
1465 @item M
1466 Read a region of written keystroke names (like @samp{C-n a b c RET})
1467 and record them as the current keyboard macro.
1469 @item 0
1470 (This is the ``zero'' digit key.)  Reset the Calculator to
1471 its default state:  Empty stack, and default mode settings.
1472 With any prefix argument, reset everything but the stack.
1473 @end table
1474 @end group
1476 @node History and Acknowledgements, , Using Calc, Getting Started
1477 @section History and Acknowledgements
1479 @noindent
1480 Calc was originally started as a two-week project to occupy a lull
1481 in the author's schedule.  Basically, a friend asked if I remembered
1482 the value of @c{$2^{32}$}
1483 @cite{2^32}.  I didn't offhand, but I said, ``that's
1484 easy, just call up an @code{xcalc}.''  @code{Xcalc} duly reported
1485 that the answer to our question was @samp{4.294967e+09}---with no way to
1486 see the full ten digits even though we knew they were there in the
1487 program's memory!  I was so annoyed, I vowed to write a calculator
1488 of my own, once and for all.
1490 I chose Emacs Lisp, a) because I had always been curious about it
1491 and b) because, being only a text editor extension language after
1492 all, Emacs Lisp would surely reach its limits long before the project
1493 got too far out of hand.
1495 To make a long story short, Emacs Lisp turned out to be a distressingly
1496 solid implementation of Lisp, and the humble task of calculating
1497 turned out to be more open-ended than one might have expected.
1499 Emacs Lisp doesn't have built-in floating point math, so it had to be
1500 simulated in software.  In fact, Emacs integers will only comfortably
1501 fit six decimal digits or so---not enough for a decent calculator.  So
1502 I had to write my own high-precision integer code as well, and once I had
1503 this I figured that arbitrary-size integers were just as easy as large
1504 integers.  Arbitrary floating-point precision was the logical next step.
1505 Also, since the large integer arithmetic was there anyway it seemed only
1506 fair to give the user direct access to it, which in turn made it practical
1507 to support fractions as well as floats.  All these features inspired me
1508 to look around for other data types that might be worth having.
1510 Around this time, my friend Rick Koshi showed me his nifty new HP-28
1511 calculator.  It allowed the user to manipulate formulas as well as
1512 numerical quantities, and it could also operate on matrices.  I decided
1513 that these would be good for Calc to have, too.  And once things had
1514 gone this far, I figured I might as well take a look at serious algebra
1515 systems like Mathematica, Macsyma, and Maple for further ideas.  Since
1516 these systems did far more than I could ever hope to implement, I decided
1517 to focus on rewrite rules and other programming features so that users
1518 could implement what they needed for themselves.
1520 Rick complained that matrices were hard to read, so I put in code to
1521 format them in a 2D style.  Once these routines were in place, Big mode
1522 was obligatory.  Gee, what other language modes would be useful?
1524 Scott Hemphill and Allen Knutson, two friends with a strong mathematical
1525 bent, contributed ideas and algorithms for a number of Calc features
1526 including modulo forms, primality testing, and float-to-fraction conversion.
1528 Units were added at the eager insistence of Mass Sivilotti.  Later,
1529 Ulrich Mueller at CERN and Przemek Klosowski at NIST provided invaluable
1530 expert assistance with the units table.  As far as I can remember, the
1531 idea of using algebraic formulas and variables to represent units dates
1532 back to an ancient article in Byte magazine about muMath, an early
1533 algebra system for microcomputers.
1535 Many people have contributed to Calc by reporting bugs and suggesting
1536 features, large and small.  A few deserve special mention:  Tim Peters,
1537 who helped develop the ideas that led to the selection commands, rewrite
1538 rules, and many other algebra features; @c{Fran\c cois}
1539 @asis{Francois} Pinard, who contributed
1540 an early prototype of the Calc Summary appendix as well as providing
1541 valuable suggestions in many other areas of Calc; Carl Witty, whose eagle
1542 eyes discovered many typographical and factual errors in the Calc manual;
1543 Tim Kay, who drove the development of Embedded mode; Ove Ewerlid, who
1544 made many suggestions relating to the algebra commands and contributed
1545 some code for polynomial operations; Randal Schwartz, who suggested the
1546 @code{calc-eval} function; Robert J. Chassell, who suggested the Calc
1547 Tutorial and exercises; and Juha Sarlin, who first worked out how to split
1548 Calc into quickly-loading parts.  Bob Weiner helped immensely with the
1549 Lucid Emacs port.
1551 @cindex Bibliography
1552 @cindex Knuth, Art of Computer Programming
1553 @cindex Numerical Recipes
1554 @c Should these be expanded into more complete references?
1555 Among the books used in the development of Calc were Knuth's @emph{Art
1556 of Computer Programming} (especially volume II, @emph{Seminumerical
1557 Algorithms}); @emph{Numerical Recipes} by Press, Flannery, Teukolsky,
1558 and Vetterling; Bevington's @emph{Data Reduction and Error Analysis for
1559 the Physical Sciences}; @emph{Concrete Mathematics} by Graham, Knuth,
1560 and Patashnik; Steele's @emph{Common Lisp, the Language}; the @emph{CRC
1561 Standard Math Tables} (William H. Beyer, ed.); and Abramowitz and
1562 Stegun's venerable @emph{Handbook of Mathematical Functions}.  I
1563 consulted the user's manuals for the HP-28 and HP-48 calculators, as
1564 well as for the programs Mathematica, SMP, Macsyma, Maple, MathCAD,
1565 Gnuplot, and others.  Also, of course, Calc could not have been written
1566 without the excellent @emph{GNU Emacs Lisp Reference Manual}, by Bil
1567 Lewis and Dan LaLiberte.
1569 Final thanks go to Richard Stallman, without whose fine implementations
1570 of the Emacs editor, language, and environment, Calc would have been
1571 finished in two weeks.
1573 @c [tutorial]
1575 @ifinfo
1576 @c This node is accessed by the `M-# t' command.
1577 @node Interactive Tutorial, , , Top
1578 @chapter Tutorial
1580 @noindent
1581 Some brief instructions on using the Emacs Info system for this tutorial:
1583 Press the space bar and Delete keys to go forward and backward in a
1584 section by screenfuls (or use the regular Emacs scrolling commands
1585 for this).
1587 Press @kbd{n} or @kbd{p} to go to the Next or Previous section.
1588 If the section has a @dfn{menu}, press a digit key like @kbd{1}
1589 or @kbd{2} to go to a sub-section from the menu.  Press @kbd{u} to
1590 go back up from a sub-section to the menu it is part of.
1592 Exercises in the tutorial all have cross-references to the
1593 appropriate page of the ``answers'' section.  Press @kbd{f}, then
1594 the exercise number, to see the answer to an exercise.  After
1595 you have followed a cross-reference, you can press the letter
1596 @kbd{l} to return to where you were before.
1598 You can press @kbd{?} at any time for a brief summary of Info commands.
1600 Press @kbd{1} now to enter the first section of the Tutorial.
1602 @menu
1603 * Tutorial::
1604 @end menu
1605 @end ifinfo
1607 @node Tutorial, Introduction, Getting Started, Top
1608 @chapter Tutorial
1610 @noindent
1611 This chapter explains how to use Calc and its many features, in
1612 a step-by-step, tutorial way.  You are encouraged to run Calc and
1613 work along with the examples as you read (@pxref{Starting Calc}).
1614 If you are already familiar with advanced calculators, you may wish
1615 @c [not-split]
1616 to skip on to the rest of this manual.
1617 @c [when-split]
1618 @c to skip on to volume II of this manual, the @dfn{Calc Reference}.
1620 @c [fix-ref Embedded Mode]
1621 This tutorial describes the standard user interface of Calc only.
1622 The ``Quick Mode'' and ``Keypad Mode'' interfaces are fairly
1623 self-explanatory.  @xref{Embedded Mode}, for a description of
1624 the ``Embedded Mode'' interface.
1626 @ifinfo
1627 The easiest way to read this tutorial on-line is to have two windows on
1628 your Emacs screen, one with Calc and one with the Info system.  (If you
1629 have a printed copy of the manual you can use that instead.)  Press
1630 @kbd{M-# c} to turn Calc on or to switch into the Calc window, and
1631 press @kbd{M-# i} to start the Info system or to switch into its window.
1632 Or, you may prefer to use the tutorial in printed form.
1633 @end ifinfo
1634 @iftex
1635 The easiest way to read this tutorial on-line is to have two windows on
1636 your Emacs screen, one with Calc and one with the Info system.  (If you
1637 have a printed copy of the manual you can use that instead.)  Press
1638 @kbd{M-# c} to turn Calc on or to switch into the Calc window, and
1639 press @kbd{M-# i} to start the Info system or to switch into its window.
1640 @end iftex
1642 This tutorial is designed to be done in sequence.  But the rest of this
1643 manual does not assume you have gone through the tutorial.  The tutorial
1644 does not cover everything in the Calculator, but it touches on most
1645 general areas.
1647 @ifinfo
1648 You may wish to print out a copy of the Calc Summary and keep notes on
1649 it as you learn Calc.  @xref{Installation}, to see how to make a printed
1650 summary.  @xref{Summary}.
1651 @end ifinfo
1652 @iftex
1653 The Calc Summary at the end of the reference manual includes some blank
1654 space for your own use.  You may wish to keep notes there as you learn
1655 Calc.
1656 @end iftex
1658 @menu
1659 * Basic Tutorial::
1660 * Arithmetic Tutorial::
1661 * Vector/Matrix Tutorial::
1662 * Types Tutorial::
1663 * Algebra Tutorial::
1664 * Programming Tutorial::
1666 * Answers to Exercises::
1667 @end menu
1669 @node Basic Tutorial, Arithmetic Tutorial, Tutorial, Tutorial
1670 @section Basic Tutorial
1672 @noindent
1673 In this section, we learn how RPN and algebraic-style calculations
1674 work, how to undo and redo an operation done by mistake, and how
1675 to control various modes of the Calculator.
1677 @menu
1678 * RPN Tutorial::            Basic operations with the stack.
1679 * Algebraic Tutorial::      Algebraic entry; variables.
1680 * Undo Tutorial::           If you make a mistake: Undo and the trail.
1681 * Modes Tutorial::          Common mode-setting commands.
1682 @end menu
1684 @node RPN Tutorial, Algebraic Tutorial, Basic Tutorial, Basic Tutorial
1685 @subsection RPN Calculations and the Stack
1687 @cindex RPN notation
1688 @ifinfo
1689 @noindent
1690 Calc normally uses RPN notation.  You may be familiar with the RPN
1691 system from Hewlett-Packard calculators, FORTH, or PostScript.
1692 (Reverse Polish Notation, RPN, is named after the Polish mathematician
1693 Jan Lukasiewicz.)
1694 @end ifinfo
1695 @tex
1696 \noindent
1697 Calc normally uses RPN notation.  You may be familiar with the RPN
1698 system from Hewlett-Packard calculators, FORTH, or PostScript.
1699 (Reverse Polish Notation, RPN, is named after the Polish mathematician
1700 Jan \L ukasiewicz.)
1701 @end tex
1703 The central component of an RPN calculator is the @dfn{stack}.  A
1704 calculator stack is like a stack of dishes.  New dishes (numbers) are
1705 added at the top of the stack, and numbers are normally only removed
1706 from the top of the stack.
1708 @cindex Operators
1709 @cindex Operands
1710 In an operation like @cite{2+3}, the 2 and 3 are called the @dfn{operands}
1711 and the @cite{+} is the @dfn{operator}.  In an RPN calculator you always
1712 enter the operands first, then the operator.  Each time you type a
1713 number, Calc adds or @dfn{pushes} it onto the top of the Stack.
1714 When you press an operator key like @kbd{+}, Calc @dfn{pops} the appropriate
1715 number of operands from the stack and pushes back the result.
1717 Thus we could add the numbers 2 and 3 in an RPN calculator by typing:
1718 @kbd{2 @key{RET} 3 @key{RET} +}.  (The @key{RET} key, Return, corresponds to
1719 the @key{ENTER} key on traditional RPN calculators.)  Try this now if
1720 you wish; type @kbd{M-# c} to switch into the Calc window (you can type
1721 @kbd{M-# c} again or @kbd{M-# o} to switch back to the Tutorial window).
1722 The first four keystrokes ``push'' the numbers 2 and 3 onto the stack.
1723 The @kbd{+} key ``pops'' the top two numbers from the stack, adds them,
1724 and pushes the result (5) back onto the stack.  Here's how the stack
1725 will look at various points throughout the calculation:@refill
1727 @group
1728 @smallexample
1729     .          1:  2          2:  2          1:  5              .
1730                    .          1:  3              .
1731                                   .
1733   M-# c          2 RET          3 RET            +             DEL
1734 @end smallexample
1735 @end group
1737 The @samp{.} symbol is a marker that represents the top of the stack.
1738 Note that the ``top'' of the stack is really shown at the bottom of
1739 the Stack window.  This may seem backwards, but it turns out to be
1740 less distracting in regular use.
1742 @cindex Stack levels
1743 @cindex Levels of stack
1744 The numbers @samp{1:} and @samp{2:} on the left are @dfn{stack level
1745 numbers}.  Old RPN calculators always had four stack levels called
1746 @cite{x}, @cite{y}, @cite{z}, and @cite{t}.  Calc's stack can grow
1747 as large as you like, so it uses numbers instead of letters.  Some
1748 stack-manipulation commands accept a numeric argument that says
1749 which stack level to work on.  Normal commands like @kbd{+} always
1750 work on the top few levels of the stack.@refill
1752 @c [fix-ref Truncating the Stack]
1753 The Stack buffer is just an Emacs buffer, and you can move around in
1754 it using the regular Emacs motion commands.  But no matter where the
1755 cursor is, even if you have scrolled the @samp{.} marker out of
1756 view, most Calc commands always move the cursor back down to level 1
1757 before doing anything.  It is possible to move the @samp{.} marker
1758 upwards through the stack, temporarily ``hiding'' some numbers from
1759 commands like @kbd{+}.  This is called @dfn{stack truncation} and
1760 we will not cover it in this tutorial; @pxref{Truncating the Stack},
1761 if you are interested.
1763 You don't really need the second @key{RET} in @kbd{2 @key{RET} 3
1764 @key{RET} +}.  That's because if you type any operator name or
1765 other non-numeric key when you are entering a number, the Calculator
1766 automatically enters that number and then does the requested command.
1767 Thus @kbd{2 @key{RET} 3 +} will work just as well.@refill
1769 Examples in this tutorial will often omit @key{RET} even when the
1770 stack displays shown would only happen if you did press @key{RET}:
1772 @group
1773 @smallexample
1774 1:  2          2:  2          1:  5
1775     .          1:  3              .
1776                    .
1778   2 RET            3              +
1779 @end smallexample
1780 @end group
1782 @noindent
1783 Here, after pressing @kbd{3} the stack would really show @samp{1:  2}
1784 with @samp{Calc:@: 3} in the minibuffer.  In these situations, you can
1785 press the optional @key{RET} to see the stack as the figure shows.
1787 (@bullet{}) @strong{Exercise 1.}  (This tutorial will include exercises
1788 at various points.  Try them if you wish.  Answers to all the exercises
1789 are located at the end of the Tutorial chapter.  Each exercise will
1790 include a cross-reference to its particular answer.  If you are
1791 reading with the Emacs Info system, press @kbd{f} and the
1792 exercise number to go to the answer, then the letter @kbd{l} to
1793 return to where you were.)
1795 @noindent
1796 Here's the first exercise:  What will the keystrokes @kbd{1 @key{RET} 2
1797 @key{RET} 3 @key{RET} 4 + * -} compute?  (@samp{*} is the symbol for
1798 multiplication.)  Figure it out by hand, then try it with Calc to see
1799 if you're right.  @xref{RPN Answer 1, 1}. (@bullet{})
1801 (@bullet{}) @strong{Exercise 2.}  Compute @c{$(2\times4) + (7\times9.4) + {5\over4}$}
1802 @cite{2*4 + 7*9.5 + 5/4} using the
1803 stack.  @xref{RPN Answer 2, 2}. (@bullet{})
1805 The @key{DEL} key is called Backspace on some keyboards.  It is
1806 whatever key you would use to correct a simple typing error when
1807 regularly using Emacs.  The @key{DEL} key pops and throws away the
1808 top value on the stack.  (You can still get that value back from
1809 the Trail if you should need it later on.)  There are many places
1810 in this tutorial where we assume you have used @key{DEL} to erase the
1811 results of the previous example at the beginning of a new example.
1812 In the few places where it is really important to use @key{DEL} to
1813 clear away old results, the text will remind you to do so.
1815 (It won't hurt to let things accumulate on the stack, except that
1816 whenever you give a display-mode-changing command Calc will have to
1817 spend a long time reformatting such a large stack.)
1819 Since the @kbd{-} key is also an operator (it subtracts the top two
1820 stack elements), how does one enter a negative number?  Calc uses
1821 the @kbd{_} (underscore) key to act like the minus sign in a number.
1822 So, typing @kbd{-5 @key{RET}} won't work because the @kbd{-} key
1823 will try to do a subtraction, but @kbd{_5 @key{RET}} works just fine.
1825 You can also press @kbd{n}, which means ``change sign.''  It changes
1826 the number at the top of the stack (or the number being entered)
1827 from positive to negative or vice-versa:  @kbd{5 n @key{RET}}.
1829 @cindex Duplicating a stack entry
1830 If you press @key{RET} when you're not entering a number, the effect
1831 is to duplicate the top number on the stack.  Consider this calculation:
1833 @group
1834 @smallexample
1835 1:  3          2:  3          1:  9          2:  9          1:  81
1836     .          1:  3              .          1:  9              .
1837                    .                             .
1839   3 RET           RET             *             RET             *
1840 @end smallexample
1841 @end group
1843 @noindent
1844 (Of course, an easier way to do this would be @kbd{3 @key{RET} 4 ^},
1845 to raise 3 to the fourth power.)
1847 The space-bar key (denoted @key{SPC} here) performs the same function
1848 as @key{RET}; you could replace all three occurrences of @key{RET} in
1849 the above example with @key{SPC} and the effect would be the same.
1851 @cindex Exchanging stack entries
1852 Another stack manipulation key is @key{TAB}.  This exchanges the top
1853 two stack entries.  Suppose you have computed @kbd{2 @key{RET} 3 +}
1854 to get 5, and then you realize what you really wanted to compute
1855 was @cite{20 / (2+3)}.
1857 @group
1858 @smallexample
1859 1:  5          2:  5          2:  20         1:  4
1860     .          1:  20         1:  5              .
1861                    .              .
1863  2 RET 3 +         20            TAB             /
1864 @end smallexample
1865 @end group
1867 @noindent
1868 Planning ahead, the calculation would have gone like this:
1870 @group
1871 @smallexample
1872 1:  20         2:  20         3:  20         2:  20         1:  4
1873     .          1:  2          2:  2          1:  5              .
1874                    .          1:  3              .
1875                                   .
1877   20 RET         2 RET            3              +              /
1878 @end smallexample
1879 @end group
1881 A related stack command is @kbd{M-@key{TAB}} (hold @key{META} and type
1882 @key{TAB}).  It rotates the top three elements of the stack upward,
1883 bringing the object in level 3 to the top.
1885 @group
1886 @smallexample
1887 1:  10         2:  10         3:  10         3:  20         3:  30
1888     .          1:  20         2:  20         2:  30         2:  10
1889                    .          1:  30         1:  10         1:  20
1890                                   .              .              .
1892   10 RET         20 RET         30 RET         M-TAB          M-TAB
1893 @end smallexample
1894 @end group
1896 (@bullet{}) @strong{Exercise 3.} Suppose the numbers 10, 20, and 30 are
1897 on the stack.  Figure out how to add one to the number in level 2
1898 without affecting the rest of the stack.  Also figure out how to add
1899 one to the number in level 3.  @xref{RPN Answer 3, 3}. (@bullet{})
1901 Operations like @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/}, and @kbd{^} pop two
1902 arguments from the stack and push a result.  Operations like @kbd{n} and
1903 @kbd{Q} (square root) pop a single number and push the result.  You can
1904 think of them as simply operating on the top element of the stack.
1906 @group
1907 @smallexample
1908 1:  3          1:  9          2:  9          1:  25         1:  5
1909     .              .          1:  16             .              .
1910                                   .
1912   3 RET          RET *        4 RET RET *        +              Q
1913 @end smallexample
1914 @end group
1916 @noindent
1917 (Note that capital @kbd{Q} means to hold down the Shift key while
1918 typing @kbd{q}.  Remember, plain unshifted @kbd{q} is the Quit command.)
1920 @cindex Pythagorean Theorem
1921 Here we've used the Pythagorean Theorem to determine the hypotenuse of a
1922 right triangle.  Calc actually has a built-in command for that called
1923 @kbd{f h}, but let's suppose we can't remember the necessary keystrokes.
1924 We can still enter it by its full name using @kbd{M-x} notation:
1926 @group
1927 @smallexample
1928 1:  3          2:  3          1:  5
1929     .          1:  4              .
1930                    .
1932   3 RET          4 RET      M-x calc-hypot
1933 @end smallexample
1934 @end group
1936 All Calculator commands begin with the word @samp{calc-}.  Since it
1937 gets tiring to type this, Calc provides an @kbd{x} key which is just
1938 like the regular Emacs @kbd{M-x} key except that it types the @samp{calc-}
1939 prefix for you:
1941 @group
1942 @smallexample
1943 1:  3          2:  3          1:  5
1944     .          1:  4              .
1945                    .
1947   3 RET          4 RET         x hypot
1948 @end smallexample
1949 @end group
1951 What happens if you take the square root of a negative number?
1953 @group
1954 @smallexample
1955 1:  4          1:  -4         1:  (0, 2)
1956     .              .              .
1958   4 RET            n              Q
1959 @end smallexample
1960 @end group
1962 @noindent
1963 The notation @cite{(a, b)} represents a complex number.
1964 Complex numbers are more traditionally written @c{$a + b i$}
1965 @cite{a + b i};
1966 Calc can display in this format, too, but for now we'll stick to the
1967 @cite{(a, b)} notation.
1969 If you don't know how complex numbers work, you can safely ignore this
1970 feature.  Complex numbers only arise from operations that would be
1971 errors in a calculator that didn't have complex numbers.  (For example,
1972 taking the square root or logarithm of a negative number produces a
1973 complex result.)
1975 Complex numbers are entered in the notation shown.  The @kbd{(} and
1976 @kbd{,} and @kbd{)} keys manipulate ``incomplete complex numbers.''
1978 @group
1979 @smallexample
1980 1:  ( ...      2:  ( ...      1:  (2, ...    1:  (2, ...    1:  (2, 3)
1981     .          1:  2              .              3              .
1982                    .                             .
1984     (              2              ,              3              )
1985 @end smallexample
1986 @end group
1988 You can perform calculations while entering parts of incomplete objects.
1989 However, an incomplete object cannot actually participate in a calculation:
1991 @group
1992 @smallexample
1993 1:  ( ...      2:  ( ...      3:  ( ...      1:  ( ...      1:  ( ...
1994     .          1:  2          2:  2              5              5
1995                    .          1:  3              .              .
1996                                   .
1997                                                              (error)
1998     (             2 RET           3              +              +
1999 @end smallexample
2000 @end group
2002 @noindent
2003 Adding 5 to an incomplete object makes no sense, so the last command
2004 produces an error message and leaves the stack the same.
2006 Incomplete objects can't participate in arithmetic, but they can be
2007 moved around by the regular stack commands.
2009 @group
2010 @smallexample
2011 2:  2          3:  2          3:  3          1:  ( ...      1:  (2, 3)
2012 1:  3          2:  3          2:  ( ...          2              .
2013     .          1:  ( ...      1:  2              3
2014                    .              .              .
2016 2 RET 3 RET        (            M-TAB          M-TAB            )
2017 @end smallexample
2018 @end group
2020 @noindent
2021 Note that the @kbd{,} (comma) key did not have to be used here.
2022 When you press @kbd{)} all the stack entries between the incomplete
2023 entry and the top are collected, so there's never really a reason
2024 to use the comma.  It's up to you.
2026 (@bullet{}) @strong{Exercise 4.}  To enter the complex number @cite{(2, 3)},
2027 your friend Joe typed @kbd{( 2 , @key{SPC} 3 )}.  What happened?
2028 (Joe thought of a clever way to correct his mistake in only two
2029 keystrokes, but it didn't quite work.  Try it to find out why.)
2030 @xref{RPN Answer 4, 4}. (@bullet{})
2032 Vectors are entered the same way as complex numbers, but with square
2033 brackets in place of parentheses.  We'll meet vectors again later in
2034 the tutorial.
2036 Any Emacs command can be given a @dfn{numeric prefix argument} by
2037 typing a series of @key{META}-digits beforehand.  If @key{META} is
2038 awkward for you, you can instead type @kbd{C-u} followed by the
2039 necessary digits.  Numeric prefix arguments can be negative, as in
2040 @kbd{M-- M-3 M-5} or @w{@kbd{C-u - 3 5}}.  Calc commands use numeric
2041 prefix arguments in a variety of ways.  For example, a numeric prefix
2042 on the @kbd{+} operator adds any number of stack entries at once:
2044 @group
2045 @smallexample
2046 1:  10         2:  10         3:  10         3:  10         1:  60
2047     .          1:  20         2:  20         2:  20             .
2048                    .          1:  30         1:  30
2049                                   .              .
2051   10 RET         20 RET         30 RET         C-u 3            +
2052 @end smallexample
2053 @end group
2055 For stack manipulation commands like @key{RET}, a positive numeric
2056 prefix argument operates on the top @var{n} stack entries at once.  A
2057 negative argument operates on the entry in level @var{n} only.  An
2058 argument of zero operates on the entire stack.  In this example, we copy
2059 the second-to-top element of the stack:
2061 @group
2062 @smallexample
2063 1:  10         2:  10         3:  10         3:  10         4:  10
2064     .          1:  20         2:  20         2:  20         3:  20
2065                    .          1:  30         1:  30         2:  30
2066                                   .              .          1:  20
2067                                                                 .
2069   10 RET         20 RET         30 RET         C-u -2          RET
2070 @end smallexample
2071 @end group
2073 @cindex Clearing the stack
2074 @cindex Emptying the stack
2075 Another common idiom is @kbd{M-0 DEL}, which clears the stack.
2076 (The @kbd{M-0} numeric prefix tells @key{DEL} to operate on the
2077 entire stack.)
2079 @node Algebraic Tutorial, Undo Tutorial, RPN Tutorial, Basic Tutorial
2080 @subsection Algebraic-Style Calculations
2082 @noindent
2083 If you are not used to RPN notation, you may prefer to operate the
2084 Calculator in ``algebraic mode,'' which is closer to the way
2085 non-RPN calculators work.  In algebraic mode, you enter formulas
2086 in traditional @cite{2+3} notation.
2088 You don't really need any special ``mode'' to enter algebraic formulas.
2089 You can enter a formula at any time by pressing the apostrophe (@kbd{'})
2090 key.  Answer the prompt with the desired formula, then press @key{RET}.
2091 The formula is evaluated and the result is pushed onto the RPN stack.
2092 If you don't want to think in RPN at all, you can enter your whole
2093 computation as a formula, read the result from the stack, then press
2094 @key{DEL} to delete it from the stack.
2096 Try pressing the apostrophe key, then @kbd{2+3+4}, then @key{RET}.
2097 The result should be the number 9.
2099 Algebraic formulas use the operators @samp{+}, @samp{-}, @samp{*},
2100 @samp{/}, and @samp{^}.  You can use parentheses to make the order
2101 of evaluation clear.  In the absence of parentheses, @samp{^} is
2102 evaluated first, then @samp{*}, then @samp{/}, then finally
2103 @samp{+} and @samp{-}.  For example, the expression
2105 @example
2106 2 + 3*4*5 / 6*7^8 - 9
2107 @end example
2109 @noindent
2110 is equivalent to
2112 @example
2113 2 + ((3*4*5) / (6*(7^8)) - 9
2114 @end example
2116 @noindent
2117 or, in large mathematical notation,
2119 @ifinfo
2120 @group
2121 @example
2122     3 * 4 * 5
2123 2 + --------- - 9
2124           8
2125      6 * 7
2126 @end example
2127 @end group
2128 @end ifinfo
2129 @tex
2130 \turnoffactive
2131 \beforedisplay
2132 $$ 2 + { 3 \times 4 \times 5 \over 6 \times 7^8 } - 9 $$
2133 \afterdisplay
2134 @end tex
2136 @noindent
2137 The result of this expression will be the number @i{-6.99999826533}.
2139 Calc's order of evaluation is the same as for most computer languages,
2140 except that @samp{*} binds more strongly than @samp{/}, as the above
2141 example shows.  As in normal mathematical notation, the @samp{*} symbol
2142 can often be omitted:  @samp{2 a} is the same as @samp{2*a}.
2144 Operators at the same level are evaluated from left to right, except
2145 that @samp{^} is evaluated from right to left.  Thus, @samp{2-3-4} is
2146 equivalent to @samp{(2-3)-4} or @i{-5}, whereas @samp{2^3^4} is equivalent
2147 to @samp{2^(3^4)} (a very large integer; try it!).
2149 If you tire of typing the apostrophe all the time, there is an
2150 ``algebraic mode'' you can select in which Calc automatically senses
2151 when you are about to type an algebraic expression.  To enter this
2152 mode, press the two letters @w{@kbd{m a}}.  (An @samp{Alg} indicator
2153 should appear in the Calc window's mode line.)
2155 Press @kbd{m a}, then @kbd{2+3+4} with no apostrophe, then @key{RET}.
2157 In algebraic mode, when you press any key that would normally begin
2158 entering a number (such as a digit, a decimal point, or the @kbd{_}
2159 key), or if you press @kbd{(} or @kbd{[}, Calc automatically begins
2160 an algebraic entry.
2162 Functions which do not have operator symbols like @samp{+} and @samp{*}
2163 must be entered in formulas using function-call notation.  For example,
2164 the function name corresponding to the square-root key @kbd{Q} is
2165 @code{sqrt}.  To compute a square root in a formula, you would use
2166 the notation @samp{sqrt(@var{x})}.
2168 Press the apostrophe, then type @kbd{sqrt(5*2) - 3}.  The result should
2169 be @cite{0.16227766017}.
2171 Note that if the formula begins with a function name, you need to use
2172 the apostrophe even if you are in algebraic mode.  If you type @kbd{arcsin}
2173 out of the blue, the @kbd{a r} will be taken as an Algebraic Rewrite
2174 command, and the @kbd{csin} will be taken as the name of the rewrite
2175 rule to use!
2177 Some people prefer to enter complex numbers and vectors in algebraic
2178 form because they find RPN entry with incomplete objects to be too
2179 distracting, even though they otherwise use Calc as an RPN calculator.
2181 Still in algebraic mode, type:
2183 @group
2184 @smallexample
2185 1:  (2, 3)     2:  (2, 3)     1:  (8, -1)    2:  (8, -1)    1:  (9, -1)
2186     .          1:  (1, -2)        .          1:  1              .
2187                    .                             .
2189  (2,3) RET      (1,-2) RET        *              1 RET          +
2190 @end smallexample
2191 @end group
2193 Algebraic mode allows us to enter complex numbers without pressing
2194 an apostrophe first, but it also means we need to press @key{RET}
2195 after every entry, even for a simple number like @cite{1}.
2197 (You can type @kbd{C-u m a} to enable a special ``incomplete algebraic
2198 mode'' in which the @kbd{(} and @kbd{[} keys use algebraic entry even
2199 though regular numeric keys still use RPN numeric entry.  There is also
2200 a ``total algebraic mode,'' started by typing @kbd{m t}, in which all
2201 normal keys begin algebraic entry.  You must then use the @key{META} key
2202 to type Calc commands:  @kbd{M-m t} to get back out of total algebraic
2203 mode, @kbd{M-q} to quit, etc.  Total algebraic mode is not supported
2204 under Emacs 19.)
2206 If you're still in algebraic mode, press @kbd{m a} again to turn it off.
2208 Actual non-RPN calculators use a mixture of algebraic and RPN styles.
2209 In general, operators of two numbers (like @kbd{+} and @kbd{*})
2210 use algebraic form, but operators of one number (like @kbd{n} and @kbd{Q})
2211 use RPN form.  Also, a non-RPN calculator allows you to see the
2212 intermediate results of a calculation as you go along.  You can
2213 accomplish this in Calc by performing your calculation as a series
2214 of algebraic entries, using the @kbd{$} sign to tie them together.
2215 In an algebraic formula, @kbd{$} represents the number on the top
2216 of the stack.  Here, we perform the calculation @c{$\sqrt{2\times4+1}$}
2217 @cite{sqrt(2*4+1)},
2218 which on a traditional calculator would be done by pressing
2219 @kbd{2 * 4 + 1 =} and then the square-root key.
2221 @group
2222 @smallexample
2223 1:  8          1:  9          1:  3
2224     .              .              .
2226   ' 2*4 RET        $+1 RET        Q
2227 @end smallexample
2228 @end group
2230 @noindent
2231 Notice that we didn't need to press an apostrophe for the @kbd{$+1},
2232 because the dollar sign always begins an algebraic entry.
2234 (@bullet{}) @strong{Exercise 1.}  How could you get the same effect as
2235 pressing @kbd{Q} but using an algebraic entry instead?  How about
2236 if the @kbd{Q} key on your keyboard were broken?
2237 @xref{Algebraic Answer 1, 1}. (@bullet{})
2239 The notations @kbd{$$}, @kbd{$$$}, and so on stand for higher stack
2240 entries.  For example, @kbd{' $$+$ RET} is just like typing @kbd{+}.
2242 Algebraic formulas can include @dfn{variables}.  To store in a
2243 variable, press @kbd{s s}, then type the variable name, then press
2244 @key{RET}.  (There are actually two flavors of store command:
2245 @kbd{s s} stores a number in a variable but also leaves the number
2246 on the stack, while @w{@kbd{s t}} removes a number from the stack and
2247 stores it in the variable.)  A variable name should consist of one
2248 or more letters or digits, beginning with a letter.
2250 @group
2251 @smallexample
2252 1:  17             .          1:  a + a^2    1:  306
2253     .                             .              .
2255     17          s t a RET      ' a+a^2 RET       =
2256 @end smallexample
2257 @end group
2259 @noindent
2260 The @kbd{=} key @dfn{evaluates} a formula by replacing all its
2261 variables by the values that were stored in them.
2263 For RPN calculations, you can recall a variable's value on the
2264 stack either by entering its name as a formula and pressing @kbd{=},
2265 or by using the @kbd{s r} command.
2267 @group
2268 @smallexample
2269 1:  17         2:  17         3:  17         2:  17         1:  306
2270     .          1:  17         2:  17         1:  289            .
2271                    .          1:  2              .
2272                                   .
2274   s r a RET     ' a RET =         2              ^              +
2275 @end smallexample
2276 @end group
2278 If you press a single digit for a variable name (as in @kbd{s t 3}, you
2279 get one of ten @dfn{quick variables} @code{q0} through @code{q9}.
2280 They are ``quick'' simply because you don't have to type the letter
2281 @code{q} or the @key{RET} after their names.  In fact, you can type
2282 simply @kbd{s 3} as a shorthand for @kbd{s s 3}, and likewise for
2283 @kbd{t 3} and @w{@kbd{r 3}}.
2285 Any variables in an algebraic formula for which you have not stored
2286 values are left alone, even when you evaluate the formula.
2288 @group
2289 @smallexample
2290 1:  2 a + 2 b     1:  34 + 2 b
2291     .                 .
2293  ' 2a+2b RET          =
2294 @end smallexample
2295 @end group
2297 Calls to function names which are undefined in Calc are also left
2298 alone, as are calls for which the value is undefined.
2300 @group
2301 @smallexample
2302 1:  2 + log10(0) + log10(x) + log10(5, 6) + foo(3)
2303     .
2305  ' log10(100) + log10(0) + log10(x) + log10(5,6) + foo(3) RET
2306 @end smallexample
2307 @end group
2309 @noindent
2310 In this example, the first call to @code{log10} works, but the other
2311 calls are not evaluated.  In the second call, the logarithm is
2312 undefined for that value of the argument; in the third, the argument
2313 is symbolic, and in the fourth, there are too many arguments.  In the
2314 fifth case, there is no function called @code{foo}.  You will see a
2315 ``Wrong number of arguments'' message referring to @samp{log10(5,6)}.
2316 Press the @kbd{w} (``why'') key to see any other messages that may
2317 have arisen from the last calculation.  In this case you will get
2318 ``logarithm of zero,'' then ``number expected: @code{x}''.  Calc
2319 automatically displays the first message only if the message is
2320 sufficiently important; for example, Calc considers ``wrong number
2321 of arguments'' and ``logarithm of zero'' to be important enough to
2322 report automatically, while a message like ``number expected: @code{x}''
2323 will only show up if you explicitly press the @kbd{w} key.
2325 (@bullet{}) @strong{Exercise 2.}  Joe entered the formula @samp{2 x y},
2326 stored 5 in @code{x}, pressed @kbd{=}, and got the expected result,
2327 @samp{10 y}.  He then tried the same for the formula @samp{2 x (1+y)},
2328 expecting @samp{10 (1+y)}, but it didn't work.  Why not?
2329 @xref{Algebraic Answer 2, 2}. (@bullet{})
2331 (@bullet{}) @strong{Exercise 3.}  What result would you expect
2332 @kbd{1 @key{RET} 0 /} to give?  What if you then type @kbd{0 *}?
2333 @xref{Algebraic Answer 3, 3}. (@bullet{})
2335 One interesting way to work with variables is to use the
2336 @dfn{evaluates-to} (@samp{=>}) operator.  It works like this:
2337 Enter a formula algebraically in the usual way, but follow
2338 the formula with an @samp{=>} symbol.  (There is also an @kbd{s =}
2339 command which builds an @samp{=>} formula using the stack.)  On
2340 the stack, you will see two copies of the formula with an @samp{=>}
2341 between them.  The lefthand formula is exactly like you typed it;
2342 the righthand formula has been evaluated as if by typing @kbd{=}.
2344 @group
2345 @smallexample
2346 2:  2 + 3 => 5                     2:  2 + 3 => 5
2347 1:  2 a + 2 b => 34 + 2 b          1:  2 a + 2 b => 20 + 2 b
2348     .                                  .
2350 ' 2+3 => RET  ' 2a+2b RET s =          10 s t a RET
2351 @end smallexample
2352 @end group
2354 @noindent
2355 Notice that the instant we stored a new value in @code{a}, all
2356 @samp{=>} operators already on the stack that referred to @cite{a}
2357 were updated to use the new value.  With @samp{=>}, you can push a
2358 set of formulas on the stack, then change the variables experimentally
2359 to see the effects on the formulas' values.
2361 You can also ``unstore'' a variable when you are through with it:
2363 @group
2364 @smallexample
2365 2:  2 + 5 => 5
2366 1:  2 a + 2 b => 2 a + 2 b
2367     .
2369     s u a RET
2370 @end smallexample
2371 @end group
2373 We will encounter formulas involving variables and functions again
2374 when we discuss the algebra and calculus features of the Calculator.
2376 @node Undo Tutorial, Modes Tutorial, Algebraic Tutorial, Basic Tutorial
2377 @subsection Undo and Redo
2379 @noindent
2380 If you make a mistake, you can usually correct it by pressing shift-@kbd{U},
2381 the ``undo'' command.  First, clear the stack (@kbd{M-0 DEL}) and exit
2382 and restart Calc (@kbd{M-# M-# M-# M-#}) to make sure things start off
2383 with a clean slate.  Now:
2385 @group
2386 @smallexample
2387 1:  2          2:  2          1:  8          2:  2          1:  6
2388     .          1:  3              .          1:  3              .
2389                    .                             .
2391    2 RET           3              ^              U              *
2392 @end smallexample
2393 @end group
2395 You can undo any number of times.  Calc keeps a complete record of
2396 all you have done since you last opened the Calc window.  After the
2397 above example, you could type:
2399 @group
2400 @smallexample
2401 1:  6          2:  2          1:  2              .              .
2402     .          1:  3              .
2403                    .
2404                                                              (error)
2405                    U              U              U              U
2406 @end smallexample
2407 @end group
2409 You can also type @kbd{D} to ``redo'' a command that you have undone
2410 mistakenly.
2412 @group
2413 @smallexample
2414     .          1:  2          2:  2          1:  6          1:  6
2415                    .          1:  3              .              .
2416                                   .
2417                                                              (error)
2418                    D              D              D              D
2419 @end smallexample
2420 @end group
2422 @noindent
2423 It was not possible to redo past the @cite{6}, since that was placed there
2424 by something other than an undo command.
2426 @cindex Time travel
2427 You can think of undo and redo as a sort of ``time machine.''  Press
2428 @kbd{U} to go backward in time, @kbd{D} to go forward.  If you go
2429 backward and do something (like @kbd{*}) then, as any science fiction
2430 reader knows, you have changed your future and you cannot go forward
2431 again.  Thus, the inability to redo past the @cite{6} even though there
2432 was an earlier undo command.
2434 You can always recall an earlier result using the Trail.  We've ignored
2435 the trail so far, but it has been faithfully recording everything we
2436 did since we loaded the Calculator.  If the Trail is not displayed,
2437 press @kbd{t d} now to turn it on.
2439 Let's try grabbing an earlier result.  The @cite{8} we computed was
2440 undone by a @kbd{U} command, and was lost even to Redo when we pressed
2441 @kbd{*}, but it's still there in the trail.  There should be a little
2442 @samp{>} arrow (the @dfn{trail pointer}) resting on the last trail
2443 entry.  If there isn't, press @kbd{t ]} to reset the trail pointer.
2444 Now, press @w{@kbd{t p}} to move the arrow onto the line containing
2445 @cite{8}, and press @w{@kbd{t y}} to ``yank'' that number back onto the
2446 stack.
2448 If you press @kbd{t ]} again, you will see that even our Yank command
2449 went into the trail.
2451 Let's go further back in time.  Earlier in the tutorial we computed
2452 a huge integer using the formula @samp{2^3^4}.  We don't remember
2453 what it was, but the first digits were ``241''.  Press @kbd{t r}
2454 (which stands for trail-search-reverse), then type @kbd{241}.
2455 The trail cursor will jump back to the next previous occurrence of
2456 the string ``241'' in the trail.  This is just a regular Emacs
2457 incremental search; you can now press @kbd{C-s} or @kbd{C-r} to
2458 continue the search forwards or backwards as you like.
2460 To finish the search, press @key{RET}.  This halts the incremental
2461 search and leaves the trail pointer at the thing we found.  Now we
2462 can type @kbd{t y} to yank that number onto the stack.  If we hadn't
2463 remembered the ``241'', we could simply have searched for @kbd{2^3^4},
2464 then pressed @kbd{@key{RET} t n} to halt and then move to the next item.
2466 You may have noticed that all the trail-related commands begin with
2467 the letter @kbd{t}.  (The store-and-recall commands, on the other hand,
2468 all began with @kbd{s}.)  Calc has so many commands that there aren't
2469 enough keys for all of them, so various commands are grouped into
2470 two-letter sequences where the first letter is called the @dfn{prefix}
2471 key.  If you type a prefix key by accident, you can press @kbd{C-g}
2472 to cancel it.  (In fact, you can press @kbd{C-g} to cancel almost
2473 anything in Emacs.)  To get help on a prefix key, press that key
2474 followed by @kbd{?}.  Some prefixes have several lines of help,
2475 so you need to press @kbd{?} repeatedly to see them all.  This may
2476 not work under Lucid Emacs, but you can also type @kbd{h h} to
2477 see all the help at once.
2479 Try pressing @kbd{t ?} now.  You will see a line of the form,
2481 @smallexample
2482 trail/time: Display; Fwd, Back; Next, Prev, Here, [, ]; Yank:  [MORE]  t-
2483 @end smallexample
2485 @noindent
2486 The word ``trail'' indicates that the @kbd{t} prefix key contains
2487 trail-related commands.  Each entry on the line shows one command,
2488 with a single capital letter showing which letter you press to get
2489 that command.  We have used @kbd{t n}, @kbd{t p}, @kbd{t ]}, and
2490 @kbd{t y} so far.  The @samp{[MORE]} means you can press @kbd{?}
2491 again to see more @kbd{t}-prefix comands.  Notice that the commands
2492 are roughly divided (by semicolons) into related groups.
2494 When you are in the help display for a prefix key, the prefix is
2495 still active.  If you press another key, like @kbd{y} for example,
2496 it will be interpreted as a @kbd{t y} command.  If all you wanted
2497 was to look at the help messages, press @kbd{C-g} afterwards to cancel
2498 the prefix.
2500 One more way to correct an error is by editing the stack entries.
2501 The actual Stack buffer is marked read-only and must not be edited
2502 directly, but you can press @kbd{`} (the backquote or accent grave)
2503 to edit a stack entry.
2505 Try entering @samp{3.141439} now.  If this is supposed to represent
2506 @c{$\pi$}
2507 @cite{pi}, it's got several errors.  Press @kbd{`} to edit this number.
2508 Now use the normal Emacs cursor motion and editing keys to change
2509 the second 4 to a 5, and to transpose the 3 and the 9.  When you
2510 press @key{RET}, the number on the stack will be replaced by your
2511 new number.  This works for formulas, vectors, and all other types
2512 of values you can put on the stack.  The @kbd{`} key also works
2513 during entry of a number or algebraic formula.
2515 @node Modes Tutorial, , Undo Tutorial, Basic Tutorial
2516 @subsection Mode-Setting Commands
2518 @noindent
2519 Calc has many types of @dfn{modes} that affect the way it interprets
2520 your commands or the way it displays data.  We have already seen one
2521 mode, namely algebraic mode.  There are many others, too; we'll
2522 try some of the most common ones here.
2524 Perhaps the most fundamental mode in Calc is the current @dfn{precision}.
2525 Notice the @samp{12} on the Calc window's mode line:
2527 @smallexample
2528 --%%-Calc: 12 Deg       (Calculator)----All------
2529 @end smallexample
2531 @noindent
2532 Most of the symbols there are Emacs things you don't need to worry
2533 about, but the @samp{12} and the @samp{Deg} are mode indicators.
2534 The @samp{12} means that calculations should always be carried to
2535 12 significant figures.  That is why, when we type @kbd{1 @key{RET} 7 /},
2536 we get @cite{0.142857142857} with exactly 12 digits, not counting
2537 leading and trailing zeros.
2539 You can set the precision to anything you like by pressing @kbd{p},
2540 then entering a suitable number.  Try pressing @kbd{p 30 @key{RET}},
2541 then doing @kbd{1 @key{RET} 7 /} again:
2543 @group
2544 @smallexample
2545 1:  0.142857142857
2546 2:  0.142857142857142857142857142857
2547     .
2548 @end smallexample
2549 @end group
2551 Although the precision can be set arbitrarily high, Calc always
2552 has to have @emph{some} value for the current precision.  After
2553 all, the true value @cite{1/7} is an infinitely repeating decimal;
2554 Calc has to stop somewhere.
2556 Of course, calculations are slower the more digits you request.
2557 Press @w{@kbd{p 12}} now to set the precision back down to the default.
2559 Calculations always use the current precision.  For example, even
2560 though we have a 30-digit value for @cite{1/7} on the stack, if
2561 we use it in a calculation in 12-digit mode it will be rounded
2562 down to 12 digits before it is used.  Try it; press @key{RET} to
2563 duplicate the number, then @w{@kbd{1 +}}.  Notice that the @key{RET}
2564 key didn't round the number, because it doesn't do any calculation.
2565 But the instant we pressed @kbd{+}, the number was rounded down.
2567 @group
2568 @smallexample
2569 1:  0.142857142857
2570 2:  0.142857142857142857142857142857
2571 3:  1.14285714286
2572     .
2573 @end smallexample
2574 @end group
2576 @noindent
2577 In fact, since we added a digit on the left, we had to lose one
2578 digit on the right from even the 12-digit value of @cite{1/7}.
2580 How did we get more than 12 digits when we computed @samp{2^3^4}?  The
2581 answer is that Calc makes a distinction between @dfn{integers} and
2582 @dfn{floating-point} numbers, or @dfn{floats}.  An integer is a number
2583 that does not contain a decimal point.  There is no such thing as an
2584 ``infinitely repeating fraction integer,'' so Calc doesn't have to limit
2585 itself.  If you asked for @samp{2^10000} (don't try this!), you would
2586 have to wait a long time but you would eventually get an exact answer.
2587 If you ask for @samp{2.^10000}, you will quickly get an answer which is
2588 correct only to 12 places.  The decimal point tells Calc that it should
2589 use floating-point arithmetic to get the answer, not exact integer
2590 arithmetic.
2592 You can use the @kbd{F} (@code{calc-floor}) command to convert a
2593 floating-point value to an integer, and @kbd{c f} (@code{calc-float})
2594 to convert an integer to floating-point form.
2596 Let's try entering that last calculation:
2598 @group
2599 @smallexample
2600 1:  2.         2:  2.         1:  1.99506311689e3010
2601     .          1:  10000          .
2602                    .
2604   2.0 RET          10000 RET      ^
2605 @end smallexample
2606 @end group
2608 @noindent
2609 @cindex Scientific notation, entry of
2610 Notice the letter @samp{e} in there.  It represents ``times ten to the
2611 power of,'' and is used by Calc automatically whenever writing the
2612 number out fully would introduce more extra zeros than you probably
2613 want to see.  You can enter numbers in this notation, too.
2615 @group
2616 @smallexample
2617 1:  2.         2:  2.         1:  1.99506311678e3010
2618     .          1:  10000.         .
2619                    .
2621   2.0 RET          1e4 RET        ^
2622 @end smallexample
2623 @end group
2625 @cindex Round-off errors
2626 @noindent
2627 Hey, the answer is different!  Look closely at the middle columns
2628 of the two examples.  In the first, the stack contained the
2629 exact integer @cite{10000}, but in the second it contained
2630 a floating-point value with a decimal point.  When you raise a
2631 number to an integer power, Calc uses repeated squaring and
2632 multiplication to get the answer.  When you use a floating-point
2633 power, Calc uses logarithms and exponentials.  As you can see,
2634 a slight error crept in during one of these methods.  Which
2635 one should we trust?  Let's raise the precision a bit and find
2636 out:
2638 @group
2639 @smallexample
2640     .          1:  2.         2:  2.         1:  1.995063116880828e3010
2641                    .          1:  10000.         .
2642                                   .
2644  p 16 RET        2. RET           1e4            ^    p 12 RET
2645 @end smallexample
2646 @end group
2648 @noindent
2649 @cindex Guard digits
2650 Presumably, it doesn't matter whether we do this higher-precision
2651 calculation using an integer or floating-point power, since we
2652 have added enough ``guard digits'' to trust the first 12 digits
2653 no matter what.  And the verdict is@dots{}  Integer powers were more
2654 accurate; in fact, the result was only off by one unit in the
2655 last place.
2657 @cindex Guard digits
2658 Calc does many of its internal calculations to a slightly higher
2659 precision, but it doesn't always bump the precision up enough.
2660 In each case, Calc added about two digits of precision during
2661 its calculation and then rounded back down to 12 digits
2662 afterward.  In one case, it was enough; in the the other, it
2663 wasn't.  If you really need @var{x} digits of precision, it
2664 never hurts to do the calculation with a few extra guard digits.
2666 What if we want guard digits but don't want to look at them?
2667 We can set the @dfn{float format}.  Calc supports four major
2668 formats for floating-point numbers, called @dfn{normal},
2669 @dfn{fixed-point}, @dfn{scientific notation}, and @dfn{engineering
2670 notation}.  You get them by pressing @w{@kbd{d n}}, @kbd{d f},
2671 @kbd{d s}, and @kbd{d e}, respectively.  In each case, you can
2672 supply a numeric prefix argument which says how many digits
2673 should be displayed.  As an example, let's put a few numbers
2674 onto the stack and try some different display modes.  First,
2675 use @kbd{M-0 DEL} to clear the stack, then enter the four
2676 numbers shown here:
2678 @group
2679 @smallexample
2680 4:  12345      4:  12345      4:  12345      4:  12345      4:  12345
2681 3:  12345.     3:  12300.     3:  1.2345e4   3:  1.23e4     3:  12345.000
2682 2:  123.45     2:  123.       2:  1.2345e2   2:  1.23e2     2:  123.450
2683 1:  12.345     1:  12.3       1:  1.2345e1   1:  1.23e1     1:  12.345
2684     .              .              .              .              .
2686    d n          M-3 d n          d s          M-3 d s        M-3 d f
2687 @end smallexample
2688 @end group
2690 @noindent
2691 Notice that when we typed @kbd{M-3 d n}, the numbers were rounded down
2692 to three significant digits, but then when we typed @kbd{d s} all
2693 five significant figures reappeared.  The float format does not
2694 affect how numbers are stored, it only affects how they are
2695 displayed.  Only the current precision governs the actual rounding
2696 of numbers in the Calculator's memory.
2698 Engineering notation, not shown here, is like scientific notation
2699 except the exponent (the power-of-ten part) is always adjusted to be
2700 a multiple of three (as in ``kilo,'' ``micro,'' etc.).  As a result
2701 there will be one, two, or three digits before the decimal point.
2703 Whenever you change a display-related mode, Calc redraws everything
2704 in the stack.  This may be slow if there are many things on the stack,
2705 so Calc allows you to type shift-@kbd{H} before any mode command to
2706 prevent it from updating the stack.  Anything Calc displays after the
2707 mode-changing command will appear in the new format.
2709 @group
2710 @smallexample
2711 4:  12345      4:  12345      4:  12345      4:  12345      4:  12345
2712 3:  12345.000  3:  12345.000  3:  12345.000  3:  1.2345e4   3:  12345.
2713 2:  123.450    2:  123.450    2:  1.2345e1   2:  1.2345e1   2:  123.45
2714 1:  12.345     1:  1.2345e1   1:  1.2345e2   1:  1.2345e2   1:  12.345
2715     .              .              .              .              .
2717     H d s          DEL U          TAB            d SPC          d n
2718 @end smallexample
2719 @end group
2721 @noindent
2722 Here the @kbd{H d s} command changes to scientific notation but without
2723 updating the screen.  Deleting the top stack entry and undoing it back
2724 causes it to show up in the new format; swapping the top two stack
2725 entries reformats both entries.  The @kbd{d SPC} command refreshes the
2726 whole stack.  The @kbd{d n} command changes back to the normal float
2727 format; since it doesn't have an @kbd{H} prefix, it also updates all
2728 the stack entries to be in @kbd{d n} format.
2730 Notice that the integer @cite{12345} was not affected by any
2731 of the float formats.  Integers are integers, and are always
2732 displayed exactly.
2734 @cindex Large numbers, readability
2735 Large integers have their own problems.  Let's look back at
2736 the result of @kbd{2^3^4}.
2738 @example
2739 2417851639229258349412352
2740 @end example
2742 @noindent
2743 Quick---how many digits does this have?  Try typing @kbd{d g}:
2745 @example
2746 2,417,851,639,229,258,349,412,352
2747 @end example
2749 @noindent
2750 Now how many digits does this have?  It's much easier to tell!
2751 We can actually group digits into clumps of any size.  Some
2752 people prefer @kbd{M-5 d g}:
2754 @example
2755 24178,51639,22925,83494,12352
2756 @end example
2758 Let's see what happens to floating-point numbers when they are grouped.
2759 First, type @kbd{p 25 @key{RET}} to make sure we have enough precision
2760 to get ourselves into trouble.  Now, type @kbd{1e13 /}:
2762 @example
2763 24,17851,63922.9258349412352
2764 @end example
2766 @noindent
2767 The integer part is grouped but the fractional part isn't.  Now try
2768 @kbd{M-- M-5 d g} (that's meta-minus-sign, meta-five):
2770 @example
2771 24,17851,63922.92583,49412,352
2772 @end example
2774 If you find it hard to tell the decimal point from the commas, try
2775 changing the grouping character to a space with @kbd{d , @key{SPC}}:
2777 @example
2778 24 17851 63922.92583 49412 352
2779 @end example
2781 Type @kbd{d , ,} to restore the normal grouping character, then
2782 @kbd{d g} again to turn grouping off.  Also, press @kbd{p 12} to
2783 restore the default precision.
2785 Press @kbd{U} enough times to get the original big integer back.
2786 (Notice that @kbd{U} does not undo each mode-setting command; if
2787 you want to undo a mode-setting command, you have to do it yourself.)
2788 Now, type @kbd{d r 16 @key{RET}}:
2790 @example
2791 16#200000000000000000000
2792 @end example
2794 @noindent
2795 The number is now displayed in @dfn{hexadecimal}, or ``base-16'' form.
2796 Suddenly it looks pretty simple; this should be no surprise, since we
2797 got this number by computing a power of two, and 16 is a power of 2.
2798 In fact, we can use @w{@kbd{d r 2 @key{RET}}} to see it in actual binary
2799 form:
2801 @example
2802 2#1000000000000000000000000000000000000000000000000000000 @dots{}
2803 @end example
2805 @noindent
2806 We don't have enough space here to show all the zeros!  They won't
2807 fit on a typical screen, either, so you will have to use horizontal
2808 scrolling to see them all.  Press @kbd{<} and @kbd{>} to scroll the
2809 stack window left and right by half its width.  Another way to view
2810 something large is to press @kbd{`} (back-quote) to edit the top of
2811 stack in a separate window.  (Press @kbd{M-# M-#} when you are done.)
2813 You can enter non-decimal numbers using the @kbd{#} symbol, too.
2814 Let's see what the hexadecimal number @samp{5FE} looks like in
2815 binary.  Type @kbd{16#5FE} (the letters can be typed in upper or
2816 lower case; they will always appear in upper case).  It will also
2817 help to turn grouping on with @kbd{d g}:
2819 @example
2820 2#101,1111,1110
2821 @end example
2823 Notice that @kbd{d g} groups by fours by default if the display radix
2824 is binary or hexadecimal, but by threes if it is decimal, octal, or any
2825 other radix.
2827 Now let's see that number in decimal; type @kbd{d r 10}:
2829 @example
2830 1,534
2831 @end example
2833 Numbers are not @emph{stored} with any particular radix attached.  They're
2834 just numbers; they can be entered in any radix, and are always displayed
2835 in whatever radix you've chosen with @kbd{d r}.  The current radix applies
2836 to integers, fractions, and floats.
2838 @cindex Roundoff errors, in non-decimal numbers
2839 (@bullet{}) @strong{Exercise 1.}  Your friend Joe tried to enter one-third
2840 as @samp{3#0.1} in @kbd{d r 3} mode with a precision of 12.  He got
2841 @samp{3#0.0222222...} (with 25 2's) in the display.  When he multiplied
2842 that by three, he got @samp{3#0.222222...} instead of the expected
2843 @samp{3#1}.  Next, Joe entered @samp{3#0.2} and, to his great relief,
2844 saw @samp{3#0.2} on the screen.  But when he typed @kbd{2 /}, he got
2845 @samp{3#0.10000001} (some zeros omitted).  What's going on here?
2846 @xref{Modes Answer 1, 1}. (@bullet{})
2848 @cindex Scientific notation, in non-decimal numbers
2849 (@bullet{}) @strong{Exercise 2.}  Scientific notation works in non-decimal
2850 modes in the natural way (the exponent is a power of the radix instead of
2851 a power of ten, although the exponent itself is always written in decimal).
2852 Thus @samp{8#1.23e3 = 8#1230.0}.  Suppose we have the hexadecimal number
2853 @samp{f.e8f} times 16 to the 15th power:  We write @samp{16#f.e8fe15}.
2854 What is wrong with this picture?  What could we write instead that would
2855 work better?  @xref{Modes Answer 2, 2}. (@bullet{})
2857 The @kbd{m} prefix key has another set of modes, relating to the way
2858 Calc interprets your inputs and does computations.  Whereas @kbd{d}-prefix
2859 modes generally affect the way things look, @kbd{m}-prefix modes affect
2860 the way they are actually computed.
2862 The most popular @kbd{m}-prefix mode is the @dfn{angular mode}.  Notice
2863 the @samp{Deg} indicator in the mode line.  This means that if you use
2864 a command that interprets a number as an angle, it will assume the
2865 angle is measured in degrees.  For example,
2867 @group
2868 @smallexample
2869 1:  45         1:  0.707106781187   1:  0.500000000001    1:  0.5
2870     .              .                    .                     .
2872     45             S                    2 ^                   c 1
2873 @end smallexample
2874 @end group
2876 @noindent
2877 The shift-@kbd{S} command computes the sine of an angle.  The sine
2878 of 45 degrees is @c{$\sqrt{2}/2$}
2879 @cite{sqrt(2)/2}; squaring this yields @cite{2/4 = 0.5}.
2880 However, there has been a slight roundoff error because the
2881 representation of @c{$\sqrt{2}/2$}
2882 @cite{sqrt(2)/2} wasn't exact.  The @kbd{c 1}
2883 command is a handy way to clean up numbers in this case; it
2884 temporarily reduces the precision by one digit while it
2885 re-rounds the number on the top of the stack.
2887 @cindex Roundoff errors, examples
2888 (@bullet{}) @strong{Exercise 3.}  Your friend Joe computed the sine
2889 of 45 degrees as shown above, then, hoping to avoid an inexact
2890 result, he increased the precision to 16 digits before squaring.
2891 What happened?  @xref{Modes Answer 3, 3}. (@bullet{})
2893 To do this calculation in radians, we would type @kbd{m r} first.
2894 (The indicator changes to @samp{Rad}.)  45 degrees corresponds to
2895 @c{$\pi\over4$}
2896 @cite{pi/4} radians.  To get @c{$\pi$}
2897 @cite{pi}, press the @kbd{P} key.  (Once
2898 again, this is a shifted capital @kbd{P}.  Remember, unshifted
2899 @kbd{p} sets the precision.)
2901 @group
2902 @smallexample
2903 1:  3.14159265359   1:  0.785398163398   1:  0.707106781187
2904     .                   .                .
2906     P                   4 /       m r    S
2907 @end smallexample
2908 @end group
2910 Likewise, inverse trigonometric functions generate results in
2911 either radians or degrees, depending on the current angular mode.
2913 @group
2914 @smallexample
2915 1:  0.707106781187   1:  0.785398163398   1:  45.
2916     .                    .                    .
2918     .5 Q        m r      I S        m d       U I S
2919 @end smallexample
2920 @end group
2922 @noindent
2923 Here we compute the Inverse Sine of @c{$\sqrt{0.5}$}
2924 @cite{sqrt(0.5)}, first in
2925 radians, then in degrees.
2927 Use @kbd{c d} and @kbd{c r} to convert a number from radians to degrees
2928 and vice-versa.
2930 @group
2931 @smallexample
2932 1:  45         1:  0.785398163397     1:  45.
2933     .              .                      .
2935     45             c r                    c d
2936 @end smallexample
2937 @end group
2939 Another interesting mode is @dfn{fraction mode}.  Normally,
2940 dividing two integers produces a floating-point result if the
2941 quotient can't be expressed as an exact integer.  Fraction mode
2942 causes integer division to produce a fraction, i.e., a rational
2943 number, instead.
2945 @group
2946 @smallexample
2947 2:  12         1:  1.33333333333    1:  4:3
2948 1:  9              .                    .
2949     .
2951  12 RET 9          /          m f       U /      m f
2952 @end smallexample
2953 @end group
2955 @noindent
2956 In the first case, we get an approximate floating-point result.
2957 In the second case, we get an exact fractional result (four-thirds).
2959 You can enter a fraction at any time using @kbd{:} notation.
2960 (Calc uses @kbd{:} instead of @kbd{/} as the fraction separator
2961 because @kbd{/} is already used to divide the top two stack
2962 elements.)  Calculations involving fractions will always
2963 produce exact fractional results; fraction mode only says
2964 what to do when dividing two integers.
2966 @cindex Fractions vs. floats
2967 @cindex Floats vs. fractions
2968 (@bullet{}) @strong{Exercise 4.}  If fractional arithmetic is exact,
2969 why would you ever use floating-point numbers instead?
2970 @xref{Modes Answer 4, 4}. (@bullet{})
2972 Typing @kbd{m f} doesn't change any existing values in the stack.
2973 In the above example, we had to Undo the division and do it over
2974 again when we changed to fraction mode.  But if you use the
2975 evaluates-to operator you can get commands like @kbd{m f} to
2976 recompute for you.
2978 @group
2979 @smallexample
2980 1:  12 / 9 => 1.33333333333    1:  12 / 9 => 1.333    1:  12 / 9 => 4:3
2981     .                              .                      .
2983    ' 12/9 => RET                   p 4 RET                m f
2984 @end smallexample
2985 @end group
2987 @noindent
2988 In this example, the righthand side of the @samp{=>} operator
2989 on the stack is recomputed when we change the precision, then
2990 again when we change to fraction mode.  All @samp{=>} expressions
2991 on the stack are recomputed every time you change any mode that
2992 might affect their values.
2994 @node Arithmetic Tutorial, Vector/Matrix Tutorial, Basic Tutorial, Tutorial
2995 @section Arithmetic Tutorial
2997 @noindent
2998 In this section, we explore the arithmetic and scientific functions
2999 available in the Calculator.
3001 The standard arithmetic commands are @kbd{+}, @kbd{-}, @kbd{*}, @kbd{/},
3002 and @kbd{^}.  Each normally takes two numbers from the top of the stack
3003 and pushes back a result.  The @kbd{n} and @kbd{&} keys perform
3004 change-sign and reciprocal operations, respectively.
3006 @group
3007 @smallexample
3008 1:  5          1:  0.2        1:  5.         1:  -5.        1:  5.
3009     .              .              .              .              .
3011     5              &              &              n              n
3012 @end smallexample
3013 @end group
3015 @cindex Binary operators
3016 You can apply a ``binary operator'' like @kbd{+} across any number of
3017 stack entries by giving it a numeric prefix.  You can also apply it
3018 pairwise to several stack elements along with the top one if you use
3019 a negative prefix.
3021 @group
3022 @smallexample
3023 3:  2          1:  9          3:  2          4:  2          3:  12
3024 2:  3              .          2:  3          3:  3          2:  13
3025 1:  4                         1:  4          2:  4          1:  14
3026     .                             .          1:  10             .
3027                                                  .
3029 2 RET 3 RET 4     M-3 +           U              10          M-- M-3 +
3030 @end smallexample
3031 @end group
3033 @cindex Unary operators
3034 You can apply a ``unary operator'' like @kbd{&} to the top @var{n}
3035 stack entries with a numeric prefix, too.
3037 @group
3038 @smallexample
3039 3:  2          3:  0.5                3:  0.5
3040 2:  3          2:  0.333333333333     2:  3.
3041 1:  4          1:  0.25               1:  4.
3042     .              .                      .
3044 2 RET 3 RET 4      M-3 &                  M-2 &
3045 @end smallexample
3046 @end group
3048 Notice that the results here are left in floating-point form.
3049 We can convert them back to integers by pressing @kbd{F}, the
3050 ``floor'' function.  This function rounds down to the next lower
3051 integer.  There is also @kbd{R}, which rounds to the nearest
3052 integer.
3054 @group
3055 @smallexample
3056 7:  2.         7:  2          7:  2
3057 6:  2.4        6:  2          6:  2
3058 5:  2.5        5:  2          5:  3
3059 4:  2.6        4:  2          4:  3
3060 3:  -2.        3:  -2         3:  -2
3061 2:  -2.4       2:  -3         2:  -2
3062 1:  -2.6       1:  -3         1:  -3
3063     .              .              .
3065                   M-7 F        U M-7 R
3066 @end smallexample
3067 @end group
3069 Since dividing-and-flooring (i.e., ``integer quotient'') is such a
3070 common operation, Calc provides a special command for that purpose, the
3071 backslash @kbd{\}.  Another common arithmetic operator is @kbd{%}, which
3072 computes the remainder that would arise from a @kbd{\} operation, i.e.,
3073 the ``modulo'' of two numbers.  For example,
3075 @group
3076 @smallexample
3077 2:  1234       1:  12         2:  1234       1:  34
3078 1:  100            .          1:  100            .
3079     .                             .
3081 1234 RET 100       \              U              %
3082 @end smallexample
3083 @end group
3085 These commands actually work for any real numbers, not just integers.
3087 @group
3088 @smallexample
3089 2:  3.1415     1:  3          2:  3.1415     1:  0.1415
3090 1:  1              .          1:  1              .
3091     .                             .
3093 3.1415 RET 1       \              U              %
3094 @end smallexample
3095 @end group
3097 (@bullet{}) @strong{Exercise 1.}  The @kbd{\} command would appear to be a
3098 frill, since you could always do the same thing with @kbd{/ F}.  Think
3099 of a situation where this is not true---@kbd{/ F} would be inadequate.
3100 Now think of a way you could get around the problem if Calc didn't
3101 provide a @kbd{\} command.  @xref{Arithmetic Answer 1, 1}. (@bullet{})
3103 We've already seen the @kbd{Q} (square root) and @kbd{S} (sine)
3104 commands.  Other commands along those lines are @kbd{C} (cosine),
3105 @kbd{T} (tangent), @kbd{E} (@cite{e^x}) and @kbd{L} (natural
3106 logarithm).  These can be modified by the @kbd{I} (inverse) and
3107 @kbd{H} (hyperbolic) prefix keys.
3109 Let's compute the sine and cosine of an angle, and verify the
3110 identity @c{$\sin^2x + \cos^2x = 1$}
3111 @cite{sin(x)^2 + cos(x)^2 = 1}.  We'll
3112 arbitrarily pick @i{-64} degrees as a good value for @cite{x}.  With
3113 the angular mode set to degrees (type @w{@kbd{m d}}), do:
3115 @group
3116 @smallexample
3117 2:  -64        2:  -64        2:  -0.89879   2:  -0.89879   1:  1.
3118 1:  -64        1:  -0.89879   1:  -64        1:  0.43837        .
3119     .              .              .              .
3121  64 n RET RET      S              TAB            C              f h
3122 @end smallexample
3123 @end group
3125 @noindent
3126 (For brevity, we're showing only five digits of the results here.
3127 You can of course do these calculations to any precision you like.)
3129 Remember, @kbd{f h} is the @code{calc-hypot}, or square-root of sum
3130 of squares, command.
3132 Another identity is @c{$\displaystyle\tan x = {\sin x \over \cos x}$}
3133 @cite{tan(x) = sin(x) / cos(x)}.
3134 @group
3135 @smallexample
3137 2:  -0.89879   1:  -2.0503    1:  -64.
3138 1:  0.43837        .              .
3139     .
3141     U              /              I T
3142 @end smallexample
3143 @end group
3145 A physical interpretation of this calculation is that if you move
3146 @cite{0.89879} units downward and @cite{0.43837} units to the right,
3147 your direction of motion is @i{-64} degrees from horizontal.  Suppose
3148 we move in the opposite direction, up and to the left:
3150 @group
3151 @smallexample
3152 2:  -0.89879   2:  0.89879    1:  -2.0503    1:  -64.
3153 1:  0.43837    1:  -0.43837       .              .
3154     .              .
3156     U U            M-2 n          /              I T
3157 @end smallexample
3158 @end group
3160 @noindent
3161 How can the angle be the same?  The answer is that the @kbd{/} operation
3162 loses information about the signs of its inputs.  Because the quotient
3163 is negative, we know exactly one of the inputs was negative, but we
3164 can't tell which one.  There is an @kbd{f T} [@code{arctan2}] function which
3165 computes the inverse tangent of the quotient of a pair of numbers.
3166 Since you feed it the two original numbers, it has enough information
3167 to give you a full 360-degree answer.
3169 @group
3170 @smallexample
3171 2:  0.89879    1:  116.       3:  116.       2:  116.       1:  180.
3172 1:  -0.43837       .          2:  -0.89879   1:  -64.           .
3173     .                         1:  0.43837        .
3174                                   .
3176     U U            f T         M-RET M-2 n       f T            -
3177 @end smallexample
3178 @end group
3180 @noindent
3181 The resulting angles differ by 180 degrees; in other words, they
3182 point in opposite directions, just as we would expect.
3184 The @key{META}-@key{RET} we used in the third step is the
3185 ``last-arguments'' command.  It is sort of like Undo, except that it
3186 restores the arguments of the last command to the stack without removing
3187 the command's result.  It is useful in situations like this one,
3188 where we need to do several operations on the same inputs.  We could
3189 have accomplished the same thing by using @kbd{M-2 @key{RET}} to duplicate
3190 the top two stack elements right after the @kbd{U U}, then a pair of
3191 @kbd{M-@key{TAB}} commands to cycle the 116 up around the duplicates.
3193 A similar identity is supposed to hold for hyperbolic sines and cosines,
3194 except that it is the @emph{difference}
3195 @c{$\cosh^2x - \sinh^2x$}
3196 @cite{cosh(x)^2 - sinh(x)^2} that always equals one.
3197 Let's try to verify this identity.@refill
3199 @group
3200 @smallexample
3201 2:  -64        2:  -64        2:  -64        2:  9.7192e54  2:  9.7192e54
3202 1:  -64        1:  -3.1175e27 1:  9.7192e54  1:  -64        1:  9.7192e54
3203     .              .              .              .              .
3205  64 n RET RET      H C            2 ^            TAB            H S 2 ^
3206 @end smallexample
3207 @end group
3209 @noindent
3210 @cindex Roundoff errors, examples
3211 Something's obviously wrong, because when we subtract these numbers
3212 the answer will clearly be zero!  But if you think about it, if these
3213 numbers @emph{did} differ by one, it would be in the 55th decimal
3214 place.  The difference we seek has been lost entirely to roundoff
3215 error.
3217 We could verify this hypothesis by doing the actual calculation with,
3218 say, 60 decimal places of precision.  This will be slow, but not
3219 enormously so.  Try it if you wish; sure enough, the answer is
3220 0.99999, reasonably close to 1.
3222 Of course, a more reasonable way to verify the identity is to use
3223 a more reasonable value for @cite{x}!
3225 @cindex Common logarithm
3226 Some Calculator commands use the Hyperbolic prefix for other purposes.
3227 The logarithm and exponential functions, for example, work to the base
3228 @cite{e} normally but use base-10 instead if you use the Hyperbolic
3229 prefix.
3231 @group
3232 @smallexample
3233 1:  1000       1:  6.9077     1:  1000       1:  3
3234     .              .              .              .
3236     1000           L              U              H L
3237 @end smallexample
3238 @end group
3240 @noindent
3241 First, we mistakenly compute a natural logarithm.  Then we undo
3242 and compute a common logarithm instead.
3244 The @kbd{B} key computes a general base-@var{b} logarithm for any
3245 value of @var{b}.
3247 @group
3248 @smallexample
3249 2:  1000       1:  3          1:  1000.      2:  1000.      1:  6.9077
3250 1:  10             .              .          1:  2.71828        .
3251     .                                            .
3253  1000 RET 10       B              H E            H P            B
3254 @end smallexample
3255 @end group
3257 @noindent
3258 Here we first use @kbd{B} to compute the base-10 logarithm, then use
3259 the ``hyperbolic'' exponential as a cheap hack to recover the number
3260 1000, then use @kbd{B} again to compute the natural logarithm.  Note
3261 that @kbd{P} with the hyperbolic prefix pushes the constant @cite{e}
3262 onto the stack.
3264 You may have noticed that both times we took the base-10 logarithm
3265 of 1000, we got an exact integer result.  Calc always tries to give
3266 an exact rational result for calculations involving rational numbers
3267 where possible.  But when we used @kbd{H E}, the result was a
3268 floating-point number for no apparent reason.  In fact, if we had
3269 computed @kbd{10 @key{RET} 3 ^} we @emph{would} have gotten an
3270 exact integer 1000.  But the @kbd{H E} command is rigged to generate
3271 a floating-point result all of the time so that @kbd{1000 H E} will
3272 not waste time computing a thousand-digit integer when all you
3273 probably wanted was @samp{1e1000}.
3275 (@bullet{}) @strong{Exercise 2.}  Find a pair of integer inputs to
3276 the @kbd{B} command for which Calc could find an exact rational
3277 result but doesn't.  @xref{Arithmetic Answer 2, 2}. (@bullet{})
3279 The Calculator also has a set of functions relating to combinatorics
3280 and statistics.  You may be familiar with the @dfn{factorial} function,
3281 which computes the product of all the integers up to a given number.
3283 @group
3284 @smallexample
3285 1:  100        1:  93326215443...    1:  100.       1:  9.3326e157
3286     .              .                     .              .
3288     100            !                     U c f          !
3289 @end smallexample
3290 @end group
3292 @noindent
3293 Recall, the @kbd{c f} command converts the integer or fraction at the
3294 top of the stack to floating-point format.  If you take the factorial
3295 of a floating-point number, you get a floating-point result
3296 accurate to the current precision.  But if you give @kbd{!} an
3297 exact integer, you get an exact integer result (158 digits long
3298 in this case).
3300 If you take the factorial of a non-integer, Calc uses a generalized
3301 factorial function defined in terms of Euler's Gamma function
3302 @c{$\Gamma(n)$}
3303 @cite{gamma(n)}
3304 (which is itself available as the @kbd{f g} command).
3306 @group
3307 @smallexample
3308 3:  4.         3:  24.               1:  5.5        1:  52.342777847
3309 2:  4.5        2:  52.3427777847         .              .
3310 1:  5.         1:  120.
3311     .              .
3313                    M-3 !              M-0 DEL 5.5       f g
3314 @end smallexample
3315 @end group
3317 @noindent
3318 Here we verify the identity @c{$n! = \Gamma(n+1)$}
3319 @cite{@var{n}!@: = gamma(@var{n}+1)}.
3321 The binomial coefficient @var{n}-choose-@var{m}@c{ or $\displaystyle {n \choose m}$}
3322 @asis{} is defined by
3323 @c{$\displaystyle {n! \over m! \, (n-m)!}$}
3324 @cite{n!@: / m!@: (n-m)!} for all reals @cite{n} and
3325 @cite{m}.  The intermediate results in this formula can become quite
3326 large even if the final result is small; the @kbd{k c} command computes
3327 a binomial coefficient in a way that avoids large intermediate
3328 values.
3330 The @kbd{k} prefix key defines several common functions out of
3331 combinatorics and number theory.  Here we compute the binomial
3332 coefficient 30-choose-20, then determine its prime factorization.
3334 @group
3335 @smallexample
3336 2:  30         1:  30045015   1:  [3, 3, 5, 7, 11, 13, 23, 29]
3337 1:  20             .              .
3338     .
3340  30 RET 20         k c            k f
3341 @end smallexample
3342 @end group
3344 @noindent
3345 You can verify these prime factors by using @kbd{v u} to ``unpack''
3346 this vector into 8 separate stack entries, then @kbd{M-8 *} to
3347 multiply them back together.  The result is the original number,
3348 30045015.
3350 @cindex Hash tables
3351 Suppose a program you are writing needs a hash table with at least
3352 10000 entries.  It's best to use a prime number as the actual size
3353 of a hash table.  Calc can compute the next prime number after 10000:
3355 @group
3356 @smallexample
3357 1:  10000      1:  10007      1:  9973
3358     .              .              .
3360     10000          k n            I k n
3361 @end smallexample
3362 @end group
3364 @noindent
3365 Just for kicks we've also computed the next prime @emph{less} than
3366 10000.
3368 @c [fix-ref Financial Functions]
3369 @xref{Financial Functions}, for a description of the Calculator
3370 commands that deal with business and financial calculations (functions
3371 like @code{pv}, @code{rate}, and @code{sln}).
3373 @c [fix-ref Binary Number Functions]
3374 @xref{Binary Functions}, to read about the commands for operating
3375 on binary numbers (like @code{and}, @code{xor}, and @code{lsh}).
3377 @node Vector/Matrix Tutorial, Types Tutorial, Arithmetic Tutorial, Tutorial
3378 @section Vector/Matrix Tutorial
3380 @noindent
3381 A @dfn{vector} is a list of numbers or other Calc data objects.
3382 Calc provides a large set of commands that operate on vectors.  Some
3383 are familiar operations from vector analysis.  Others simply treat
3384 a vector as a list of objects.
3386 @menu
3387 * Vector Analysis Tutorial::
3388 * Matrix Tutorial::
3389 * List Tutorial::
3390 @end menu
3392 @node Vector Analysis Tutorial, Matrix Tutorial, Vector/Matrix Tutorial, Vector/Matrix Tutorial
3393 @subsection Vector Analysis
3395 @noindent
3396 If you add two vectors, the result is a vector of the sums of the
3397 elements, taken pairwise.
3399 @group
3400 @smallexample
3401 1:  [1, 2, 3]     2:  [1, 2, 3]     1:  [8, 8, 3]
3402     .             1:  [7, 6, 0]         .
3403                       .
3405     [1,2,3]  s 1      [7 6 0]  s 2      +
3406 @end smallexample
3407 @end group
3409 @noindent
3410 Note that we can separate the vector elements with either commas or
3411 spaces.  This is true whether we are using incomplete vectors or
3412 algebraic entry.  The @kbd{s 1} and @kbd{s 2} commands save these
3413 vectors so we can easily reuse them later.
3415 If you multiply two vectors, the result is the sum of the products
3416 of the elements taken pairwise.  This is called the @dfn{dot product}
3417 of the vectors.
3419 @group
3420 @smallexample
3421 2:  [1, 2, 3]     1:  19
3422 1:  [7, 6, 0]         .
3423     .
3425     r 1 r 2           *
3426 @end smallexample
3427 @end group
3429 @cindex Dot product
3430 The dot product of two vectors is equal to the product of their
3431 lengths times the cosine of the angle between them.  (Here the vector
3432 is interpreted as a line from the origin @cite{(0,0,0)} to the
3433 specified point in three-dimensional space.)  The @kbd{A}
3434 (absolute value) command can be used to compute the length of a
3435 vector.
3437 @group
3438 @smallexample
3439 3:  19            3:  19          1:  0.550782    1:  56.579
3440 2:  [1, 2, 3]     2:  3.741657        .               .
3441 1:  [7, 6, 0]     1:  9.219544
3442     .                 .
3444     M-RET             M-2 A          * /             I C
3445 @end smallexample
3446 @end group
3448 @noindent
3449 First we recall the arguments to the dot product command, then
3450 we compute the absolute values of the top two stack entries to
3451 obtain the lengths of the vectors, then we divide the dot product
3452 by the product of the lengths to get the cosine of the angle.
3453 The inverse cosine finds that the angle between the vectors
3454 is about 56 degrees.
3456 @cindex Cross product
3457 @cindex Perpendicular vectors
3458 The @dfn{cross product} of two vectors is a vector whose length
3459 is the product of the lengths of the inputs times the sine of the
3460 angle between them, and whose direction is perpendicular to both
3461 input vectors.  Unlike the dot product, the cross product is
3462 defined only for three-dimensional vectors.  Let's double-check
3463 our computation of the angle using the cross product.
3465 @group
3466 @smallexample
3467 2:  [1, 2, 3]  3:  [-18, 21, -8]  1:  [-0.52, 0.61, -0.23]  1:  56.579
3468 1:  [7, 6, 0]  2:  [1, 2, 3]          .                         .
3469     .          1:  [7, 6, 0]
3470                    .
3472     r 1 r 2        V C  s 3  M-RET    M-2 A * /                 A I S
3473 @end smallexample
3474 @end group
3476 @noindent
3477 First we recall the original vectors and compute their cross product,
3478 which we also store for later reference.  Now we divide the vector
3479 by the product of the lengths of the original vectors.  The length of
3480 this vector should be the sine of the angle; sure enough, it is!
3482 @c [fix-ref General Mode Commands]
3483 Vector-related commands generally begin with the @kbd{v} prefix key.
3484 Some are uppercase letters and some are lowercase.  To make it easier
3485 to type these commands, the shift-@kbd{V} prefix key acts the same as
3486 the @kbd{v} key.  (@xref{General Mode Commands}, for a way to make all
3487 prefix keys have this property.)
3489 If we take the dot product of two perpendicular vectors we expect
3490 to get zero, since the cosine of 90 degrees is zero.  Let's check
3491 that the cross product is indeed perpendicular to both inputs:
3493 @group
3494 @smallexample
3495 2:  [1, 2, 3]      1:  0          2:  [7, 6, 0]      1:  0
3496 1:  [-18, 21, -8]      .          1:  [-18, 21, -8]      .
3497     .                                 .
3499     r 1 r 3            *          DEL r 2 r 3            *
3500 @end smallexample
3501 @end group
3503 @cindex Normalizing a vector
3504 @cindex Unit vectors
3505 (@bullet{}) @strong{Exercise 1.}  Given a vector on the top of the
3506 stack, what keystrokes would you use to @dfn{normalize} the
3507 vector, i.e., to reduce its length to one without changing its
3508 direction?  @xref{Vector Answer 1, 1}. (@bullet{})
3510 (@bullet{}) @strong{Exercise 2.}  Suppose a certain particle can be
3511 at any of several positions along a ruler.  You have a list of
3512 those positions in the form of a vector, and another list of the
3513 probabilities for the particle to be at the corresponding positions.
3514 Find the average position of the particle.
3515 @xref{Vector Answer 2, 2}. (@bullet{})
3517 @node Matrix Tutorial, List Tutorial, Vector Analysis Tutorial, Vector/Matrix Tutorial
3518 @subsection Matrices
3520 @noindent
3521 A @dfn{matrix} is just a vector of vectors, all the same length.
3522 This means you can enter a matrix using nested brackets.  You can
3523 also use the semicolon character to enter a matrix.  We'll show
3524 both methods here:
3526 @group
3527 @smallexample
3528 1:  [ [ 1, 2, 3 ]             1:  [ [ 1, 2, 3 ]
3529       [ 4, 5, 6 ] ]                 [ 4, 5, 6 ] ]
3530     .                             .
3532   [[1 2 3] [4 5 6]]             ' [1 2 3; 4 5 6] RET
3533 @end smallexample
3534 @end group
3536 @noindent
3537 We'll be using this matrix again, so type @kbd{s 4} to save it now.
3539 Note that semicolons work with incomplete vectors, but they work
3540 better in algebraic entry.  That's why we use the apostrophe in
3541 the second example.
3543 When two matrices are multiplied, the lefthand matrix must have
3544 the same number of columns as the righthand matrix has rows.
3545 Row @cite{i}, column @cite{j} of the result is effectively the
3546 dot product of row @cite{i} of the left matrix by column @cite{j}
3547 of the right matrix.
3549 If we try to duplicate this matrix and multiply it by itself,
3550 the dimensions are wrong and the multiplication cannot take place:
3552 @group
3553 @smallexample
3554 1:  [ [ 1, 2, 3 ]   * [ [ 1, 2, 3 ]
3555       [ 4, 5, 6 ] ]     [ 4, 5, 6 ] ]
3556     .
3558     RET *
3559 @end smallexample
3560 @end group
3562 @noindent
3563 Though rather hard to read, this is a formula which shows the product
3564 of two matrices.  The @samp{*} function, having invalid arguments, has
3565 been left in symbolic form.
3567 We can multiply the matrices if we @dfn{transpose} one of them first.
3569 @group
3570 @smallexample
3571 2:  [ [ 1, 2, 3 ]       1:  [ [ 14, 32 ]      1:  [ [ 17, 22, 27 ]
3572       [ 4, 5, 6 ] ]           [ 32, 77 ] ]          [ 22, 29, 36 ]
3573 1:  [ [ 1, 4 ]              .                       [ 27, 36, 45 ] ]
3574       [ 2, 5 ]                                    .
3575       [ 3, 6 ] ]
3576     .
3578     U v t                   *                     U TAB *
3579 @end smallexample
3580 @end group
3582 Matrix multiplication is not commutative; indeed, switching the
3583 order of the operands can even change the dimensions of the result
3584 matrix, as happened here!
3586 If you multiply a plain vector by a matrix, it is treated as a
3587 single row or column depending on which side of the matrix it is
3588 on.  The result is a plain vector which should also be interpreted
3589 as a row or column as appropriate.
3591 @group
3592 @smallexample
3593 2:  [ [ 1, 2, 3 ]      1:  [14, 32]
3594       [ 4, 5, 6 ] ]        .
3595 1:  [1, 2, 3]
3596     .
3598     r 4 r 1                *
3599 @end smallexample
3600 @end group
3602 Multiplying in the other order wouldn't work because the number of
3603 rows in the matrix is different from the number of elements in the
3604 vector.
3606 (@bullet{}) @strong{Exercise 1.}  Use @samp{*} to sum along the rows
3607 of the above @c{$2\times3$}
3608 @asis{2x3} matrix to get @cite{[6, 15]}.  Now use @samp{*} to
3609 sum along the columns to get @cite{[5, 7, 9]}.
3610 @xref{Matrix Answer 1, 1}. (@bullet{})
3612 @cindex Identity matrix
3613 An @dfn{identity matrix} is a square matrix with ones along the
3614 diagonal and zeros elsewhere.  It has the property that multiplication
3615 by an identity matrix, on the left or on the right, always produces
3616 the original matrix.
3618 @group
3619 @smallexample
3620 1:  [ [ 1, 2, 3 ]      2:  [ [ 1, 2, 3 ]      1:  [ [ 1, 2, 3 ]
3621       [ 4, 5, 6 ] ]          [ 4, 5, 6 ] ]          [ 4, 5, 6 ] ]
3622     .                  1:  [ [ 1, 0, 0 ]          .
3623                              [ 0, 1, 0 ]
3624                              [ 0, 0, 1 ] ]
3625                            .
3627     r 4                    v i 3 RET              *
3628 @end smallexample
3629 @end group
3631 If a matrix is square, it is often possible to find its @dfn{inverse},
3632 that is, a matrix which, when multiplied by the original matrix, yields
3633 an identity matrix.  The @kbd{&} (reciprocal) key also computes the
3634 inverse of a matrix.
3636 @group
3637 @smallexample
3638 1:  [ [ 1, 2, 3 ]      1:  [ [   -2.4,     1.2,   -0.2 ]
3639       [ 4, 5, 6 ]            [    2.8,    -1.4,    0.4 ]
3640       [ 7, 6, 0 ] ]          [ -0.73333, 0.53333, -0.2 ] ]
3641     .                      .
3643     r 4 r 2 |  s 5         &
3644 @end smallexample
3645 @end group
3647 @noindent
3648 The vertical bar @kbd{|} @dfn{concatenates} numbers, vectors, and
3649 matrices together.  Here we have used it to add a new row onto
3650 our matrix to make it square.
3652 We can multiply these two matrices in either order to get an identity.
3654 @group
3655 @smallexample
3656 1:  [ [ 1., 0., 0. ]      1:  [ [ 1., 0., 0. ]
3657       [ 0., 1., 0. ]            [ 0., 1., 0. ]
3658       [ 0., 0., 1. ] ]          [ 0., 0., 1. ] ]
3659     .                         .
3661     M-RET  *                  U TAB *
3662 @end smallexample
3663 @end group
3665 @cindex Systems of linear equations
3666 @cindex Linear equations, systems of
3667 Matrix inverses are related to systems of linear equations in algebra.
3668 Suppose we had the following set of equations:
3670 @ifinfo
3671 @group
3672 @example
3673     a + 2b + 3c = 6
3674    4a + 5b + 6c = 2
3675    7a + 6b      = 3
3676 @end example
3677 @end group
3678 @end ifinfo
3679 @tex
3680 \turnoffactive
3681 \beforedisplayh
3682 $$ \openup1\jot \tabskip=0pt plus1fil
3683 \halign to\displaywidth{\tabskip=0pt
3684    $\hfil#$&$\hfil{}#{}$&
3685    $\hfil#$&$\hfil{}#{}$&
3686    $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3687   a&+&2b&+&3c&=6 \cr
3688  4a&+&5b&+&6c&=2 \cr
3689  7a&+&6b& &  &=3 \cr}
3691 \afterdisplayh
3692 @end tex
3694 @noindent
3695 This can be cast into the matrix equation,
3697 @ifinfo
3698 @group
3699 @example
3700    [ [ 1, 2, 3 ]     [ [ a ]     [ [ 6 ]
3701      [ 4, 5, 6 ]   *   [ b ]   =   [ 2 ]
3702      [ 7, 6, 0 ] ]     [ c ] ]     [ 3 ] ]
3703 @end example
3704 @end group
3705 @end ifinfo
3706 @tex
3707 \turnoffactive
3708 \beforedisplay
3709 $$ \pmatrix{ 1 & 2 & 3 \cr 4 & 5 & 6 \cr 7 & 6 & 0 }
3710    \times
3711    \pmatrix{ a \cr b \cr c } = \pmatrix{ 6 \cr 2 \cr 3 }
3713 \afterdisplay
3714 @end tex
3716 We can solve this system of equations by multiplying both sides by the
3717 inverse of the matrix.  Calc can do this all in one step:
3719 @group
3720 @smallexample
3721 2:  [6, 2, 3]          1:  [-12.6, 15.2, -3.93333]
3722 1:  [ [ 1, 2, 3 ]          .
3723       [ 4, 5, 6 ]
3724       [ 7, 6, 0 ] ]
3725     .
3727     [6,2,3] r 5            /
3728 @end smallexample
3729 @end group
3731 @noindent
3732 The result is the @cite{[a, b, c]} vector that solves the equations.
3733 (Dividing by a square matrix is equivalent to multiplying by its
3734 inverse.)
3736 Let's verify this solution:
3738 @group
3739 @smallexample
3740 2:  [ [ 1, 2, 3 ]                1:  [6., 2., 3.]
3741       [ 4, 5, 6 ]                    .
3742       [ 7, 6, 0 ] ]
3743 1:  [-12.6, 15.2, -3.93333]
3744     .
3746     r 5  TAB                         *
3747 @end smallexample
3748 @end group
3750 @noindent
3751 Note that we had to be careful about the order in which we multiplied
3752 the matrix and vector.  If we multiplied in the other order, Calc would
3753 assume the vector was a row vector in order to make the dimensions
3754 come out right, and the answer would be incorrect.  If you
3755 don't feel safe letting Calc take either interpretation of your
3756 vectors, use explicit @c{$N\times1$}
3757 @asis{Nx1} or @c{$1\times N$}
3758 @asis{1xN} matrices instead.
3759 In this case, you would enter the original column vector as
3760 @samp{[[6], [2], [3]]} or @samp{[6; 2; 3]}.
3762 (@bullet{}) @strong{Exercise 2.}  Algebraic entry allows you to make
3763 vectors and matrices that include variables.  Solve the following
3764 system of equations to get expressions for @cite{x} and @cite{y}
3765 in terms of @cite{a} and @cite{b}.
3767 @ifinfo
3768 @group
3769 @example
3770    x + a y = 6
3771    x + b y = 10
3772 @end example
3773 @end group
3774 @end ifinfo
3775 @tex
3776 \turnoffactive
3777 \beforedisplay
3778 $$ \eqalign{ x &+ a y = 6 \cr
3779              x &+ b y = 10}
3781 \afterdisplay
3782 @end tex
3784 @noindent
3785 @xref{Matrix Answer 2, 2}. (@bullet{})
3787 @cindex Least-squares for over-determined systems
3788 @cindex Over-determined systems of equations
3789 (@bullet{}) @strong{Exercise 3.}  A system of equations is ``over-determined''
3790 if it has more equations than variables.  It is often the case that
3791 there are no values for the variables that will satisfy all the
3792 equations at once, but it is still useful to find a set of values
3793 which ``nearly'' satisfy all the equations.  In terms of matrix equations,
3794 you can't solve @cite{A X = B} directly because the matrix @cite{A}
3795 is not square for an over-determined system.  Matrix inversion works
3796 only for square matrices.  One common trick is to multiply both sides
3797 on the left by the transpose of @cite{A}:
3798 @ifinfo
3799 @samp{trn(A)*A*X = trn(A)*B}.
3800 @end ifinfo
3801 @tex
3802 \turnoffactive
3803 $A^T A \, X = A^T B$, where $A^T$ is the transpose \samp{trn(A)}.
3804 @end tex
3805 Now @c{$A^T A$}
3806 @cite{trn(A)*A} is a square matrix so a solution is possible.  It
3807 turns out that the @cite{X} vector you compute in this way will be a
3808 ``least-squares'' solution, which can be regarded as the ``closest''
3809 solution to the set of equations.  Use Calc to solve the following
3810 over-determined system:@refill
3812 @ifinfo
3813 @group
3814 @example
3815     a + 2b + 3c = 6
3816    4a + 5b + 6c = 2
3817    7a + 6b      = 3
3818    2a + 4b + 6c = 11
3819 @end example
3820 @end group
3821 @end ifinfo
3822 @tex
3823 \turnoffactive
3824 \beforedisplayh
3825 $$ \openup1\jot \tabskip=0pt plus1fil
3826 \halign to\displaywidth{\tabskip=0pt
3827    $\hfil#$&$\hfil{}#{}$&
3828    $\hfil#$&$\hfil{}#{}$&
3829    $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
3830   a&+&2b&+&3c&=6 \cr
3831  4a&+&5b&+&6c&=2 \cr
3832  7a&+&6b& &  &=3 \cr
3833  2a&+&4b&+&6c&=11 \cr}
3835 \afterdisplayh
3836 @end tex
3838 @noindent
3839 @xref{Matrix Answer 3, 3}. (@bullet{})
3841 @node List Tutorial, , Matrix Tutorial, Vector/Matrix Tutorial
3842 @subsection Vectors as Lists
3844 @noindent
3845 @cindex Lists
3846 Although Calc has a number of features for manipulating vectors and
3847 matrices as mathematical objects, you can also treat vectors as
3848 simple lists of values.  For example, we saw that the @kbd{k f}
3849 command returns a vector which is a list of the prime factors of a
3850 number.
3852 You can pack and unpack stack entries into vectors:
3854 @group
3855 @smallexample
3856 3:  10         1:  [10, 20, 30]     3:  10
3857 2:  20             .                2:  20
3858 1:  30                              1:  30
3859     .                                   .
3861                    M-3 v p              v u
3862 @end smallexample
3863 @end group
3865 You can also build vectors out of consecutive integers, or out
3866 of many copies of a given value:
3868 @group
3869 @smallexample
3870 1:  [1, 2, 3, 4]    2:  [1, 2, 3, 4]    2:  [1, 2, 3, 4]
3871     .               1:  17              1:  [17, 17, 17, 17]
3872                         .                   .
3874     v x 4 RET           17                  v b 4 RET
3875 @end smallexample
3876 @end group
3878 You can apply an operator to every element of a vector using the
3879 @dfn{map} command.
3881 @group
3882 @smallexample
3883 1:  [17, 34, 51, 68]   1:  [289, 1156, 2601, 4624]  1:  [17, 34, 51, 68]
3884     .                      .                            .
3886     V M *                  2 V M ^                      V M Q
3887 @end smallexample
3888 @end group
3890 @noindent
3891 In the first step, we multiply the vector of integers by the vector
3892 of 17's elementwise.  In the second step, we raise each element to
3893 the power two.  (The general rule is that both operands must be
3894 vectors of the same length, or else one must be a vector and the
3895 other a plain number.)  In the final step, we take the square root
3896 of each element.
3898 (@bullet{}) @strong{Exercise 1.}  Compute a vector of powers of two
3899 from @c{$2^{-4}$}
3900 @cite{2^-4} to @cite{2^4}.  @xref{List Answer 1, 1}. (@bullet{})
3902 You can also @dfn{reduce} a binary operator across a vector.
3903 For example, reducing @samp{*} computes the product of all the
3904 elements in the vector:
3906 @group
3907 @smallexample
3908 1:  123123     1:  [3, 7, 11, 13, 41]      1:  123123
3909     .              .                           .
3911     123123         k f                         V R *
3912 @end smallexample
3913 @end group
3915 @noindent
3916 In this example, we decompose 123123 into its prime factors, then
3917 multiply those factors together again to yield the original number.
3919 We could compute a dot product ``by hand'' using mapping and
3920 reduction:
3922 @group
3923 @smallexample
3924 2:  [1, 2, 3]     1:  [7, 12, 0]     1:  19
3925 1:  [7, 6, 0]         .                  .
3926     .
3928     r 1 r 2           V M *              V R +
3929 @end smallexample
3930 @end group
3932 @noindent
3933 Recalling two vectors from the previous section, we compute the
3934 sum of pairwise products of the elements to get the same answer
3935 for the dot product as before.
3937 A slight variant of vector reduction is the @dfn{accumulate} operation,
3938 @kbd{V U}.  This produces a vector of the intermediate results from
3939 a corresponding reduction.  Here we compute a table of factorials:
3941 @group
3942 @smallexample
3943 1:  [1, 2, 3, 4, 5, 6]    1:  [1, 2, 6, 24, 120, 720]
3944     .                         .
3946     v x 6 RET                 V U *
3947 @end smallexample
3948 @end group
3950 Calc allows vectors to grow as large as you like, although it gets
3951 rather slow if vectors have more than about a hundred elements.
3952 Actually, most of the time is spent formatting these large vectors
3953 for display, not calculating on them.  Try the following experiment
3954 (if your computer is very fast you may need to substitute a larger
3955 vector size).
3957 @group
3958 @smallexample
3959 1:  [1, 2, 3, 4, ...      1:  [2, 3, 4, 5, ...
3960     .                         .
3962     v x 500 RET               1 V M +
3963 @end smallexample
3964 @end group
3966 Now press @kbd{v .} (the letter @kbd{v}, then a period) and try the
3967 experiment again.  In @kbd{v .} mode, long vectors are displayed
3968 ``abbreviated'' like this:
3970 @group
3971 @smallexample
3972 1:  [1, 2, 3, ..., 500]   1:  [2, 3, 4, ..., 501]
3973     .                         .
3975     v x 500 RET               1 V M +
3976 @end smallexample
3977 @end group
3979 @noindent
3980 (where now the @samp{...} is actually part of the Calc display).
3981 You will find both operations are now much faster.  But notice that
3982 even in @w{@kbd{v .}} mode, the full vectors are still shown in the Trail.
3983 Type @w{@kbd{t .}} to cause the trail to abbreviate as well, and try the
3984 experiment one more time.  Operations on long vectors are now quite
3985 fast!  (But of course if you use @kbd{t .} you will lose the ability
3986 to get old vectors back using the @kbd{t y} command.)
3988 An easy way to view a full vector when @kbd{v .} mode is active is
3989 to press @kbd{`} (back-quote) to edit the vector; editing always works
3990 with the full, unabbreviated value.
3992 @cindex Least-squares for fitting a straight line
3993 @cindex Fitting data to a line
3994 @cindex Line, fitting data to
3995 @cindex Data, extracting from buffers
3996 @cindex Columns of data, extracting
3997 As a larger example, let's try to fit a straight line to some data,
3998 using the method of least squares.  (Calc has a built-in command for
3999 least-squares curve fitting, but we'll do it by hand here just to
4000 practice working with vectors.)  Suppose we have the following list
4001 of values in a file we have loaded into Emacs:
4003 @smallexample
4004   x        y
4005  ---      ---
4006  1.34    0.234
4007  1.41    0.298
4008  1.49    0.402
4009  1.56    0.412
4010  1.64    0.466
4011  1.73    0.473
4012  1.82    0.601
4013  1.91    0.519
4014  2.01    0.603
4015  2.11    0.637
4016  2.22    0.645
4017  2.33    0.705
4018  2.45    0.917
4019  2.58    1.009
4020  2.71    0.971
4021  2.85    1.062
4022  3.00    1.148
4023  3.15    1.157
4024  3.32    1.354
4025 @end smallexample
4027 @noindent
4028 If you are reading this tutorial in printed form, you will find it
4029 easiest to press @kbd{M-# i} to enter the on-line Info version of
4030 the manual and find this table there.  (Press @kbd{g}, then type
4031 @kbd{List Tutorial}, to jump straight to this section.)
4033 Position the cursor at the upper-left corner of this table, just
4034 to the left of the @cite{1.34}.  Press @kbd{C-@@} to set the mark.
4035 (On your system this may be @kbd{C-2}, @kbd{C-SPC}, or @kbd{NUL}.)
4036 Now position the cursor to the lower-right, just after the @cite{1.354}.
4037 You have now defined this region as an Emacs ``rectangle.''  Still
4038 in the Info buffer, type @kbd{M-# r}.  This command
4039 (@code{calc-grab-rectangle}) will pop you back into the Calculator, with
4040 the contents of the rectangle you specified in the form of a matrix.@refill
4042 @group
4043 @smallexample
4044 1:  [ [ 1.34, 0.234 ]
4045       [ 1.41, 0.298 ]
4046       @dots{}
4047 @end smallexample
4048 @end group
4050 @noindent
4051 (You may wish to use @kbd{v .} mode to abbreviate the display of this
4052 large matrix.)
4054 We want to treat this as a pair of lists.  The first step is to
4055 transpose this matrix into a pair of rows.  Remember, a matrix is
4056 just a vector of vectors.  So we can unpack the matrix into a pair
4057 of row vectors on the stack.
4059 @group
4060 @smallexample
4061 1:  [ [ 1.34,  1.41,  1.49,  ... ]     2:  [1.34, 1.41, 1.49, ... ]
4062       [ 0.234, 0.298, 0.402, ... ] ]   1:  [0.234, 0.298, 0.402, ... ]
4063     .                                      .
4065     v t                                    v u
4066 @end smallexample
4067 @end group
4069 @noindent
4070 Let's store these in quick variables 1 and 2, respectively.
4072 @group
4073 @smallexample
4074 1:  [1.34, 1.41, 1.49, ... ]        .
4075     .
4077     t 2                             t 1
4078 @end smallexample
4079 @end group
4081 @noindent
4082 (Recall that @kbd{t 2} is a variant of @kbd{s 2} that removes the
4083 stored value from the stack.)
4085 In a least squares fit, the slope @cite{m} is given by the formula
4087 @ifinfo
4088 @example
4089 m = (N sum(x y) - sum(x) sum(y)) / (N sum(x^2) - sum(x)^2)
4090 @end example
4091 @end ifinfo
4092 @tex
4093 \turnoffactive
4094 \beforedisplay
4095 $$ m = {N \sum x y - \sum x \sum y  \over
4096         N \sum x^2 - \left( \sum x \right)^2} $$
4097 \afterdisplay
4098 @end tex
4100 @noindent
4101 where @c{$\sum x$}
4102 @cite{sum(x)} represents the sum of all the values of @cite{x}.
4103 While there is an actual @code{sum} function in Calc, it's easier to
4104 sum a vector using a simple reduction.  First, let's compute the four
4105 different sums that this formula uses.
4107 @group
4108 @smallexample
4109 1:  41.63                 1:  98.0003
4110     .                         .
4112  r 1 V R +   t 3           r 1 2 V M ^ V R +   t 4
4114 @end smallexample
4115 @end group
4116 @noindent
4117 @group
4118 @smallexample
4119 1:  13.613                1:  33.36554
4120     .                         .
4122  r 2 V R +   t 5           r 1 r 2 V M * V R +   t 6
4123 @end smallexample
4124 @end group
4126 @ifinfo
4127 @noindent
4128 These are @samp{sum(x)}, @samp{sum(x^2)}, @samp{sum(y)}, and @samp{sum(x y)},
4129 respectively.  (We could have used @kbd{*} to compute @samp{sum(x^2)} and
4130 @samp{sum(x y)}.)
4131 @end ifinfo
4132 @tex
4133 \turnoffactive
4134 These are $\sum x$, $\sum x^2$, $\sum y$, and $\sum x y$,
4135 respectively.  (We could have used \kbd{*} to compute $\sum x^2$ and
4136 $\sum x y$.)
4137 @end tex
4139 Finally, we also need @cite{N}, the number of data points.  This is just
4140 the length of either of our lists.
4142 @group
4143 @smallexample
4144 1:  19
4145     .
4147  r 1 v l   t 7
4148 @end smallexample
4149 @end group
4151 @noindent
4152 (That's @kbd{v} followed by a lower-case @kbd{l}.)
4154 Now we grind through the formula:
4156 @group
4157 @smallexample
4158 1:  633.94526  2:  633.94526  1:  67.23607
4159     .          1:  566.70919      .
4160                    .
4162  r 7 r 6 *      r 3 r 5 *         -
4164 @end smallexample
4165 @end group
4166 @noindent
4167 @group
4168 @smallexample
4169 2:  67.23607   3:  67.23607   2:  67.23607   1:  0.52141679
4170 1:  1862.0057  2:  1862.0057  1:  128.9488       .
4171     .          1:  1733.0569      .
4172                    .
4174  r 7 r 4 *      r 3 2 ^           -              /   t 8
4175 @end smallexample
4176 @end group
4178 That gives us the slope @cite{m}.  The y-intercept @cite{b} can now
4179 be found with the simple formula,
4181 @ifinfo
4182 @example
4183 b = (sum(y) - m sum(x)) / N
4184 @end example
4185 @end ifinfo
4186 @tex
4187 \turnoffactive
4188 \beforedisplay
4189 $$ b = {\sum y - m \sum x \over N} $$
4190 \afterdisplay
4191 \vskip10pt
4192 @end tex
4194 @group
4195 @smallexample
4196 1:  13.613     2:  13.613     1:  -8.09358   1:  -0.425978
4197     .          1:  21.70658       .              .
4198                    .
4200    r 5            r 8 r 3 *       -              r 7 /   t 9
4201 @end smallexample
4202 @end group
4204 Let's ``plot'' this straight line approximation, @c{$y \approx m x + b$}
4205 @cite{m x + b}, and compare it with the original data.@refill
4207 @group
4208 @smallexample
4209 1:  [0.699, 0.735, ... ]    1:  [0.273, 0.309, ... ]
4210     .                           .
4212     r 1 r 8 *                   r 9 +    s 0
4213 @end smallexample
4214 @end group
4216 @noindent
4217 Notice that multiplying a vector by a constant, and adding a constant
4218 to a vector, can be done without mapping commands since these are
4219 common operations from vector algebra.  As far as Calc is concerned,
4220 we've just been doing geometry in 19-dimensional space!
4222 We can subtract this vector from our original @cite{y} vector to get
4223 a feel for the error of our fit.  Let's find the maximum error:
4225 @group
4226 @smallexample
4227 1:  [0.0387, 0.0112, ... ]   1:  [0.0387, 0.0112, ... ]   1:  0.0897
4228     .                            .                            .
4230     r 2 -                        V M A                        V R X
4231 @end smallexample
4232 @end group
4234 @noindent
4235 First we compute a vector of differences, then we take the absolute
4236 values of these differences, then we reduce the @code{max} function
4237 across the vector.  (The @code{max} function is on the two-key sequence
4238 @kbd{f x}; because it is so common to use @code{max} in a vector
4239 operation, the letters @kbd{X} and @kbd{N} are also accepted for
4240 @code{max} and @code{min} in this context.  In general, you answer
4241 the @kbd{V M} or @kbd{V R} prompt with the actual key sequence that
4242 invokes the function you want.  You could have typed @kbd{V R f x} or
4243 even @kbd{V R x max @key{RET}} if you had preferred.)
4245 If your system has the GNUPLOT program, you can see graphs of your
4246 data and your straight line to see how well they match.  (If you have
4247 GNUPLOT 3.0, the following instructions will work regardless of the
4248 kind of display you have.  Some GNUPLOT 2.0, non-X-windows systems
4249 may require additional steps to view the graphs.)
4251 Let's start by plotting the original data.  Recall the ``@i{x}'' and ``@i{y}''
4252 vectors onto the stack and press @kbd{g f}.  This ``fast'' graphing
4253 command does everything you need to do for simple, straightforward
4254 plotting of data.
4256 @group
4257 @smallexample
4258 2:  [1.34, 1.41, 1.49, ... ]
4259 1:  [0.234, 0.298, 0.402, ... ]
4260     .
4262     r 1 r 2    g f
4263 @end smallexample
4264 @end group
4266 If all goes well, you will shortly get a new window containing a graph
4267 of the data.  (If not, contact your GNUPLOT or Calc installer to find
4268 out what went wrong.)  In the X window system, this will be a separate
4269 graphics window.  For other kinds of displays, the default is to
4270 display the graph in Emacs itself using rough character graphics.
4271 Press @kbd{q} when you are done viewing the character graphics.
4273 Next, let's add the line we got from our least-squares fit:
4275 @group
4276 @smallexample
4277 2:  [1.34, 1.41, 1.49, ... ]
4278 1:  [0.273, 0.309, 0.351, ... ]
4279     .
4281     DEL r 0    g a  g p
4282 @end smallexample
4283 @end group
4285 It's not very useful to get symbols to mark the data points on this
4286 second curve; you can type @kbd{g S g p} to remove them.  Type @kbd{g q}
4287 when you are done to remove the X graphics window and terminate GNUPLOT.
4289 (@bullet{}) @strong{Exercise 2.}  An earlier exercise showed how to do
4290 least squares fitting to a general system of equations.  Our 19 data
4291 points are really 19 equations of the form @cite{y_i = m x_i + b} for
4292 different pairs of @cite{(x_i,y_i)}.  Use the matrix-transpose method
4293 to solve for @cite{m} and @cite{b}, duplicating the above result.
4294 @xref{List Answer 2, 2}. (@bullet{})
4296 @cindex Geometric mean
4297 (@bullet{}) @strong{Exercise 3.}  If the input data do not form a
4298 rectangle, you can use @w{@kbd{M-# g}} (@code{calc-grab-region})
4299 to grab the data the way Emacs normally works with regions---it reads
4300 left-to-right, top-to-bottom, treating line breaks the same as spaces.
4301 Use this command to find the geometric mean of the following numbers.
4302 (The geometric mean is the @var{n}th root of the product of @var{n} numbers.)
4304 @example
4305 2.3  6  22  15.1  7
4306   15  14  7.5
4307   2.5
4308 @end example
4310 @noindent
4311 The @kbd{M-# g} command accepts numbers separated by spaces or commas,
4312 with or without surrounding vector brackets.
4313 @xref{List Answer 3, 3}. (@bullet{})
4315 @ifinfo
4316 As another example, a theorem about binomial coefficients tells
4317 us that the alternating sum of binomial coefficients
4318 @var{n}-choose-0 minus @var{n}-choose-1 plus @var{n}-choose-2, and so
4319 on up to @var{n}-choose-@var{n},
4320 always comes out to zero.  Let's verify this
4321 for @cite{n=6}.@refill
4322 @end ifinfo
4323 @tex
4324 As another example, a theorem about binomial coefficients tells
4325 us that the alternating sum of binomial coefficients
4326 ${n \choose 0} - {n \choose 1} + {n \choose 2} - \cdots \pm {n \choose n}$
4327 always comes out to zero.  Let's verify this
4328 for \cite{n=6}.
4329 @end tex
4331 @group
4332 @smallexample
4333 1:  [1, 2, 3, 4, 5, 6, 7]     1:  [0, 1, 2, 3, 4, 5, 6]
4334     .                             .
4336     v x 7 RET                     1 -
4338 @end smallexample
4339 @end group
4340 @noindent
4341 @group
4342 @smallexample
4343 1:  [1, -6, 15, -20, 15, -6, 1]          1:  0
4344     .                                        .
4346     V M ' (-1)^$ choose(6,$) RET             V R +
4347 @end smallexample
4348 @end group
4350 The @kbd{V M '} command prompts you to enter any algebraic expression
4351 to define the function to map over the vector.  The symbol @samp{$}
4352 inside this expression represents the argument to the function.
4353 The Calculator applies this formula to each element of the vector,
4354 substituting each element's value for the @samp{$} sign(s) in turn.
4356 To define a two-argument function, use @samp{$$} for the first
4357 argument and @samp{$} for the second:  @kbd{V M ' $$-$ RET} is
4358 equivalent to @kbd{V M -}.  This is analogous to regular algebraic
4359 entry, where @samp{$$} would refer to the next-to-top stack entry
4360 and @samp{$} would refer to the top stack entry, and @kbd{' $$-$ RET}
4361 would act exactly like @kbd{-}.
4363 Notice that the @kbd{V M '} command has recorded two things in the
4364 trail:  The result, as usual, and also a funny-looking thing marked
4365 @samp{oper} that represents the operator function you typed in.
4366 The function is enclosed in @samp{< >} brackets, and the argument is
4367 denoted by a @samp{#} sign.  If there were several arguments, they
4368 would be shown as @samp{#1}, @samp{#2}, and so on.  (For example,
4369 @kbd{V M ' $$-$} will put the function @samp{<#1 - #2>} on the
4370 trail.)  This object is a ``nameless function''; you can use nameless
4371 @w{@samp{< >}} notation to answer the @kbd{V M '} prompt if you like.
4372 Nameless function notation has the interesting, occasionally useful
4373 property that a nameless function is not actually evaluated until
4374 it is used.  For example, @kbd{V M ' $+random(2.0)} evaluates
4375 @samp{random(2.0)} once and adds that random number to all elements
4376 of the vector, but @kbd{V M ' <#+random(2.0)>} evaluates the
4377 @samp{random(2.0)} separately for each vector element.
4379 Another group of operators that are often useful with @kbd{V M} are
4380 the relational operators:  @kbd{a =}, for example, compares two numbers
4381 and gives the result 1 if they are equal, or 0 if not.  Similarly,
4382 @w{@kbd{a <}} checks for one number being less than another.
4384 Other useful vector operations include @kbd{v v}, to reverse a
4385 vector end-for-end; @kbd{V S}, to sort the elements of a vector
4386 into increasing order; and @kbd{v r} and @w{@kbd{v c}}, to extract
4387 one row or column of a matrix, or (in both cases) to extract one
4388 element of a plain vector.  With a negative argument, @kbd{v r}
4389 and @kbd{v c} instead delete one row, column, or vector element.
4391 @cindex Divisor functions
4392 (@bullet{}) @strong{Exercise 4.}  The @cite{k}th @dfn{divisor function}
4393 @tex
4394 $\sigma_k(n)$
4395 @end tex
4396 is the sum of the @cite{k}th powers of all the divisors of an
4397 integer @cite{n}.  Figure out a method for computing the divisor
4398 function for reasonably small values of @cite{n}.  As a test,
4399 the 0th and 1st divisor functions of 30 are 8 and 72, respectively.
4400 @xref{List Answer 4, 4}. (@bullet{})
4402 @cindex Square-free numbers
4403 @cindex Duplicate values in a list
4404 (@bullet{}) @strong{Exercise 5.}  The @kbd{k f} command produces a
4405 list of prime factors for a number.  Sometimes it is important to
4406 know that a number is @dfn{square-free}, i.e., that no prime occurs
4407 more than once in its list of prime factors.  Find a sequence of
4408 keystrokes to tell if a number is square-free; your method should
4409 leave 1 on the stack if it is, or 0 if it isn't.
4410 @xref{List Answer 5, 5}. (@bullet{})
4412 @cindex Triangular lists
4413 (@bullet{}) @strong{Exercise 6.}  Build a list of lists that looks
4414 like the following diagram.  (You may wish to use the @kbd{v /}
4415 command to enable multi-line display of vectors.)
4417 @group
4418 @smallexample
4419 1:  [ [1],
4420       [1, 2],
4421       [1, 2, 3],
4422       [1, 2, 3, 4],
4423       [1, 2, 3, 4, 5],
4424       [1, 2, 3, 4, 5, 6] ]
4425 @end smallexample
4426 @end group
4428 @noindent
4429 @xref{List Answer 6, 6}. (@bullet{})
4431 (@bullet{}) @strong{Exercise 7.}  Build the following list of lists.
4433 @group
4434 @smallexample
4435 1:  [ [0],
4436       [1, 2],
4437       [3, 4, 5],
4438       [6, 7, 8, 9],
4439       [10, 11, 12, 13, 14],
4440       [15, 16, 17, 18, 19, 20] ]
4441 @end smallexample
4442 @end group
4444 @noindent
4445 @xref{List Answer 7, 7}. (@bullet{})
4447 @cindex Maximizing a function over a list of values
4448 @c [fix-ref Numerical Solutions]
4449 (@bullet{}) @strong{Exercise 8.}  Compute a list of values of Bessel's
4450 @c{$J_1(x)$}
4451 @cite{J1} function @samp{besJ(1,x)} for @cite{x} from 0 to 5
4452 in steps of 0.25.
4453 Find the value of @cite{x} (from among the above set of values) for
4454 which @samp{besJ(1,x)} is a maximum.  Use an ``automatic'' method,
4455 i.e., just reading along the list by hand to find the largest value
4456 is not allowed!  (There is an @kbd{a X} command which does this kind
4457 of thing automatically; @pxref{Numerical Solutions}.)
4458 @xref{List Answer 8, 8}. (@bullet{})@refill
4460 @cindex Digits, vectors of
4461 (@bullet{}) @strong{Exercise 9.}  You are given an integer in the range
4462 @c{$0 \le N < 10^m$}
4463 @cite{0 <= N < 10^m} for @cite{m=12} (i.e., an integer of less than
4464 twelve digits).  Convert this integer into a vector of @cite{m}
4465 digits, each in the range from 0 to 9.  In vector-of-digits notation,
4466 add one to this integer to produce a vector of @cite{m+1} digits
4467 (since there could be a carry out of the most significant digit).
4468 Convert this vector back into a regular integer.  A good integer
4469 to try is 25129925999.  @xref{List Answer 9, 9}. (@bullet{})
4471 (@bullet{}) @strong{Exercise 10.}  Your friend Joe tried to use
4472 @kbd{V R a =} to test if all numbers in a list were equal.  What
4473 happened?  How would you do this test?  @xref{List Answer 10, 10}. (@bullet{})
4475 (@bullet{}) @strong{Exercise 11.}  The area of a circle of radius one
4476 is @c{$\pi$}
4477 @cite{pi}.  The area of the @c{$2\times2$}
4478 @asis{2x2} square that encloses that
4479 circle is 4.  So if we throw @i{N} darts at random points in the square,
4480 about @c{$\pi/4$}
4481 @cite{pi/4} of them will land inside the circle.  This gives us
4482 an entertaining way to estimate the value of @c{$\pi$}
4483 @cite{pi}.  The @w{@kbd{k r}}
4484 command picks a random number between zero and the value on the stack.
4485 We could get a random floating-point number between @i{-1} and 1 by typing
4486 @w{@kbd{2.0 k r 1 -}}.  Build a vector of 100 random @cite{(x,y)} points in
4487 this square, then use vector mapping and reduction to count how many
4488 points lie inside the unit circle.  Hint:  Use the @kbd{v b} command.
4489 @xref{List Answer 11, 11}. (@bullet{})
4491 @cindex Matchstick problem
4492 (@bullet{}) @strong{Exercise 12.}  The @dfn{matchstick problem} provides
4493 another way to calculate @c{$\pi$}
4494 @cite{pi}.  Say you have an infinite field
4495 of vertical lines with a spacing of one inch.  Toss a one-inch matchstick
4496 onto the field.  The probability that the matchstick will land crossing
4497 a line turns out to be @c{$2/\pi$}
4498 @cite{2/pi}.  Toss 100 matchsticks to estimate
4499 @c{$\pi$}
4500 @cite{pi}.  (If you want still more fun, the probability that the GCD
4501 (@w{@kbd{k g}}) of two large integers is one turns out to be @c{$6/\pi^2$}
4502 @cite{6/pi^2}.
4503 That provides yet another way to estimate @c{$\pi$}
4504 @cite{pi}.)
4505 @xref{List Answer 12, 12}. (@bullet{})
4507 (@bullet{}) @strong{Exercise 13.}  An algebraic entry of a string in
4508 double-quote marks, @samp{"hello"}, creates a vector of the numerical
4509 (ASCII) codes of the characters (here, @cite{[104, 101, 108, 108, 111]}).
4510 Sometimes it is convenient to compute a @dfn{hash code} of a string,
4511 which is just an integer that represents the value of that string.
4512 Two equal strings have the same hash code; two different strings
4513 @dfn{probably} have different hash codes.  (For example, Calc has
4514 over 400 function names, but Emacs can quickly find the definition for
4515 any given name because it has sorted the functions into ``buckets'' by
4516 their hash codes.  Sometimes a few names will hash into the same bucket,
4517 but it is easier to search among a few names than among all the names.)
4518 One popular hash function is computed as follows:  First set @cite{h = 0}.
4519 Then, for each character from the string in turn, set @cite{h = 3h + c_i}
4520 where @cite{c_i} is the character's ASCII code.  If we have 511 buckets,
4521 we then take the hash code modulo 511 to get the bucket number.  Develop a
4522 simple command or commands for converting string vectors into hash codes.
4523 The hash code for @samp{"Testing, 1, 2, 3"} is 1960915098, which modulo
4524 511 is 121.  @xref{List Answer 13, 13}. (@bullet{})
4526 (@bullet{}) @strong{Exercise 14.}  The @kbd{H V R} and @kbd{H V U}
4527 commands do nested function evaluations.  @kbd{H V U} takes a starting
4528 value and a number of steps @var{n} from the stack; it then applies the
4529 function you give to the starting value 0, 1, 2, up to @var{n} times
4530 and returns a vector of the results.  Use this command to create a
4531 ``random walk'' of 50 steps.  Start with the two-dimensional point
4532 @cite{(0,0)}; then take one step a random distance between @i{-1} and 1
4533 in both @cite{x} and @cite{y}; then take another step, and so on.  Use the
4534 @kbd{g f} command to display this random walk.  Now modify your random
4535 walk to walk a unit distance, but in a random direction, at each step.
4536 (Hint:  The @code{sincos} function returns a vector of the cosine and
4537 sine of an angle.)  @xref{List Answer 14, 14}. (@bullet{})
4539 @node Types Tutorial, Algebra Tutorial, Vector/Matrix Tutorial, Tutorial
4540 @section Types Tutorial
4542 @noindent
4543 Calc understands a variety of data types as well as simple numbers.
4544 In this section, we'll experiment with each of these types in turn.
4546 The numbers we've been using so far have mainly been either @dfn{integers}
4547 or @dfn{floats}.  We saw that floats are usually a good approximation to
4548 the mathematical concept of real numbers, but they are only approximations
4549 and are susceptible to roundoff error.  Calc also supports @dfn{fractions},
4550 which can exactly represent any rational number.
4552 @group
4553 @smallexample
4554 1:  3628800    2:  3628800    1:  518400:7   1:  518414:7   1:  7:518414
4555     .          1:  49             .              .              .
4556                    .
4558     10 !           49 RET         :              2 +            &
4559 @end smallexample
4560 @end group
4562 @noindent
4563 The @kbd{:} command divides two integers to get a fraction; @kbd{/}
4564 would normally divide integers to get a floating-point result.
4565 Notice we had to type @key{RET} between the @kbd{49} and the @kbd{:}
4566 since the @kbd{:} would otherwise be interpreted as part of a
4567 fraction beginning with 49.
4569 You can convert between floating-point and fractional format using
4570 @kbd{c f} and @kbd{c F}:
4572 @group
4573 @smallexample
4574 1:  1.35027217629e-5    1:  7:518414
4575     .                       .
4577     c f                     c F
4578 @end smallexample
4579 @end group
4581 The @kbd{c F} command replaces a floating-point number with the
4582 ``simplest'' fraction whose floating-point representation is the
4583 same, to within the current precision.
4585 @group
4586 @smallexample
4587 1:  3.14159265359   1:  1146408:364913   1:  3.1416   1:  355:113
4588     .                   .                    .            .
4590     P                   c F      DEL       p 5 RET P      c F
4591 @end smallexample
4592 @end group
4594 (@bullet{}) @strong{Exercise 1.}  A calculation has produced the
4595 result 1.26508260337.  You suspect it is the square root of the
4596 product of @c{$\pi$}
4597 @cite{pi} and some rational number.  Is it?  (Be sure
4598 to allow for roundoff error!)  @xref{Types Answer 1, 1}. (@bullet{})
4600 @dfn{Complex numbers} can be stored in both rectangular and polar form.
4602 @group
4603 @smallexample
4604 1:  -9     1:  (0, 3)    1:  (3; 90.)   1:  (6; 90.)   1:  (2.4495; 45.)
4605     .          .             .              .              .
4607     9 n        Q             c p            2 *            Q
4608 @end smallexample
4609 @end group
4611 @noindent
4612 The square root of @i{-9} is by default rendered in rectangular form
4613 (@w{@cite{0 + 3i}}), but we can convert it to polar form (3 with a
4614 phase angle of 90 degrees).  All the usual arithmetic and scientific
4615 operations are defined on both types of complex numbers.
4617 Another generalized kind of number is @dfn{infinity}.  Infinity
4618 isn't really a number, but it can sometimes be treated like one.
4619 Calc uses the symbol @code{inf} to represent positive infinity,
4620 i.e., a value greater than any real number.  Naturally, you can
4621 also write @samp{-inf} for minus infinity, a value less than any
4622 real number.  The word @code{inf} can only be input using
4623 algebraic entry.
4625 @group
4626 @smallexample
4627 2:  inf        2:  -inf       2:  -inf       2:  -inf       1:  nan
4628 1:  -17        1:  -inf       1:  -inf       1:  inf            .
4629     .              .              .              .
4631 ' inf RET 17 n     *  RET         72 +           A              +
4632 @end smallexample
4633 @end group
4635 @noindent
4636 Since infinity is infinitely large, multiplying it by any finite
4637 number (like @i{-17}) has no effect, except that since @i{-17}
4638 is negative, it changes a plus infinity to a minus infinity.
4639 (``A huge positive number, multiplied by @i{-17}, yields a huge
4640 negative number.'')  Adding any finite number to infinity also
4641 leaves it unchanged.  Taking an absolute value gives us plus
4642 infinity again.  Finally, we add this plus infinity to the minus
4643 infinity we had earlier.  If you work it out, you might expect
4644 the answer to be @i{-72} for this.  But the 72 has been completely
4645 lost next to the infinities; by the time we compute @w{@samp{inf - inf}}
4646 the finite difference between them, if any, is indetectable.
4647 So we say the result is @dfn{indeterminate}, which Calc writes
4648 with the symbol @code{nan} (for Not A Number).
4650 Dividing by zero is normally treated as an error, but you can get
4651 Calc to write an answer in terms of infinity by pressing @kbd{m i}
4652 to turn on ``infinite mode.''
4654 @group
4655 @smallexample
4656 3:  nan        2:  nan        2:  nan        2:  nan        1:  nan
4657 2:  1          1:  1 / 0      1:  uinf       1:  uinf           .
4658 1:  0              .              .              .
4659     .
4661   1 RET 0          /       m i    U /            17 n *         +
4662 @end smallexample
4663 @end group
4665 @noindent
4666 Dividing by zero normally is left unevaluated, but after @kbd{m i}
4667 it instead gives an infinite result.  The answer is actually
4668 @code{uinf}, ``undirected infinity.''  If you look at a graph of
4669 @cite{1 / x} around @w{@cite{x = 0}}, you'll see that it goes toward
4670 plus infinity as you approach zero from above, but toward minus
4671 infinity as you approach from below.  Since we said only @cite{1 / 0},
4672 Calc knows that the answer is infinite but not in which direction.
4673 That's what @code{uinf} means.  Notice that multiplying @code{uinf}
4674 by a negative number still leaves plain @code{uinf}; there's no
4675 point in saying @samp{-uinf} because the sign of @code{uinf} is
4676 unknown anyway.  Finally, we add @code{uinf} to our @code{nan},
4677 yielding @code{nan} again.  It's easy to see that, because
4678 @code{nan} means ``totally unknown'' while @code{uinf} means
4679 ``unknown sign but known to be infinite,'' the more mysterious
4680 @code{nan} wins out when it is combined with @code{uinf}, or, for
4681 that matter, with anything else.
4683 (@bullet{}) @strong{Exercise 2.}  Predict what Calc will answer
4684 for each of these formulas:  @samp{inf / inf}, @samp{exp(inf)},
4685 @samp{exp(-inf)}, @samp{sqrt(-inf)}, @samp{sqrt(uinf)},
4686 @samp{abs(uinf)}, @samp{ln(0)}.
4687 @xref{Types Answer 2, 2}. (@bullet{})
4689 (@bullet{}) @strong{Exercise 3.}  We saw that @samp{inf - inf = nan},
4690 which stands for an unknown value.  Can @code{nan} stand for
4691 a complex number?  Can it stand for infinity?
4692 @xref{Types Answer 3, 3}. (@bullet{})
4694 @dfn{HMS forms} represent a value in terms of hours, minutes, and
4695 seconds.
4697 @group
4698 @smallexample
4699 1:  2@@ 30' 0"     1:  3@@ 30' 0"     2:  3@@ 30' 0"     1:  2.
4700     .                 .             1:  1@@ 45' 0."        .
4701                                         .
4703   2@@ 30' RET          1 +               RET 2 /           /
4704 @end smallexample
4705 @end group
4707 HMS forms can also be used to hold angles in degrees, minutes, and
4708 seconds.
4710 @group
4711 @smallexample
4712 1:  0.5        1:  26.56505   1:  26@@ 33' 54.18"    1:  0.44721
4713     .              .              .                     .
4715     0.5            I T            c h                   S
4716 @end smallexample
4717 @end group
4719 @noindent
4720 First we convert the inverse tangent of 0.5 to degrees-minutes-seconds
4721 form, then we take the sine of that angle.  Note that the trigonometric
4722 functions will accept HMS forms directly as input.
4724 @cindex Beatles
4725 (@bullet{}) @strong{Exercise 4.}  The Beatles' @emph{Abbey Road} is
4726 47 minutes and 26 seconds long, and contains 17 songs.  What is the
4727 average length of a song on @emph{Abbey Road}?  If the Extended Disco
4728 Version of @emph{Abbey Road} added 20 seconds to the length of each
4729 song, how long would the album be?  @xref{Types Answer 4, 4}. (@bullet{})
4731 A @dfn{date form} represents a date, or a date and time.  Dates must
4732 be entered using algebraic entry.  Date forms are surrounded by
4733 @samp{< >} symbols; most standard formats for dates are recognized.
4735 @group
4736 @smallexample
4737 2:  <Sun Jan 13, 1991>                    1:  2.25
4738 1:  <6:00pm Thu Jan 10, 1991>                 .
4739     .
4741 ' <13 Jan 1991>, <1/10/91, 6pm> RET           -
4742 @end smallexample
4743 @end group
4745 @noindent
4746 In this example, we enter two dates, then subtract to find the
4747 number of days between them.  It is also possible to add an
4748 HMS form or a number (of days) to a date form to get another
4749 date form.
4751 @group
4752 @smallexample
4753 1:  <4:45:59pm Mon Jan 14, 1991>     1:  <2:50:59am Thu Jan 17, 1991>
4754     .                                    .
4756     t N                                  2 + 10@@ 5' +
4757 @end smallexample
4758 @end group
4760 @c [fix-ref Date Arithmetic]
4761 @noindent
4762 The @kbd{t N} (``now'') command pushes the current date and time on the
4763 stack; then we add two days, ten hours and five minutes to the date and
4764 time.  Other date-and-time related commands include @kbd{t J}, which
4765 does Julian day conversions, @kbd{t W}, which finds the beginning of
4766 the week in which a date form lies, and @kbd{t I}, which increments a
4767 date by one or several months.  @xref{Date Arithmetic}, for more.
4769 (@bullet{}) @strong{Exercise 5.}  How many days until the next
4770 Friday the 13th?  @xref{Types Answer 5, 5}. (@bullet{})
4772 (@bullet{}) @strong{Exercise 6.}  How many leap years will there be
4773 between now and the year 10001 A.D.?  @xref{Types Answer 6, 6}. (@bullet{})
4775 @cindex Slope and angle of a line
4776 @cindex Angle and slope of a line
4777 An @dfn{error form} represents a mean value with an attached standard
4778 deviation, or error estimate.  Suppose our measurements indicate that
4779 a certain telephone pole is about 30 meters away, with an estimated
4780 error of 1 meter, and 8 meters tall, with an estimated error of 0.2
4781 meters.  What is the slope of a line from here to the top of the
4782 pole, and what is the equivalent angle in degrees?
4784 @group
4785 @smallexample
4786 1:  8 +/- 0.2    2:  8 +/- 0.2   1:  0.266 +/- 0.011   1:  14.93 +/- 0.594
4787     .            1:  30 +/- 1        .                     .
4788                      .
4790     8 p .2 RET       30 p 1          /                     I T
4791 @end smallexample
4792 @end group
4794 @noindent
4795 This means that the angle is about 15 degrees, and, assuming our
4796 original error estimates were valid standard deviations, there is about
4797 a 60% chance that the result is correct within 0.59 degrees.
4799 @cindex Torus, volume of
4800 (@bullet{}) @strong{Exercise 7.}  The volume of a torus (a donut shape) is
4801 @c{$2 \pi^2 R r^2$}
4802 @w{@cite{2 pi^2 R r^2}} where @cite{R} is the radius of the circle that
4803 defines the center of the tube and @cite{r} is the radius of the tube
4804 itself.  Suppose @cite{R} is 20 cm and @cite{r} is 4 cm, each known to
4805 within 5 percent.  What is the volume and the relative uncertainty of
4806 the volume?  @xref{Types Answer 7, 7}. (@bullet{})
4808 An @dfn{interval form} represents a range of values.  While an
4809 error form is best for making statistical estimates, intervals give
4810 you exact bounds on an answer.  Suppose we additionally know that
4811 our telephone pole is definitely between 28 and 31 meters away,
4812 and that it is between 7.7 and 8.1 meters tall.
4814 @group
4815 @smallexample
4816 1:  [7.7 .. 8.1]  2:  [7.7 .. 8.1]  1:  [0.24 .. 0.28]  1:  [13.9 .. 16.1]
4817     .             1:  [28 .. 31]        .                   .
4818                       .
4820   [ 7.7 .. 8.1 ]    [ 28 .. 31 ]        /                   I T
4821 @end smallexample
4822 @end group
4824 @noindent
4825 If our bounds were correct, then the angle to the top of the pole
4826 is sure to lie in the range shown.
4828 The square brackets around these intervals indicate that the endpoints
4829 themselves are allowable values.  In other words, the distance to the
4830 telephone pole is between 28 and 31, @emph{inclusive}.  You can also
4831 make an interval that is exclusive of its endpoints by writing
4832 parentheses instead of square brackets.  You can even make an interval
4833 which is inclusive (``closed'') on one end and exclusive (``open'') on
4834 the other.
4836 @group
4837 @smallexample
4838 1:  [1 .. 10)    1:  (0.1 .. 1]   2:  (0.1 .. 1]   1:  (0.2 .. 3)
4839     .                .            1:  [2 .. 3)         .
4840                                       .
4842   [ 1 .. 10 )        &              [ 2 .. 3 )         *
4843 @end smallexample
4844 @end group
4846 @noindent
4847 The Calculator automatically keeps track of which end values should
4848 be open and which should be closed.  You can also make infinite or
4849 semi-infinite intervals by using @samp{-inf} or @samp{inf} for one
4850 or both endpoints.
4852 (@bullet{}) @strong{Exercise 8.}  What answer would you expect from
4853 @samp{@w{1 /} @w{(0 .. 10)}}?  What about @samp{@w{1 /} @w{(-10 .. 0)}}?  What
4854 about @samp{@w{1 /} @w{[0 .. 10]}} (where the interval actually includes
4855 zero)?  What about @samp{@w{1 /} @w{(-10 .. 10)}}?
4856 @xref{Types Answer 8, 8}. (@bullet{})
4858 (@bullet{}) @strong{Exercise 9.}  Two easy ways of squaring a number
4859 are @kbd{RET *} and @w{@kbd{2 ^}}.  Normally these produce the same
4860 answer.  Would you expect this still to hold true for interval forms?
4861 If not, which of these will result in a larger interval?
4862 @xref{Types Answer 9, 9}. (@bullet{})
4864 A @dfn{modulo form} is used for performing arithmetic modulo @i{M}.
4865 For example, arithmetic involving time is generally done modulo 12
4866 or 24 hours.
4868 @group
4869 @smallexample
4870 1:  17 mod 24    1:  3 mod 24     1:  21 mod 24    1:  9 mod 24
4871     .                .                .                .
4873     17 M 24 RET      10 +             n                5 /
4874 @end smallexample
4875 @end group
4877 @noindent
4878 In this last step, Calc has found a new number which, when multiplied
4879 by 5 modulo 24, produces the original number, 21.  If @i{M} is prime
4880 it is always possible to find such a number.  For non-prime @i{M}
4881 like 24, it is only sometimes possible.
4883 @group
4884 @smallexample
4885 1:  10 mod 24    1:  16 mod 24    1:  1000000...   1:  16
4886     .                .                .                .
4888     10 M 24 RET      100 ^            10 RET 100 ^     24 %
4889 @end smallexample
4890 @end group
4892 @noindent
4893 These two calculations get the same answer, but the first one is
4894 much more efficient because it avoids the huge intermediate value
4895 that arises in the second one.
4897 @cindex Fermat, primality test of
4898 (@bullet{}) @strong{Exercise 10.}  A theorem of Pierre de Fermat
4899 says that @c{\w{$x^{n-1} \bmod n = 1$}}
4900 @cite{x^(n-1) mod n = 1} if @cite{n} is a prime number
4901 and @cite{x} is an integer less than @cite{n}.  If @cite{n} is
4902 @emph{not} a prime number, this will @emph{not} be true for most
4903 values of @cite{x}.  Thus we can test informally if a number is
4904 prime by trying this formula for several values of @cite{x}.
4905 Use this test to tell whether the following numbers are prime:
4906 811749613, 15485863.  @xref{Types Answer 10, 10}. (@bullet{})
4908 It is possible to use HMS forms as parts of error forms, intervals,
4909 modulo forms, or as the phase part of a polar complex number.
4910 For example, the @code{calc-time} command pushes the current time
4911 of day on the stack as an HMS/modulo form.
4913 @group
4914 @smallexample
4915 1:  17@@ 34' 45" mod 24@@ 0' 0"     1:  6@@ 22' 15" mod 24@@ 0' 0"
4916     .                                 .
4918     x time RET                        n
4919 @end smallexample
4920 @end group
4922 @noindent
4923 This calculation tells me it is six hours and 22 minutes until midnight.
4925 (@bullet{}) @strong{Exercise 11.}  A rule of thumb is that one year
4926 is about @c{$\pi \times 10^7$}
4927 @w{@cite{pi * 10^7}} seconds.  What time will it be that
4928 many seconds from right now?  @xref{Types Answer 11, 11}. (@bullet{})
4930 (@bullet{}) @strong{Exercise 12.}  You are preparing to order packaging
4931 for the CD release of the Extended Disco Version of @emph{Abbey Road}.
4932 You are told that the songs will actually be anywhere from 20 to 60
4933 seconds longer than the originals.  One CD can hold about 75 minutes
4934 of music.  Should you order single or double packages?
4935 @xref{Types Answer 12, 12}. (@bullet{})
4937 Another kind of data the Calculator can manipulate is numbers with
4938 @dfn{units}.  This isn't strictly a new data type; it's simply an
4939 application of algebraic expressions, where we use variables with
4940 suggestive names like @samp{cm} and @samp{in} to represent units
4941 like centimeters and inches.
4943 @group
4944 @smallexample
4945 1:  2 in        1:  5.08 cm      1:  0.027778 fath   1:  0.0508 m
4946     .               .                .                   .
4948     ' 2in RET       u c cm RET       u c fath RET        u b
4949 @end smallexample
4950 @end group
4952 @noindent
4953 We enter the quantity ``2 inches'' (actually an algebraic expression
4954 which means two times the variable @samp{in}), then we convert it
4955 first to centimeters, then to fathoms, then finally to ``base'' units,
4956 which in this case means meters.
4958 @group
4959 @smallexample
4960 1:  9 acre     1:  3 sqrt(acre)   1:  190.84 m   1:  190.84 m + 30 cm
4961     .              .                  .              .
4963  ' 9 acre RET      Q                  u s            ' $+30 cm RET
4965 @end smallexample
4966 @end group
4967 @noindent
4968 @group
4969 @smallexample
4970 1:  191.14 m     1:  36536.3046 m^2    1:  365363046 cm^2
4971     .                .                     .
4973     u s              2 ^                   u c cgs
4974 @end smallexample
4975 @end group
4977 @noindent
4978 Since units expressions are really just formulas, taking the square
4979 root of @samp{acre} is undefined.  After all, @code{acre} might be an
4980 algebraic variable that you will someday assign a value.  We use the
4981 ``units-simplify'' command to simplify the expression with variables
4982 being interpreted as unit names.
4984 In the final step, we have converted not to a particular unit, but to a
4985 units system.  The ``cgs'' system uses centimeters instead of meters
4986 as its standard unit of length.
4988 There is a wide variety of units defined in the Calculator.
4990 @group
4991 @smallexample
4992 1:  55 mph     1:  88.5139 kph   1:   88.5139 km / hr   1:  8.201407e-8 c
4993     .              .                  .                     .
4995  ' 55 mph RET      u c kph RET        u c km/hr RET         u c c RET
4996 @end smallexample
4997 @end group
4999 @noindent
5000 We express a speed first in miles per hour, then in kilometers per
5001 hour, then again using a slightly more explicit notation, then
5002 finally in terms of fractions of the speed of light.
5004 Temperature conversions are a bit more tricky.  There are two ways to
5005 interpret ``20 degrees Fahrenheit''---it could mean an actual
5006 temperature, or it could mean a change in temperature.  For normal
5007 units there is no difference, but temperature units have an offset
5008 as well as a scale factor and so there must be two explicit commands
5009 for them.
5011 @group
5012 @smallexample
5013 1:  20 degF       1:  11.1111 degC     1:  -20:3 degC    1:  -6.666 degC
5014     .                 .                    .                 .
5016   ' 20 degF RET       u c degC RET         U u t degC RET    c f
5017 @end smallexample
5018 @end group
5020 @noindent
5021 First we convert a change of 20 degrees Fahrenheit into an equivalent
5022 change in degrees Celsius (or Centigrade).  Then, we convert the
5023 absolute temperature 20 degrees Fahrenheit into Celsius.  Since
5024 this comes out as an exact fraction, we then convert to floating-point
5025 for easier comparison with the other result.
5027 For simple unit conversions, you can put a plain number on the stack.
5028 Then @kbd{u c} and @kbd{u t} will prompt for both old and new units.
5029 When you use this method, you're responsible for remembering which
5030 numbers are in which units:
5032 @group
5033 @smallexample
5034 1:  55         1:  88.5139              1:  8.201407e-8
5035     .              .                        .
5037     55             u c mph RET kph RET      u c km/hr RET c RET
5038 @end smallexample
5039 @end group
5041 To see a complete list of built-in units, type @kbd{u v}.  Press
5042 @w{@kbd{M-# c}} again to re-enter the Calculator when you're done looking
5043 at the units table.
5045 (@bullet{}) @strong{Exercise 13.}  How many seconds are there really
5046 in a year?  @xref{Types Answer 13, 13}. (@bullet{})
5048 @cindex Speed of light
5049 (@bullet{}) @strong{Exercise 14.}  Supercomputer designs are limited by
5050 the speed of light (and of electricity, which is nearly as fast).
5051 Suppose a computer has a 4.1 ns (nanosecond) clock cycle, and its
5052 cabinet is one meter across.  Is speed of light going to be a
5053 significant factor in its design?  @xref{Types Answer 14, 14}. (@bullet{})
5055 (@bullet{}) @strong{Exercise 15.}  Sam the Slug normally travels about
5056 five yards in an hour.  He has obtained a supply of Power Pills; each
5057 Power Pill he eats doubles his speed.  How many Power Pills can he
5058 swallow and still travel legally on most US highways?
5059 @xref{Types Answer 15, 15}. (@bullet{})
5061 @node Algebra Tutorial, Programming Tutorial, Types Tutorial, Tutorial
5062 @section Algebra and Calculus Tutorial
5064 @noindent
5065 This section shows how to use Calc's algebra facilities to solve
5066 equations, do simple calculus problems, and manipulate algebraic
5067 formulas.
5069 @menu
5070 * Basic Algebra Tutorial::
5071 * Rewrites Tutorial::
5072 @end menu
5074 @node Basic Algebra Tutorial, Rewrites Tutorial, Algebra Tutorial, Algebra Tutorial
5075 @subsection Basic Algebra
5077 @noindent
5078 If you enter a formula in algebraic mode that refers to variables,
5079 the formula itself is pushed onto the stack.  You can manipulate
5080 formulas as regular data objects.
5082 @group
5083 @smallexample
5084 1:  2 x^2 - 6       1:  6 - 2 x^2       1:  (6 - 2 x^2) (3 x^2 + y)
5085     .                   .                   .
5087     ' 2x^2-6 RET        n                   ' 3x^2+y RET *
5088 @end smallexample
5089 @end group
5091 (@bullet{}) @strong{Exercise 1.}  Do @kbd{' x RET Q 2 ^} and
5092 @kbd{' x RET 2 ^ Q} both wind up with the same result (@samp{x})?
5093 Why or why not?  @xref{Algebra Answer 1, 1}. (@bullet{})
5095 There are also commands for doing common algebraic operations on
5096 formulas.  Continuing with the formula from the last example,
5098 @group
5099 @smallexample
5100 1:  18 x^2 + 6 y - 6 x^4 - 2 x^2 y    1:  (18 - 2 y) x^2 - 6 x^4 + 6 y
5101     .                                     .
5103     a x                                   a c x RET
5104 @end smallexample
5105 @end group
5107 @noindent
5108 First we ``expand'' using the distributive law, then we ``collect''
5109 terms involving like powers of @cite{x}.
5111 Let's find the value of this expression when @cite{x} is 2 and @cite{y}
5112 is one-half.
5114 @group
5115 @smallexample
5116 1:  17 x^2 - 6 x^4 + 3      1:  -25
5117     .                           .
5119     1:2 s l y RET               2 s l x RET
5120 @end smallexample
5121 @end group
5123 @noindent
5124 The @kbd{s l} command means ``let''; it takes a number from the top of
5125 the stack and temporarily assigns it as the value of the variable
5126 you specify.  It then evaluates (as if by the @kbd{=} key) the
5127 next expression on the stack.  After this command, the variable goes
5128 back to its original value, if any.
5130 (An earlier exercise in this tutorial involved storing a value in the
5131 variable @code{x}; if this value is still there, you will have to
5132 unstore it with @kbd{s u x RET} before the above example will work
5133 properly.)
5135 @cindex Maximum of a function using Calculus
5136 Let's find the maximum value of our original expression when @cite{y}
5137 is one-half and @cite{x} ranges over all possible values.  We can
5138 do this by taking the derivative with respect to @cite{x} and examining
5139 values of @cite{x} for which the derivative is zero.  If the second
5140 derivative of the function at that value of @cite{x} is negative,
5141 the function has a local maximum there.
5143 @group
5144 @smallexample
5145 1:  17 x^2 - 6 x^4 + 3      1:  34 x - 24 x^3
5146     .                           .
5148     U DEL  s 1                  a d x RET   s 2
5149 @end smallexample
5150 @end group
5152 @noindent
5153 Well, the derivative is clearly zero when @cite{x} is zero.  To find
5154 the other root(s), let's divide through by @cite{x} and then solve:
5156 @group
5157 @smallexample
5158 1:  (34 x - 24 x^3) / x    1:  34 x / x - 24 x^3 / x    1:  34 - 24 x^2
5159     .                          .                            .
5161     ' x RET /                  a x                          a s
5163 @end smallexample
5164 @end group
5165 @noindent
5166 @group
5167 @smallexample
5168 1:  34 - 24 x^2 = 0        1:  x = 1.19023
5169     .                          .
5171     0 a =  s 3                 a S x RET
5172 @end smallexample
5173 @end group
5175 @noindent
5176 Notice the use of @kbd{a s} to ``simplify'' the formula.  When the
5177 default algebraic simplifications don't do enough, you can use
5178 @kbd{a s} to tell Calc to spend more time on the job.
5180 Now we compute the second derivative and plug in our values of @cite{x}:
5182 @group
5183 @smallexample
5184 1:  1.19023        2:  1.19023         2:  1.19023
5185     .              1:  34 x - 24 x^3   1:  34 - 72 x^2
5186                        .                   .
5188     a .                r 2                 a d x RET s 4
5189 @end smallexample
5190 @end group
5192 @noindent
5193 (The @kbd{a .} command extracts just the righthand side of an equation.
5194 Another method would have been to use @kbd{v u} to unpack the equation
5195 @w{@samp{x = 1.19}} to @samp{x} and @samp{1.19}, then use @kbd{M-- M-2 DEL}
5196 to delete the @samp{x}.)
5198 @group
5199 @smallexample
5200 2:  34 - 72 x^2   1:  -68.         2:  34 - 72 x^2     1:  34
5201 1:  1.19023           .            1:  0                   .
5202     .                                  .
5204     TAB               s l x RET        U DEL 0             s l x RET
5205 @end smallexample
5206 @end group
5208 @noindent
5209 The first of these second derivatives is negative, so we know the function
5210 has a maximum value at @cite{x = 1.19023}.  (The function also has a
5211 local @emph{minimum} at @cite{x = 0}.)
5213 When we solved for @cite{x}, we got only one value even though
5214 @cite{34 - 24 x^2 = 0} is a quadratic equation that ought to have
5215 two solutions.  The reason is that @w{@kbd{a S}} normally returns a
5216 single ``principal'' solution.  If it needs to come up with an
5217 arbitrary sign (as occurs in the quadratic formula) it picks @cite{+}.
5218 If it needs an arbitrary integer, it picks zero.  We can get a full
5219 solution by pressing @kbd{H} (the Hyperbolic flag) before @kbd{a S}.
5221 @group
5222 @smallexample
5223 1:  34 - 24 x^2 = 0    1:  x = 1.19023 s1      1:  x = -1.19023
5224     .                      .                       .
5226     r 3                    H a S x RET  s 5        1 n  s l s1 RET
5227 @end smallexample
5228 @end group
5230 @noindent
5231 Calc has invented the variable @samp{s1} to represent an unknown sign;
5232 it is supposed to be either @i{+1} or @i{-1}.  Here we have used
5233 the ``let'' command to evaluate the expression when the sign is negative.
5234 If we plugged this into our second derivative we would get the same,
5235 negative, answer, so @cite{x = -1.19023} is also a maximum.
5237 To find the actual maximum value, we must plug our two values of @cite{x}
5238 into the original formula.
5240 @group
5241 @smallexample
5242 2:  17 x^2 - 6 x^4 + 3    1:  24.08333 s1^2 - 12.04166 s1^4 + 3
5243 1:  x = 1.19023 s1            .
5244     .
5246     r 1 r 5                   s l RET
5247 @end smallexample
5248 @end group
5250 @noindent
5251 (Here we see another way to use @kbd{s l}; if its input is an equation
5252 with a variable on the lefthand side, then @kbd{s l} treats the equation
5253 like an assignment to that variable if you don't give a variable name.)
5255 It's clear that this will have the same value for either sign of
5256 @code{s1}, but let's work it out anyway, just for the exercise:
5258 @group
5259 @smallexample
5260 2:  [-1, 1]              1:  [15.04166, 15.04166]
5261 1:  24.08333 s1^2 ...        .
5262     .
5264   [ 1 n , 1 ] TAB            V M $ RET
5265 @end smallexample
5266 @end group
5268 @noindent
5269 Here we have used a vector mapping operation to evaluate the function
5270 at several values of @samp{s1} at once.  @kbd{V M $} is like @kbd{V M '}
5271 except that it takes the formula from the top of the stack.  The
5272 formula is interpreted as a function to apply across the vector at the
5273 next-to-top stack level.  Since a formula on the stack can't contain
5274 @samp{$} signs, Calc assumes the variables in the formula stand for
5275 different arguments.  It prompts you for an @dfn{argument list}, giving
5276 the list of all variables in the formula in alphabetical order as the
5277 default list.  In this case the default is @samp{(s1)}, which is just
5278 what we want so we simply press @key{RET} at the prompt.
5280 If there had been several different values, we could have used
5281 @w{@kbd{V R X}} to find the global maximum.
5283 Calc has a built-in @kbd{a P} command that solves an equation using
5284 @w{@kbd{H a S}} and returns a vector of all the solutions.  It simply
5285 automates the job we just did by hand.  Applied to our original
5286 cubic polynomial, it would produce the vector of solutions
5287 @cite{[1.19023, -1.19023, 0]}.  (There is also an @kbd{a X} command
5288 which finds a local maximum of a function.  It uses a numerical search
5289 method rather than examining the derivatives, and thus requires you
5290 to provide some kind of initial guess to show it where to look.)
5292 (@bullet{}) @strong{Exercise 2.}  Given a vector of the roots of a
5293 polynomial (such as the output of an @kbd{a P} command), what
5294 sequence of commands would you use to reconstruct the original
5295 polynomial?  (The answer will be unique to within a constant
5296 multiple; choose the solution where the leading coefficient is one.)
5297 @xref{Algebra Answer 2, 2}. (@bullet{})
5299 The @kbd{m s} command enables ``symbolic mode,'' in which formulas
5300 like @samp{sqrt(5)} that can't be evaluated exactly are left in
5301 symbolic form rather than giving a floating-point approximate answer.
5302 Fraction mode (@kbd{m f}) is also useful when doing algebra.
5304 @group
5305 @smallexample
5306 2:  34 x - 24 x^3        2:  34 x - 24 x^3
5307 1:  34 x - 24 x^3        1:  [sqrt(51) / 6, sqrt(51) / -6, 0]
5308     .                        .
5310     r 2  RET     m s  m f    a P x RET
5311 @end smallexample
5312 @end group
5314 One more mode that makes reading formulas easier is ``Big mode.''
5316 @group
5317 @smallexample
5318                3
5319 2:  34 x - 24 x
5321       ____   ____
5322      V 51   V 51
5323 1:  [-----, -----, 0]
5324        6     -6
5326     .
5328     d B
5329 @end smallexample
5330 @end group
5332 Here things like powers, square roots, and quotients and fractions
5333 are displayed in a two-dimensional pictorial form.  Calc has other
5334 language modes as well, such as C mode, FORTRAN mode, and @TeX{} mode.
5336 @group
5337 @smallexample
5338 2:  34*x - 24*pow(x, 3)               2:  34*x - 24*x**3
5339 1:  @{sqrt(51) / 6, sqrt(51) / -6, 0@}  1:  /sqrt(51) / 6, sqrt(51) / -6, 0/
5340     .                                     .
5342     d C                                   d F
5344 @end smallexample
5345 @end group
5346 @noindent
5347 @group
5348 @smallexample
5349 3:  34 x - 24 x^3
5350 2:  [@{\sqrt@{51@} \over 6@}, @{\sqrt@{51@} \over -6@}, 0]
5351 1:  @{2 \over 3@} \sqrt@{5@}
5352     .
5354     d T   ' 2 \sqrt@{5@} \over 3 RET
5355 @end smallexample
5356 @end group
5358 @noindent
5359 As you can see, language modes affect both entry and display of
5360 formulas.  They affect such things as the names used for built-in
5361 functions, the set of arithmetic operators and their precedences,
5362 and notations for vectors and matrices.
5364 Notice that @samp{sqrt(51)} may cause problems with older
5365 implementations of C and FORTRAN, which would require something more
5366 like @samp{sqrt(51.0)}.  It is always wise to check over the formulas
5367 produced by the various language modes to make sure they are fully
5368 correct.
5370 Type @kbd{m s}, @kbd{m f}, and @kbd{d N} to reset these modes.  (You
5371 may prefer to remain in Big mode, but all the examples in the tutorial
5372 are shown in normal mode.)
5374 @cindex Area under a curve
5375 What is the area under the portion of this curve from @cite{x = 1} to @cite{2}?
5376 This is simply the integral of the function:
5378 @group
5379 @smallexample
5380 1:  17 x^2 - 6 x^4 + 3     1:  5.6666 x^3 - 1.2 x^5 + 3 x
5381     .                          .
5383     r 1                        a i x
5384 @end smallexample
5385 @end group
5387 @noindent
5388 We want to evaluate this at our two values for @cite{x} and subtract.
5389 One way to do it is again with vector mapping and reduction:
5391 @group
5392 @smallexample
5393 2:  [2, 1]            1:  [12.93333, 7.46666]    1:  5.46666
5394 1:  5.6666 x^3 ...        .                          .
5396    [ 2 , 1 ] TAB          V M $ RET                  V R -
5397 @end smallexample
5398 @end group
5400 (@bullet{}) @strong{Exercise 3.}  Find the integral from 1 to @cite{y}
5401 of @c{$x \sin \pi x$}
5402 @w{@cite{x sin(pi x)}} (where the sine is calculated in radians).
5403 Find the values of the integral for integers @cite{y} from 1 to 5.
5404 @xref{Algebra Answer 3, 3}. (@bullet{})
5406 Calc's integrator can do many simple integrals symbolically, but many
5407 others are beyond its capabilities.  Suppose we wish to find the area
5408 under the curve @c{$\sin x \ln x$}
5409 @cite{sin(x) ln(x)} over the same range of @cite{x}.  If
5410 you entered this formula and typed @kbd{a i x RET} (don't bother to try
5411 this), Calc would work for a long time but would be unable to find a
5412 solution.  In fact, there is no closed-form solution to this integral.
5413 Now what do we do?
5415 @cindex Integration, numerical
5416 @cindex Numerical integration
5417 One approach would be to do the integral numerically.  It is not hard
5418 to do this by hand using vector mapping and reduction.  It is rather
5419 slow, though, since the sine and logarithm functions take a long time.
5420 We can save some time by reducing the working precision.
5422 @group
5423 @smallexample
5424 3:  10                  1:  [1, 1.1, 1.2,  ...  , 1.8, 1.9]
5425 2:  1                       .
5426 1:  0.1
5427     .
5429  10 RET 1 RET .1 RET        C-u v x
5430 @end smallexample
5431 @end group
5433 @noindent
5434 (Note that we have used the extended version of @kbd{v x}; we could
5435 also have used plain @kbd{v x} as follows:  @kbd{v x 10 RET 9 + .1 *}.)
5437 @group
5438 @smallexample
5439 2:  [1, 1.1, ... ]              1:  [0., 0.084941, 0.16993, ... ]
5440 1:  sin(x) ln(x)                    .
5441     .
5443     ' sin(x) ln(x) RET  s 1    m r  p 5 RET   V M $ RET
5445 @end smallexample
5446 @end group
5447 @noindent
5448 @group
5449 @smallexample
5450 1:  3.4195     0.34195
5451     .          .
5453     V R +      0.1 *
5454 @end smallexample
5455 @end group
5457 @noindent
5458 (If you got wildly different results, did you remember to switch
5459 to radians mode?)
5461 Here we have divided the curve into ten segments of equal width;
5462 approximating these segments as rectangular boxes (i.e., assuming
5463 the curve is nearly flat at that resolution), we compute the areas
5464 of the boxes (height times width), then sum the areas.  (It is
5465 faster to sum first, then multiply by the width, since the width
5466 is the same for every box.)
5468 The true value of this integral turns out to be about 0.374, so
5469 we're not doing too well.  Let's try another approach.
5471 @group
5472 @smallexample
5473 1:  sin(x) ln(x)    1:  0.84147 x - 0.84147 + 0.11957 (x - 1)^2 - ...
5474     .                   .
5476     r 1                 a t x=1 RET 4 RET
5477 @end smallexample
5478 @end group
5480 @noindent
5481 Here we have computed the Taylor series expansion of the function
5482 about the point @cite{x=1}.  We can now integrate this polynomial
5483 approximation, since polynomials are easy to integrate.
5485 @group
5486 @smallexample
5487 1:  0.42074 x^2 + ...    1:  [-0.0446, -0.42073]      1:  0.3761
5488     .                        .                            .
5490     a i x RET            [ 2 , 1 ] TAB  V M $ RET         V R -
5491 @end smallexample
5492 @end group
5494 @noindent
5495 Better!  By increasing the precision and/or asking for more terms
5496 in the Taylor series, we can get a result as accurate as we like.
5497 (Taylor series converge better away from singularities in the
5498 function such as the one at @code{ln(0)}, so it would also help to
5499 expand the series about the points @cite{x=2} or @cite{x=1.5} instead
5500 of @cite{x=1}.)
5502 @cindex Simpson's rule
5503 @cindex Integration by Simpson's rule
5504 (@bullet{}) @strong{Exercise 4.}  Our first method approximated the
5505 curve by stairsteps of width 0.1; the total area was then the sum
5506 of the areas of the rectangles under these stairsteps.  Our second
5507 method approximated the function by a polynomial, which turned out
5508 to be a better approximation than stairsteps.  A third method is
5509 @dfn{Simpson's rule}, which is like the stairstep method except
5510 that the steps are not required to be flat.  Simpson's rule boils
5511 down to the formula,
5513 @ifinfo
5514 @example
5515 (h/3) * (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + ...
5516               + 2 f(a+(n-2)*h) + 4 f(a+(n-1)*h) + f(a+n*h))
5517 @end example
5518 @end ifinfo
5519 @tex
5520 \turnoffactive
5521 \beforedisplay
5522 $$ \displaylines{
5523       \qquad {h \over 3} (f(a) + 4 f(a+h) + 2 f(a+2h) + 4 f(a+3h) + \cdots
5524    \hfill \cr \hfill    {} + 2 f(a+(n-2)h) + 4 f(a+(n-1)h) + f(a+n h)) \qquad
5525 } $$
5526 \afterdisplay
5527 @end tex
5529 @noindent
5530 where @cite{n} (which must be even) is the number of slices and @cite{h}
5531 is the width of each slice.  These are 10 and 0.1 in our example.
5532 For reference, here is the corresponding formula for the stairstep
5533 method:
5535 @ifinfo
5536 @example
5537 h * (f(a) + f(a+h) + f(a+2h) + f(a+3h) + ...
5538           + f(a+(n-2)*h) + f(a+(n-1)*h))
5539 @end example
5540 @end ifinfo
5541 @tex
5542 \turnoffactive
5543 \beforedisplay
5544 $$ h (f(a) + f(a+h) + f(a+2h) + f(a+3h) + \cdots
5545            + f(a+(n-2)h) + f(a+(n-1)h)) $$
5546 \afterdisplay
5547 @end tex
5549 Compute the integral from 1 to 2 of @c{$\sin x \ln x$}
5550 @cite{sin(x) ln(x)} using
5551 Simpson's rule with 10 slices.  @xref{Algebra Answer 4, 4}. (@bullet{})
5553 Calc has a built-in @kbd{a I} command for doing numerical integration.
5554 It uses @dfn{Romberg's method}, which is a more sophisticated cousin
5555 of Simpson's rule.  In particular, it knows how to keep refining the
5556 result until the current precision is satisfied.
5558 @c [fix-ref Selecting Sub-Formulas]
5559 Aside from the commands we've seen so far, Calc also provides a
5560 large set of commands for operating on parts of formulas.  You
5561 indicate the desired sub-formula by placing the cursor on any part
5562 of the formula before giving a @dfn{selection} command.  Selections won't
5563 be covered in the tutorial; @pxref{Selecting Subformulas}, for
5564 details and examples.
5566 @c hard exercise: simplify (2^(n r) - 2^(r*(n - 1))) / (2^r - 1) 2^(n - 1)
5567 @c                to 2^((n-1)*(r-1)).
5569 @node Rewrites Tutorial, , Basic Algebra Tutorial, Algebra Tutorial
5570 @subsection Rewrite Rules
5572 @noindent
5573 No matter how many built-in commands Calc provided for doing algebra,
5574 there would always be something you wanted to do that Calc didn't have
5575 in its repertoire.  So Calc also provides a @dfn{rewrite rule} system
5576 that you can use to define your own algebraic manipulations.
5578 Suppose we want to simplify this trigonometric formula:
5580 @group
5581 @smallexample
5582 1:  1 / cos(x) - sin(x) tan(x)
5583     .
5585     ' 1/cos(x) - sin(x) tan(x) RET   s 1
5586 @end smallexample
5587 @end group
5589 @noindent
5590 If we were simplifying this by hand, we'd probably replace the
5591 @samp{tan} with a @samp{sin/cos} first, then combine over a common
5592 denominator.  There is no Calc command to do the former; the @kbd{a n}
5593 algebra command will do the latter but we'll do both with rewrite
5594 rules just for practice.
5596 Rewrite rules are written with the @samp{:=} symbol.
5598 @group
5599 @smallexample
5600 1:  1 / cos(x) - sin(x)^2 / cos(x)
5601     .
5603     a r tan(a) := sin(a)/cos(a) RET
5604 @end smallexample
5605 @end group
5607 @noindent
5608 (The ``assignment operator'' @samp{:=} has several uses in Calc.  All
5609 by itself the formula @samp{tan(a) := sin(a)/cos(a)} doesn't do anything,
5610 but when it is given to the @kbd{a r} command, that command interprets
5611 it as a rewrite rule.)
5613 The lefthand side, @samp{tan(a)}, is called the @dfn{pattern} of the
5614 rewrite rule.  Calc searches the formula on the stack for parts that
5615 match the pattern.  Variables in a rewrite pattern are called
5616 @dfn{meta-variables}, and when matching the pattern each meta-variable
5617 can match any sub-formula.  Here, the meta-variable @samp{a} matched
5618 the actual variable @samp{x}.
5620 When the pattern part of a rewrite rule matches a part of the formula,
5621 that part is replaced by the righthand side with all the meta-variables
5622 substituted with the things they matched.  So the result is
5623 @samp{sin(x) / cos(x)}.  Calc's normal algebraic simplifications then
5624 mix this in with the rest of the original formula.
5626 To merge over a common denominator, we can use another simple rule:
5628 @group
5629 @smallexample
5630 1:  (1 - sin(x)^2) / cos(x)
5631     .
5633     a r a/x + b/x := (a+b)/x RET
5634 @end smallexample
5635 @end group
5637 This rule points out several interesting features of rewrite patterns.
5638 First, if a meta-variable appears several times in a pattern, it must
5639 match the same thing everywhere.  This rule detects common denominators
5640 because the same meta-variable @samp{x} is used in both of the
5641 denominators.
5643 Second, meta-variable names are independent from variables in the
5644 target formula.  Notice that the meta-variable @samp{x} here matches
5645 the subformula @samp{cos(x)}; Calc never confuses the two meanings of
5646 @samp{x}.
5648 And third, rewrite patterns know a little bit about the algebraic
5649 properties of formulas.  The pattern called for a sum of two quotients;
5650 Calc was able to match a difference of two quotients by matching
5651 @samp{a = 1}, @samp{b = -sin(x)^2}, and @samp{x = cos(x)}.
5653 @c [fix-ref Algebraic Properties of Rewrite Rules]
5654 We could just as easily have written @samp{a/x - b/x := (a-b)/x} for
5655 the rule.  It would have worked just the same in all cases.  (If we
5656 really wanted the rule to apply only to @samp{+} or only to @samp{-},
5657 we could have used the @code{plain} symbol.  @xref{Algebraic Properties
5658 of Rewrite Rules}, for some examples of this.)
5660 One more rewrite will complete the job.  We want to use the identity
5661 @samp{sin(x)^2 + cos(x)^2 = 1}, but of course we must first rearrange
5662 the identity in a way that matches our formula.  The obvious rule
5663 would be @samp{@w{1 - sin(x)^2} := cos(x)^2}, but a little thought shows
5664 that the rule @samp{sin(x)^2 := 1 - cos(x)^2} will also work.  The
5665 latter rule has a more general pattern so it will work in many other
5666 situations, too.
5668 @group
5669 @smallexample
5670 1:  (1 + cos(x)^2 - 1) / cos(x)           1:  cos(x)
5671     .                                         .
5673     a r sin(x)^2 := 1 - cos(x)^2 RET          a s
5674 @end smallexample
5675 @end group
5677 You may ask, what's the point of using the most general rule if you
5678 have to type it in every time anyway?  The answer is that Calc allows
5679 you to store a rewrite rule in a variable, then give the variable
5680 name in the @kbd{a r} command.  In fact, this is the preferred way to
5681 use rewrites.  For one, if you need a rule once you'll most likely
5682 need it again later.  Also, if the rule doesn't work quite right you
5683 can simply Undo, edit the variable, and run the rule again without
5684 having to retype it.
5686 @group
5687 @smallexample
5688 ' tan(x) := sin(x)/cos(x) RET      s t tsc RET
5689 ' a/x + b/x := (a+b)/x RET         s t merge RET
5690 ' sin(x)^2 := 1 - cos(x)^2 RET     s t sinsqr RET
5692 1:  1 / cos(x) - sin(x) tan(x)     1:  cos(x)
5693     .                                  .
5695     r 1                a r tsc RET  a r merge RET  a r sinsqr RET  a s
5696 @end smallexample
5697 @end group
5699 To edit a variable, type @kbd{s e} and the variable name, use regular
5700 Emacs editing commands as necessary, then type @kbd{M-# M-#} or
5701 @kbd{C-c C-c} to store the edited value back into the variable.
5702 You can also use @w{@kbd{s e}} to create a new variable if you wish.
5704 Notice that the first time you use each rule, Calc puts up a ``compiling''
5705 message briefly.  The pattern matcher converts rules into a special
5706 optimized pattern-matching language rather than using them directly.
5707 This allows @kbd{a r} to apply even rather complicated rules very
5708 efficiently.  If the rule is stored in a variable, Calc compiles it
5709 only once and stores the compiled form along with the variable.  That's
5710 another good reason to store your rules in variables rather than
5711 entering them on the fly.
5713 (@bullet{}) @strong{Exercise 1.}  Type @kbd{m s} to get symbolic
5714 mode, then enter the formula @samp{@w{(2 + sqrt(2))} / @w{(1 + sqrt(2))}}.
5715 Using a rewrite rule, simplify this formula by multiplying both
5716 sides by the conjugate @w{@samp{1 - sqrt(2)}}.  The result will have
5717 to be expanded by the distributive law; do this with another
5718 rewrite.  @xref{Rewrites Answer 1, 1}. (@bullet{})
5720 The @kbd{a r} command can also accept a vector of rewrite rules, or
5721 a variable containing a vector of rules.
5723 @group
5724 @smallexample
5725 1:  [tsc, merge, sinsqr]          1:  [tan(x) := sin(x) / cos(x), ... ]
5726     .                                 .
5728     ' [tsc,merge,sinsqr] RET          =
5730 @end smallexample
5731 @end group
5732 @noindent
5733 @group
5734 @smallexample
5735 1:  1 / cos(x) - sin(x) tan(x)    1:  cos(x)
5736     .                                 .
5738     s t trig RET  r 1                 a r trig RET  a s
5739 @end smallexample
5740 @end group
5742 @c [fix-ref Nested Formulas with Rewrite Rules]
5743 Calc tries all the rules you give against all parts of the formula,
5744 repeating until no further change is possible.  (The exact order in
5745 which things are tried is rather complex, but for simple rules like
5746 the ones we've used here the order doesn't really matter.
5747 @xref{Nested Formulas with Rewrite Rules}.)
5749 Calc actually repeats only up to 100 times, just in case your rule set
5750 has gotten into an infinite loop.  You can give a numeric prefix argument
5751 to @kbd{a r} to specify any limit.  In particular, @kbd{M-1 a r} does
5752 only one rewrite at a time.
5754 @group
5755 @smallexample
5756 1:  1 / cos(x) - sin(x)^2 / cos(x)    1:  (1 - sin(x)^2) / cos(x)
5757     .                                     .
5759     r 1  M-1 a r trig RET                 M-1 a r trig RET
5760 @end smallexample
5761 @end group
5763 You can type @kbd{M-0 a r} if you want no limit at all on the number
5764 of rewrites that occur.
5766 Rewrite rules can also be @dfn{conditional}.  Simply follow the rule
5767 with a @samp{::} symbol and the desired condition.  For example,
5769 @group
5770 @smallexample
5771 1:  exp(2 pi i) + exp(3 pi i) + exp(4 pi i)
5772     .
5774     ' exp(2 pi i) + exp(3 pi i) + exp(4 pi i) RET
5776 @end smallexample
5777 @end group
5778 @noindent
5779 @group
5780 @smallexample
5781 1:  1 + exp(3 pi i) + 1
5782     .
5784     a r exp(k pi i) := 1 :: k % 2 = 0 RET
5785 @end smallexample
5786 @end group
5788 @noindent
5789 (Recall, @samp{k % 2} is the remainder from dividing @samp{k} by 2,
5790 which will be zero only when @samp{k} is an even integer.)
5792 An interesting point is that the variables @samp{pi} and @samp{i}
5793 were matched literally rather than acting as meta-variables.
5794 This is because they are special-constant variables.  The special
5795 constants @samp{e}, @samp{phi}, and so on also match literally.
5796 A common error with rewrite
5797 rules is to write, say, @samp{f(a,b,c,d,e) := g(a+b+c+d+e)}, expecting
5798 to match any @samp{f} with five arguments but in fact matching
5799 only when the fifth argument is literally @samp{e}!@refill
5801 @cindex Fibonacci numbers
5802 @c @starindex
5803 @tindex fib
5804 Rewrite rules provide an interesting way to define your own functions.
5805 Suppose we want to define @samp{fib(n)} to produce the @var{n}th
5806 Fibonacci number.  The first two Fibonacci numbers are each 1;
5807 later numbers are formed by summing the two preceding numbers in
5808 the sequence.  This is easy to express in a set of three rules:
5810 @group
5811 @smallexample
5812 ' [fib(1) := 1, fib(2) := 1, fib(n) := fib(n-1) + fib(n-2)] RET  s t fib
5814 1:  fib(7)               1:  13
5815     .                        .
5817     ' fib(7) RET             a r fib RET
5818 @end smallexample
5819 @end group
5821 One thing that is guaranteed about the order that rewrites are tried
5822 is that, for any given subformula, earlier rules in the rule set will
5823 be tried for that subformula before later ones.  So even though the
5824 first and third rules both match @samp{fib(1)}, we know the first will
5825 be used preferentially.
5827 This rule set has one dangerous bug:  Suppose we apply it to the
5828 formula @samp{fib(x)}?  (Don't actually try this.)  The third rule
5829 will match @samp{fib(x)} and replace it with @w{@samp{fib(x-1) + fib(x-2)}}.
5830 Each of these will then be replaced to get @samp{fib(x-2) + 2 fib(x-3) +
5831 fib(x-4)}, and so on, expanding forever.  What we really want is to apply
5832 the third rule only when @samp{n} is an integer greater than two.  Type
5833 @w{@kbd{s e fib RET}}, then edit the third rule to:
5835 @smallexample
5836 fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2
5837 @end smallexample
5839 @noindent
5840 Now:
5842 @group
5843 @smallexample
5844 1:  fib(6) + fib(x) + fib(0)      1:  8 + fib(x) + fib(0)
5845     .                                 .
5847     ' fib(6)+fib(x)+fib(0) RET        a r fib RET
5848 @end smallexample
5849 @end group
5851 @noindent
5852 We've created a new function, @code{fib}, and a new command,
5853 @w{@kbd{a r fib RET}}, which means ``evaluate all @code{fib} calls in
5854 this formula.''  To make things easier still, we can tell Calc to
5855 apply these rules automatically by storing them in the special
5856 variable @code{EvalRules}.
5858 @group
5859 @smallexample
5860 1:  [fib(1) := ...]    .                1:  [8, 13]
5861     .                                       .
5863     s r fib RET        s t EvalRules RET    ' [fib(6), fib(7)] RET
5864 @end smallexample
5865 @end group
5867 It turns out that this rule set has the problem that it does far
5868 more work than it needs to when @samp{n} is large.  Consider the
5869 first few steps of the computation of @samp{fib(6)}:
5871 @group
5872 @smallexample
5873 fib(6) =
5874 fib(5)              +               fib(4) =
5875 fib(4)     +      fib(3)     +      fib(3)     +      fib(2) =
5876 fib(3) + fib(2) + fib(2) + fib(1) + fib(2) + fib(1) + 1 = ...
5877 @end smallexample
5878 @end group
5880 @noindent
5881 Note that @samp{fib(3)} appears three times here.  Unless Calc's
5882 algebraic simplifier notices the multiple @samp{fib(3)}s and combines
5883 them (and, as it happens, it doesn't), this rule set does lots of
5884 needless recomputation.  To cure the problem, type @code{s e EvalRules}
5885 to edit the rules (or just @kbd{s E}, a shorthand command for editing
5886 @code{EvalRules}) and add another condition:
5888 @smallexample
5889 fib(n) := fib(n-1) + fib(n-2) :: integer(n) :: n > 2 :: remember
5890 @end smallexample
5892 @noindent
5893 If a @samp{:: remember} condition appears anywhere in a rule, then if
5894 that rule succeeds Calc will add another rule that describes that match
5895 to the front of the rule set.  (Remembering works in any rule set, but
5896 for technical reasons it is most effective in @code{EvalRules}.)  For
5897 example, if the rule rewrites @samp{fib(7)} to something that evaluates
5898 to 13, then the rule @samp{fib(7) := 13} will be added to the rule set.
5900 Type @kbd{' fib(8) RET} to compute the eighth Fibonacci number, then
5901 type @kbd{s E} again to see what has happened to the rule set.
5903 With the @code{remember} feature, our rule set can now compute
5904 @samp{fib(@var{n})} in just @var{n} steps.  In the process it builds
5905 up a table of all Fibonacci numbers up to @var{n}.  After we have
5906 computed the result for a particular @var{n}, we can get it back
5907 (and the results for all smaller @var{n}) later in just one step.
5909 All Calc operations will run somewhat slower whenever @code{EvalRules}
5910 contains any rules.  You should type @kbd{s u EvalRules RET} now to
5911 un-store the variable.
5913 (@bullet{}) @strong{Exercise 2.}  Sometimes it is possible to reformulate
5914 a problem to reduce the amount of recursion necessary to solve it.
5915 Create a rule that, in about @var{n} simple steps and without recourse
5916 to the @code{remember} option, replaces @samp{fib(@var{n}, 1, 1)} with
5917 @samp{fib(1, @var{x}, @var{y})} where @var{x} and @var{y} are the
5918 @var{n}th and @var{n+1}st Fibonacci numbers, respectively.  This rule is
5919 rather clunky to use, so add a couple more rules to make the ``user
5920 interface'' the same as for our first version: enter @samp{fib(@var{n})},
5921 get back a plain number.  @xref{Rewrites Answer 2, 2}. (@bullet{})
5923 There are many more things that rewrites can do.  For example, there
5924 are @samp{&&&} and @samp{|||} pattern operators that create ``and''
5925 and ``or'' combinations of rules.  As one really simple example, we
5926 could combine our first two Fibonacci rules thusly:
5928 @example
5929 [fib(1 ||| 2) := 1, fib(n) := ... ]
5930 @end example
5932 @noindent
5933 That means ``@code{fib} of something matching either 1 or 2 rewrites
5934 to 1.''
5936 You can also make meta-variables optional by enclosing them in @code{opt}.
5937 For example, the pattern @samp{a + b x} matches @samp{2 + 3 x} but not
5938 @samp{2 + x} or @samp{3 x} or @samp{x}.  The pattern @samp{opt(a) + opt(b) x}
5939 matches all of these forms, filling in a default of zero for @samp{a}
5940 and one for @samp{b}.
5942 (@bullet{}) @strong{Exercise 3.}  Your friend Joe had @samp{2 + 3 x}
5943 on the stack and tried to use the rule
5944 @samp{opt(a) + opt(b) x := f(a, b, x)}.  What happened?
5945 @xref{Rewrites Answer 3, 3}. (@bullet{})
5947 (@bullet{}) @strong{Exercise 4.}  Starting with a positive integer @cite{a},
5948 divide @cite{a} by two if it is even, otherwise compute @cite{3 a + 1}.
5949 Now repeat this step over and over.  A famous unproved conjecture
5950 is that for any starting @cite{a}, the sequence always eventually
5951 reaches 1.  Given the formula @samp{seq(@var{a}, 0)}, write a set of
5952 rules that convert this into @samp{seq(1, @var{n})} where @var{n}
5953 is the number of steps it took the sequence to reach the value 1.
5954 Now enhance the rules to accept @samp{seq(@var{a})} as a starting
5955 configuration, and to stop with just the number @var{n} by itself.
5956 Now make the result be a vector of values in the sequence, from @var{a}
5957 to 1.  (The formula @samp{@var{x}|@var{y}} appends the vectors @var{x}
5958 and @var{y}.)  For example, rewriting @samp{seq(6)} should yield the
5959 vector @cite{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
5960 @xref{Rewrites Answer 4, 4}. (@bullet{})
5962 (@bullet{}) @strong{Exercise 5.}  Define, using rewrite rules, a function
5963 @samp{nterms(@var{x})} that returns the number of terms in the sum
5964 @var{x}, or 1 if @var{x} is not a sum.  (A @dfn{sum} for our purposes
5965 is one or more non-sum terms separated by @samp{+} or @samp{-} signs,
5966 so that @cite{2 - 3 (x + y) + x y} is a sum of three terms.)
5967 @xref{Rewrites Answer 5, 5}. (@bullet{})
5969 (@bullet{}) @strong{Exercise 6.}  Calc considers the form @cite{0^0}
5970 to be ``indeterminate,'' and leaves it unevaluated (assuming infinite
5971 mode is not enabled).  Some people prefer to define @cite{0^0 = 1},
5972 so that the identity @cite{x^0 = 1} can safely be used for all @cite{x}.
5973 Find a way to make Calc follow this convention.  What happens if you
5974 now type @kbd{m i} to turn on infinite mode?
5975 @xref{Rewrites Answer 6, 6}. (@bullet{})
5977 (@bullet{}) @strong{Exercise 7.}  A Taylor series for a function is an
5978 infinite series that exactly equals the value of that function at
5979 values of @cite{x} near zero.
5981 @ifinfo
5982 @example
5983 cos(x) = 1 - x^2 / 2! + x^4 / 4! - x^6 / 6! + ...
5984 @end example
5985 @end ifinfo
5986 @tex
5987 \turnoffactive \let\rm\goodrm
5988 \beforedisplay
5989 $$ \cos x = 1 - {x^2 \over 2!} + {x^4 \over 4!} - {x^6 \over 6!} + \cdots $$
5990 \afterdisplay
5991 @end tex
5993 The @kbd{a t} command produces a @dfn{truncated Taylor series} which
5994 is obtained by dropping all the terms higher than, say, @cite{x^2}.
5995 Calc represents the truncated Taylor series as a polynomial in @cite{x}.
5996 Mathematicians often write a truncated series using a ``big-O'' notation
5997 that records what was the lowest term that was truncated.
5999 @ifinfo
6000 @example
6001 cos(x) = 1 - x^2 / 2! + O(x^3)
6002 @end example
6003 @end ifinfo
6004 @tex
6005 \turnoffactive \let\rm\goodrm
6006 \beforedisplay
6007 $$ \cos x = 1 - {x^2 \over 2!} + O(x^3) $$
6008 \afterdisplay
6009 @end tex
6011 @noindent
6012 The meaning of @cite{O(x^3)} is ``a quantity which is negligibly small
6013 if @cite{x^3} is considered negligibly small as @cite{x} goes to zero.''
6015 The exercise is to create rewrite rules that simplify sums and products of
6016 power series represented as @samp{@var{polynomial} + O(@var{var}^@var{n})}.
6017 For example, given @samp{1 - x^2 / 2 + O(x^3)} and @samp{x - x^3 / 6 + O(x^4)}
6018 on the stack, we want to be able to type @kbd{*} and get the result
6019 @samp{x - 2:3 x^3 + O(x^4)}.  Don't worry if the terms of the sum are
6020 rearranged or if @kbd{a s} needs to be typed after rewriting.  (This one
6021 is rather tricky; the solution at the end of this chapter uses 6 rewrite
6022 rules.  Hint:  The @samp{constant(x)} condition tests whether @samp{x} is
6023 a number.)  @xref{Rewrites Answer 7, 7}. (@bullet{})
6025 @c [fix-ref Rewrite Rules]
6026 @xref{Rewrite Rules}, for the whole story on rewrite rules.
6028 @node Programming Tutorial, Answers to Exercises, Algebra Tutorial, Tutorial
6029 @section Programming Tutorial
6031 @noindent
6032 The Calculator is written entirely in Emacs Lisp, a highly extensible
6033 language.  If you know Lisp, you can program the Calculator to do
6034 anything you like.  Rewrite rules also work as a powerful programming
6035 system.  But Lisp and rewrite rules take a while to master, and often
6036 all you want to do is define a new function or repeat a command a few
6037 times.  Calc has features that allow you to do these things easily.
6039 (Note that the programming commands relating to user-defined keys
6040 are not yet supported under Lucid Emacs 19.)
6042 One very limited form of programming is defining your own functions.
6043 Calc's @kbd{Z F} command allows you to define a function name and
6044 key sequence to correspond to any formula.  Programming commands use
6045 the shift-@kbd{Z} prefix; the user commands they create use the lower
6046 case @kbd{z} prefix.
6048 @group
6049 @smallexample
6050 1:  1 + x + x^2 / 2 + x^3 / 6         1:  1 + x + x^2 / 2 + x^3 / 6
6051     .                                     .
6053     ' 1 + x + x^2/2! + x^3/3! RET         Z F e myexp RET RET RET y
6054 @end smallexample
6055 @end group
6057 This polynomial is a Taylor series approximation to @samp{exp(x)}.
6058 The @kbd{Z F} command asks a number of questions.  The above answers
6059 say that the key sequence for our function should be @kbd{z e}; the
6060 @kbd{M-x} equivalent should be @code{calc-myexp}; the name of the
6061 function in algebraic formulas should also be @code{myexp}; the
6062 default argument list @samp{(x)} is acceptable; and finally @kbd{y}
6063 answers the question ``leave it in symbolic form for non-constant
6064 arguments?''
6066 @group
6067 @smallexample
6068 1:  1.3495     2:  1.3495     3:  1.3495
6069     .          1:  1.34986    2:  1.34986
6070                    .          1:  myexp(a + 1)
6071                                   .
6073     .3 z e         .3 E           ' a+1 RET z e
6074 @end smallexample
6075 @end group
6077 @noindent
6078 First we call our new @code{exp} approximation with 0.3 as an
6079 argument, and compare it with the true @code{exp} function.  Then
6080 we note that, as requested, if we try to give @kbd{z e} an
6081 argument that isn't a plain number, it leaves the @code{myexp}
6082 function call in symbolic form.  If we had answered @kbd{n} to the
6083 final question, @samp{myexp(a + 1)} would have evaluated by plugging
6084 in @samp{a + 1} for @samp{x} in the defining formula.
6086 @cindex Sine integral Si(x)
6087 @c @starindex
6088 @tindex Si
6089 (@bullet{}) @strong{Exercise 1.}  The ``sine integral'' function
6090 @c{${\rm Si}(x)$}
6091 @cite{Si(x)} is defined as the integral of @samp{sin(t)/t} for
6092 @cite{t = 0} to @cite{x} in radians.  (It was invented because this
6093 integral has no solution in terms of basic functions; if you give it
6094 to Calc's @kbd{a i} command, it will ponder it for a long time and then
6095 give up.)  We can use the numerical integration command, however,
6096 which in algebraic notation is written like @samp{ninteg(f(t), t, 0, x)}
6097 with any integrand @samp{f(t)}.  Define a @kbd{z s} command and
6098 @code{Si} function that implement this.  You will need to edit the
6099 default argument list a bit.  As a test, @samp{Si(1)} should return
6100 0.946083.  (Hint:  @code{ninteg} will run a lot faster if you reduce
6101 the precision to, say, six digits beforehand.)
6102 @xref{Programming Answer 1, 1}. (@bullet{})
6104 The simplest way to do real ``programming'' of Emacs is to define a
6105 @dfn{keyboard macro}.  A keyboard macro is simply a sequence of
6106 keystrokes which Emacs has stored away and can play back on demand.
6107 For example, if you find yourself typing @kbd{H a S x @key{RET}} often,
6108 you may wish to program a keyboard macro to type this for you.
6110 @group
6111 @smallexample
6112 1:  y = sqrt(x)          1:  x = y^2
6113     .                        .
6115     ' y=sqrt(x) RET       C-x ( H a S x RET C-x )
6117 1:  y = cos(x)           1:  x = s1 arccos(y) + 2 pi n1
6118     .                        .
6120     ' y=cos(x) RET           X
6121 @end smallexample
6122 @end group
6124 @noindent
6125 When you type @kbd{C-x (}, Emacs begins recording.  But it is also
6126 still ready to execute your keystrokes, so you're really ``training''
6127 Emacs by walking it through the procedure once.  When you type
6128 @w{@kbd{C-x )}}, the macro is recorded.  You can now type @kbd{X} to
6129 re-execute the same keystrokes.
6131 You can give a name to your macro by typing @kbd{Z K}.
6133 @group
6134 @smallexample
6135 1:  .              1:  y = x^4         1:  x = s2 sqrt(s1 sqrt(y))
6136                        .                   .
6138   Z K x RET            ' y=x^4 RET         z x
6139 @end smallexample
6140 @end group
6142 @noindent
6143 Notice that we use shift-@kbd{Z} to define the command, and lower-case
6144 @kbd{z} to call it up.
6146 Keyboard macros can call other macros.
6148 @group
6149 @smallexample
6150 1:  abs(x)        1:  x = s1 y                1:  2 / x    1:  x = 2 / y
6151     .                 .                           .            .
6153  ' abs(x) RET   C-x ( ' y RET a = z x C-x )    ' 2/x RET       X
6154 @end smallexample
6155 @end group
6157 (@bullet{}) @strong{Exercise 2.}  Define a keyboard macro to negate
6158 the item in level 3 of the stack, without disturbing the rest of
6159 the stack.  @xref{Programming Answer 2, 2}. (@bullet{})
6161 (@bullet{}) @strong{Exercise 3.}  Define keyboard macros to compute
6162 the following functions:
6164 @enumerate
6165 @item
6166 Compute @c{$\displaystyle{\sin x \over x}$}
6167 @cite{sin(x) / x}, where @cite{x} is the number on the
6168 top of the stack.
6170 @item
6171 Compute the base-@cite{b} logarithm, just like the @kbd{B} key except
6172 the arguments are taken in the opposite order.
6174 @item
6175 Produce a vector of integers from 1 to the integer on the top of
6176 the stack.
6177 @end enumerate
6178 @noindent
6179 @xref{Programming Answer 3, 3}. (@bullet{})
6181 (@bullet{}) @strong{Exercise 4.}  Define a keyboard macro to compute
6182 the average (mean) value of a list of numbers.
6183 @xref{Programming Answer 4, 4}. (@bullet{})
6185 In many programs, some of the steps must execute several times.
6186 Calc has @dfn{looping} commands that allow this.  Loops are useful
6187 inside keyboard macros, but actually work at any time.
6189 @group
6190 @smallexample
6191 1:  x^6          2:  x^6        1: 360 x^2
6192     .            1:  4             .
6193                      .
6195   ' x^6 RET          4         Z < a d x RET Z >
6196 @end smallexample
6197 @end group
6199 @noindent
6200 Here we have computed the fourth derivative of @cite{x^6} by
6201 enclosing a derivative command in a ``repeat loop'' structure.
6202 This structure pops a repeat count from the stack, then
6203 executes the body of the loop that many times.
6205 If you make a mistake while entering the body of the loop,
6206 type @w{@kbd{Z C-g}} to cancel the loop command.
6208 @cindex Fibonacci numbers
6209 Here's another example:
6211 @group
6212 @smallexample
6213 3:  1               2:  10946
6214 2:  1               1:  17711
6215 1:  20                  .
6216     .
6218 1 RET RET 20       Z < TAB C-j + Z >
6219 @end smallexample
6220 @end group
6222 @noindent
6223 The numbers in levels 2 and 1 should be the 21st and 22nd Fibonacci
6224 numbers, respectively.  (To see what's going on, try a few repetitions
6225 of the loop body by hand; @kbd{C-j}, also on the Line-Feed or @key{LFD}
6226 key if you have one, makes a copy of the number in level 2.)
6228 @cindex Golden ratio
6229 @cindex Phi, golden ratio
6230 A fascinating property of the Fibonacci numbers is that the @cite{n}th
6231 Fibonacci number can be found directly by computing @c{$\phi^n / \sqrt{5}$}
6232 @cite{phi^n / sqrt(5)}
6233 and then rounding to the nearest integer, where @c{$\phi$ (``phi'')}
6234 @cite{phi}, the
6235 ``golden ratio,'' is @c{$(1 + \sqrt{5}) / 2$}
6236 @cite{(1 + sqrt(5)) / 2}.  (For convenience, this constant is available
6237 from the @code{phi} variable, or the @kbd{I H P} command.)
6239 @group
6240 @smallexample
6241 1:  1.61803         1:  24476.0000409    1:  10945.9999817    1:  10946
6242     .                   .                    .                    .
6244     I H P               21 ^                 5 Q /                R
6245 @end smallexample
6246 @end group
6248 @cindex Continued fractions
6249 (@bullet{}) @strong{Exercise 5.}  The @dfn{continued fraction}
6250 representation of @c{$\phi$}
6251 @cite{phi} is @c{$1 + 1/(1 + 1/(1 + 1/( \ldots )))$}
6252 @cite{1 + 1/(1 + 1/(1 + 1/( ...@: )))}.
6253 We can compute an approximate value by carrying this however far
6254 and then replacing the innermost @c{$1/( \ldots )$}
6255 @cite{1/( ...@: )} by 1.  Approximate
6256 @c{$\phi$}
6257 @cite{phi} using a twenty-term continued fraction.
6258 @xref{Programming Answer 5, 5}. (@bullet{})
6260 (@bullet{}) @strong{Exercise 6.}  Linear recurrences like the one for
6261 Fibonacci numbers can be expressed in terms of matrices.  Given a
6262 vector @w{@cite{[a, b]}} determine a matrix which, when multiplied by this
6263 vector, produces the vector @cite{[b, c]}, where @cite{a}, @cite{b} and
6264 @cite{c} are three successive Fibonacci numbers.  Now write a program
6265 that, given an integer @cite{n}, computes the @cite{n}th Fibonacci number
6266 using matrix arithmetic.  @xref{Programming Answer 6, 6}. (@bullet{})
6268 @cindex Harmonic numbers
6269 A more sophisticated kind of loop is the @dfn{for} loop.  Suppose
6270 we wish to compute the 20th ``harmonic'' number, which is equal to
6271 the sum of the reciprocals of the integers from 1 to 20.
6273 @group
6274 @smallexample
6275 3:  0               1:  3.597739
6276 2:  1                   .
6277 1:  20
6278     .
6280 0 RET 1 RET 20         Z ( & + 1 Z )
6281 @end smallexample
6282 @end group
6284 @noindent
6285 The ``for'' loop pops two numbers, the lower and upper limits, then
6286 repeats the body of the loop as an internal counter increases from
6287 the lower limit to the upper one.  Just before executing the loop
6288 body, it pushes the current loop counter.  When the loop body
6289 finishes, it pops the ``step,'' i.e., the amount by which to
6290 increment the loop counter.  As you can see, our loop always
6291 uses a step of one.
6293 This harmonic number function uses the stack to hold the running
6294 total as well as for the various loop housekeeping functions.  If
6295 you find this disorienting, you can sum in a variable instead:
6297 @group
6298 @smallexample
6299 1:  0         2:  1                  .            1:  3.597739
6300     .         1:  20                                  .
6301                   .
6303     0 t 7       1 RET 20      Z ( & s + 7 1 Z )       r 7
6304 @end smallexample
6305 @end group
6307 @noindent
6308 The @kbd{s +} command adds the top-of-stack into the value in a
6309 variable (and removes that value from the stack).
6311 It's worth noting that many jobs that call for a ``for'' loop can
6312 also be done more easily by Calc's high-level operations.  Two
6313 other ways to compute harmonic numbers are to use vector mapping
6314 and reduction (@kbd{v x 20}, then @w{@kbd{V M &}}, then @kbd{V R +}),
6315 or to use the summation command @kbd{a +}.  Both of these are
6316 probably easier than using loops.  However, there are some
6317 situations where loops really are the way to go:
6319 (@bullet{}) @strong{Exercise 7.}  Use a ``for'' loop to find the first
6320 harmonic number which is greater than 4.0.
6321 @xref{Programming Answer 7, 7}. (@bullet{})
6323 Of course, if we're going to be using variables in our programs,
6324 we have to worry about the programs clobbering values that the
6325 caller was keeping in those same variables.  This is easy to
6326 fix, though:
6328 @group
6329 @smallexample
6330     .        1:  0.6667       1:  0.6667     3:  0.6667
6331                  .                .          2:  3.597739
6332                                              1:  0.6667
6333                                                  .
6335    Z `    p 4 RET 2 RET 3 /   s 7 s s a RET    Z '  r 7 s r a RET
6336 @end smallexample
6337 @end group
6339 @noindent
6340 When we type @kbd{Z `} (that's a back-quote character), Calc saves
6341 its mode settings and the contents of the ten ``quick variables''
6342 for later reference.  When we type @kbd{Z '} (that's an apostrophe
6343 now), Calc restores those saved values.  Thus the @kbd{p 4} and
6344 @kbd{s 7} commands have no effect outside this sequence.  Wrapping
6345 this around the body of a keyboard macro ensures that it doesn't
6346 interfere with what the user of the macro was doing.  Notice that
6347 the contents of the stack, and the values of named variables,
6348 survive past the @kbd{Z '} command.
6350 @cindex Bernoulli numbers, approximate
6351 The @dfn{Bernoulli numbers} are a sequence with the interesting
6352 property that all of the odd Bernoulli numbers are zero, and the
6353 even ones, while difficult to compute, can be roughly approximated
6354 by the formula @c{$\displaystyle{2 n! \over (2 \pi)^n}$}
6355 @cite{2 n!@: / (2 pi)^n}.  Let's write a keyboard
6356 macro to compute (approximate) Bernoulli numbers.  (Calc has a
6357 command, @kbd{k b}, to compute exact Bernoulli numbers, but
6358 this command is very slow for large @cite{n} since the higher
6359 Bernoulli numbers are very large fractions.)
6361 @group
6362 @smallexample
6363 1:  10               1:  0.0756823
6364     .                    .
6366     10     C-x ( RET 2 % Z [ DEL 0 Z : ' 2 $! / (2 pi)^$ RET = Z ] C-x )
6367 @end smallexample
6368 @end group
6370 @noindent
6371 You can read @kbd{Z [} as ``then,'' @kbd{Z :} as ``else,'' and
6372 @kbd{Z ]} as ``end-if.''  There is no need for an explicit ``if''
6373 command.  For the purposes of @w{@kbd{Z [}}, the condition is ``true''
6374 if the value it pops from the stack is a nonzero number, or ``false''
6375 if it pops zero or something that is not a number (like a formula).
6376 Here we take our integer argument modulo 2; this will be nonzero
6377 if we're asking for an odd Bernoulli number.
6379 The actual tenth Bernoulli number is @cite{5/66}.
6381 @group
6382 @smallexample
6383 3:  0.0756823    1:  0          1:  0.25305    1:  0          1:  1.16659
6384 2:  5:66             .              .              .              .
6385 1:  0.0757575
6386     .
6388 10 k b RET c f   M-0 DEL 11 X   DEL 12 X       DEL 13 X       DEL 14 X
6389 @end smallexample
6390 @end group
6392 Just to exercise loops a bit more, let's compute a table of even
6393 Bernoulli numbers.
6395 @group
6396 @smallexample
6397 3:  []             1:  [0.10132, 0.03079, 0.02340, 0.033197, ...]
6398 2:  2                  .
6399 1:  30
6400     .
6402  [ ] 2 RET 30          Z ( X | 2 Z )
6403 @end smallexample
6404 @end group
6406 @noindent
6407 The vertical-bar @kbd{|} is the vector-concatenation command.  When
6408 we execute it, the list we are building will be in stack level 2
6409 (initially this is an empty list), and the next Bernoulli number
6410 will be in level 1.  The effect is to append the Bernoulli number
6411 onto the end of the list.  (To create a table of exact fractional
6412 Bernoulli numbers, just replace @kbd{X} with @kbd{k b} in the above
6413 sequence of keystrokes.)
6415 With loops and conditionals, you can program essentially anything
6416 in Calc.  One other command that makes looping easier is @kbd{Z /},
6417 which takes a condition from the stack and breaks out of the enclosing
6418 loop if the condition is true (non-zero).  You can use this to make
6419 ``while'' and ``until'' style loops.
6421 If you make a mistake when entering a keyboard macro, you can edit
6422 it using @kbd{Z E}.  First, you must attach it to a key with @kbd{Z K}.
6423 One technique is to enter a throwaway dummy definition for the macro,
6424 then enter the real one in the edit command.
6426 @group
6427 @smallexample
6428 1:  3                   1:  3           Keyboard Macro Editor.
6429     .                       .           Original keys: 1 RET 2 +
6431                                         type "1\r"
6432                                         type "2"
6433                                         calc-plus
6435 C-x ( 1 RET 2 + C-x )    Z K h RET      Z E h
6436 @end smallexample
6437 @end group
6439 @noindent
6440 This shows the screen display assuming you have the @file{macedit}
6441 keyboard macro editing package installed, which is usually the case
6442 since a copy of @file{macedit} comes bundled with Calc.
6444 A keyboard macro is stored as a pure keystroke sequence.  The
6445 @file{macedit} package (invoked by @kbd{Z E}) scans along the
6446 macro and tries to decode it back into human-readable steps.
6447 If a key or keys are simply shorthand for some command with a
6448 @kbd{M-x} name, that name is shown.  Anything that doesn't correspond
6449 to a @kbd{M-x} command is written as a @samp{type} command.
6451 Let's edit in a new definition, for computing harmonic numbers.
6452 First, erase the three lines of the old definition.  Then, type
6453 in the new definition (or use Emacs @kbd{M-w} and @kbd{C-y} commands
6454 to copy it from this page of the Info file; you can skip typing
6455 the comments that begin with @samp{#}).
6457 @smallexample
6458 calc-kbd-push         # Save local values (Z `)
6459 type "0"              # Push a zero
6460 calc-store-into       # Store it in variable 1
6461 type "1"
6462 type "1"              # Initial value for loop
6463 calc-roll-down        # This is the TAB key; swap initial & final
6464 calc-kbd-for          # Begin "for" loop...
6465 calc-inv              #   Take reciprocal
6466 calc-store-plus       #   Add to accumulator
6467 type "1"
6468 type "1"              #   Loop step is 1
6469 calc-kbd-end-for      # End "for" loop
6470 calc-recall           # Now recall final accumulated value
6471 type "1"
6472 calc-kbd-pop          # Restore values (Z ')
6473 @end smallexample
6475 @noindent
6476 Press @kbd{M-# M-#} to finish editing and return to the Calculator.
6478 @group
6479 @smallexample
6480 1:  20         1:  3.597739
6481     .              .
6483     20             z h
6484 @end smallexample
6485 @end group
6487 If you don't know how to write a particular command in @file{macedit}
6488 format, you can always write it as keystrokes in a @code{type} command.
6489 There is also a @code{keys} command which interprets the rest of the
6490 line as standard Emacs keystroke names.  In fact, @file{macedit} defines
6491 a handy @code{read-kbd-macro} command which reads the current region
6492 of the current buffer as a sequence of keystroke names, and defines that
6493 sequence on the @kbd{X} (and @kbd{C-x e}) key.  Because this is so
6494 useful, Calc puts this command on the @kbd{M-# m} key.  Try reading in
6495 this macro in the following form:  Press @kbd{C-@@} (or @kbd{C-SPC}) at
6496 one end of the text below, then type @kbd{M-# m} at the other.
6498 @group
6499 @example
6500 Z ` 0 t 1
6501     1 TAB
6502     Z (  & s + 1  1 Z )
6503     r 1
6504 Z '
6505 @end example
6506 @end group
6508 (@bullet{}) @strong{Exercise 8.}  A general algorithm for solving
6509 equations numerically is @dfn{Newton's Method}.  Given the equation
6510 @cite{f(x) = 0} for any function @cite{f}, and an initial guess
6511 @cite{x_0} which is reasonably close to the desired solution, apply
6512 this formula over and over:
6514 @ifinfo
6515 @example
6516 new_x = x - f(x)/f'(x)
6517 @end example
6518 @end ifinfo
6519 @tex
6520 \beforedisplay
6521 $$ x_{\goodrm new} = x - {f(x) \over f'(x)} $$
6522 \afterdisplay
6523 @end tex
6525 @noindent
6526 where @cite{f'(x)} is the derivative of @cite{f}.  The @cite{x}
6527 values will quickly converge to a solution, i.e., eventually
6528 @c{$x_{\rm new}$}
6529 @cite{new_x} and @cite{x} will be equal to within the limits
6530 of the current precision.  Write a program which takes a formula
6531 involving the variable @cite{x}, and an initial guess @cite{x_0},
6532 on the stack, and produces a value of @cite{x} for which the formula
6533 is zero.  Use it to find a solution of @c{$\sin(\cos x) = 0.5$}
6534 @cite{sin(cos(x)) = 0.5}
6535 near @cite{x = 4.5}.  (Use angles measured in radians.)  Note that
6536 the built-in @w{@kbd{a R}} (@code{calc-find-root}) command uses Newton's
6537 method when it is able.  @xref{Programming Answer 8, 8}. (@bullet{})
6539 @cindex Digamma function
6540 @cindex Gamma constant, Euler's
6541 @cindex Euler's gamma constant
6542 (@bullet{}) @strong{Exercise 9.}  The @dfn{digamma} function @c{$\psi(z)$ (``psi'')}
6543 @cite{psi(z)}
6544 is defined as the derivative of @c{$\ln \Gamma(z)$}
6545 @cite{ln(gamma(z))}.  For large
6546 values of @cite{z}, it can be approximated by the infinite sum
6548 @ifinfo
6549 @example
6550 psi(z) ~= ln(z) - 1/2z - sum(bern(2 n) / 2 n z^(2 n), n, 1, inf)
6551 @end example
6552 @end ifinfo
6553 @tex
6554 \let\rm\goodrm
6555 \beforedisplay
6556 $$ \psi(z) \approx \ln z - {1\over2z} -
6557    \sum_{n=1}^\infty {\code{bern}(2 n) \over 2 n z^{2n}}
6559 \afterdisplay
6560 @end tex
6562 @noindent
6563 where @c{$\sum$}
6564 @cite{sum} represents the sum over @cite{n} from 1 to infinity
6565 (or to some limit high enough to give the desired accuracy), and
6566 the @code{bern} function produces (exact) Bernoulli numbers.
6567 While this sum is not guaranteed to converge, in practice it is safe.
6568 An interesting mathematical constant is Euler's gamma, which is equal
6569 to about 0.5772.  One way to compute it is by the formula,
6570 @c{$\gamma = -\psi(1)$}
6571 @cite{gamma = -psi(1)}.  Unfortunately, 1 isn't a large enough argument
6572 for the above formula to work (5 is a much safer value for @cite{z}).
6573 Fortunately, we can compute @c{$\psi(1)$}
6574 @cite{psi(1)} from @c{$\psi(5)$}
6575 @cite{psi(5)} using
6576 the recurrence @c{$\psi(z+1) = \psi(z) + {1 \over z}$}
6577 @cite{psi(z+1) = psi(z) + 1/z}.  Your task:  Develop
6578 a program to compute @c{$\psi(z)$}
6579 @cite{psi(z)}; it should ``pump up'' @cite{z}
6580 if necessary to be greater than 5, then use the above summation
6581 formula.  Use looping commands to compute the sum.  Use your function
6582 to compute @c{$\gamma$}
6583 @cite{gamma} to twelve decimal places.  (Calc has a built-in command
6584 for Euler's constant, @kbd{I P}, which you can use to check your answer.)
6585 @xref{Programming Answer 9, 9}. (@bullet{})
6587 @cindex Polynomial, list of coefficients
6588 (@bullet{}) @strong{Exercise 10.}  Given a polynomial in @cite{x} and
6589 a number @cite{m} on the stack, where the polynomial is of degree
6590 @cite{m} or less (i.e., does not have any terms higher than @cite{x^m}),
6591 write a program to convert the polynomial into a list-of-coefficients
6592 notation.  For example, @cite{5 x^4 + (x + 1)^2} with @cite{m = 6}
6593 should produce the list @cite{[1, 2, 1, 0, 5, 0, 0]}.  Also develop
6594 a way to convert from this form back to the standard algebraic form.
6595 @xref{Programming Answer 10, 10}. (@bullet{})
6597 @cindex Recursion
6598 (@bullet{}) @strong{Exercise 11.}  The @dfn{Stirling numbers of the
6599 first kind} are defined by the recurrences,
6601 @ifinfo
6602 @example
6603 s(n,n) = 1   for n >= 0,
6604 s(n,0) = 0   for n > 0,
6605 s(n+1,m) = s(n,m-1) - n s(n,m)   for n >= m >= 1.
6606 @end example
6607 @end ifinfo
6608 @tex
6609 \turnoffactive
6610 \beforedisplay
6611 $$ \eqalign{ s(n,n)   &= 1 \qquad \hbox{for } n \ge 0,  \cr
6612              s(n,0)   &= 0 \qquad \hbox{for } n > 0, \cr
6613              s(n+1,m) &= s(n,m-1) - n \, s(n,m) \qquad
6614                           \hbox{for } n \ge m \ge 1.}
6616 \afterdisplay
6617 \vskip5pt
6618 (These numbers are also sometimes written $\displaystyle{n \brack m}$.)
6619 @end tex
6621 This can be implemented using a @dfn{recursive} program in Calc; the
6622 program must invoke itself in order to calculate the two righthand
6623 terms in the general formula.  Since it always invokes itself with
6624 ``simpler'' arguments, it's easy to see that it must eventually finish
6625 the computation.  Recursion is a little difficult with Emacs keyboard
6626 macros since the macro is executed before its definition is complete.
6627 So here's the recommended strategy:  Create a ``dummy macro'' and assign
6628 it to a key with, e.g., @kbd{Z K s}.  Now enter the true definition,
6629 using the @kbd{z s} command to call itself recursively, then assign it
6630 to the same key with @kbd{Z K s}.  Now the @kbd{z s} command will run
6631 the complete recursive program.  (Another way is to use @w{@kbd{Z E}}
6632 or @kbd{M-# m} (@code{read-kbd-macro}) to read the whole macro at once,
6633 thus avoiding the ``training'' phase.)  The task:  Write a program
6634 that computes Stirling numbers of the first kind, given @cite{n} and
6635 @cite{m} on the stack.  Test it with @emph{small} inputs like
6636 @cite{s(4,2)}.  (There is a built-in command for Stirling numbers,
6637 @kbd{k s}, which you can use to check your answers.)
6638 @xref{Programming Answer 11, 11}. (@bullet{})
6640 The programming commands we've seen in this part of the tutorial
6641 are low-level, general-purpose operations.  Often you will find
6642 that a higher-level function, such as vector mapping or rewrite
6643 rules, will do the job much more easily than a detailed, step-by-step
6644 program can:
6646 (@bullet{}) @strong{Exercise 12.}  Write another program for
6647 computing Stirling numbers of the first kind, this time using
6648 rewrite rules.  Once again, @cite{n} and @cite{m} should be taken
6649 from the stack.  @xref{Programming Answer 12, 12}. (@bullet{})
6651 @example
6653 @end example
6654 This ends the tutorial section of the Calc manual.  Now you know enough
6655 about Calc to use it effectively for many kinds of calculations.  But
6656 Calc has many features that were not even touched upon in this tutorial.
6657 @c [not-split]
6658 The rest of this manual tells the whole story.
6659 @c [when-split]
6660 @c Volume II of this manual, the @dfn{Calc Reference}, tells the whole story.
6662 @page
6663 @node Answers to Exercises, , Programming Tutorial, Tutorial
6664 @section Answers to Exercises
6666 @noindent
6667 This section includes answers to all the exercises in the Calc tutorial.
6669 @menu
6670 * RPN Answer 1::           1 RET 2 RET 3 RET 4 + * -
6671 * RPN Answer 2::           2*4 + 7*9.5 + 5/4
6672 * RPN Answer 3::           Operating on levels 2 and 3
6673 * RPN Answer 4::           Joe's complex problems
6674 * Algebraic Answer 1::     Simulating Q command
6675 * Algebraic Answer 2::     Joe's algebraic woes
6676 * Algebraic Answer 3::     1 / 0
6677 * Modes Answer 1::         3#0.1 = 3#0.0222222?
6678 * Modes Answer 2::         16#f.e8fe15
6679 * Modes Answer 3::         Joe's rounding bug
6680 * Modes Answer 4::         Why floating point?
6681 * Arithmetic Answer 1::    Why the \ command?
6682 * Arithmetic Answer 2::    Tripping up the B command
6683 * Vector Answer 1::        Normalizing a vector
6684 * Vector Answer 2::        Average position
6685 * Matrix Answer 1::        Row and column sums
6686 * Matrix Answer 2::        Symbolic system of equations
6687 * Matrix Answer 3::        Over-determined system
6688 * List Answer 1::          Powers of two
6689 * List Answer 2::          Least-squares fit with matrices
6690 * List Answer 3::          Geometric mean
6691 * List Answer 4::          Divisor function
6692 * List Answer 5::          Duplicate factors
6693 * List Answer 6::          Triangular list
6694 * List Answer 7::          Another triangular list
6695 * List Answer 8::          Maximum of Bessel function
6696 * List Answer 9::          Integers the hard way
6697 * List Answer 10::         All elements equal
6698 * List Answer 11::         Estimating pi with darts
6699 * List Answer 12::         Estimating pi with matchsticks
6700 * List Answer 13::         Hash codes
6701 * List Answer 14::         Random walk
6702 * Types Answer 1::         Square root of pi times rational
6703 * Types Answer 2::         Infinities
6704 * Types Answer 3::         What can "nan" be?
6705 * Types Answer 4::         Abbey Road
6706 * Types Answer 5::         Friday the 13th
6707 * Types Answer 6::         Leap years
6708 * Types Answer 7::         Erroneous donut
6709 * Types Answer 8::         Dividing intervals
6710 * Types Answer 9::         Squaring intervals
6711 * Types Answer 10::        Fermat's primality test
6712 * Types Answer 11::        pi * 10^7 seconds
6713 * Types Answer 12::        Abbey Road on CD
6714 * Types Answer 13::        Not quite pi * 10^7 seconds
6715 * Types Answer 14::        Supercomputers and c
6716 * Types Answer 15::        Sam the Slug
6717 * Algebra Answer 1::       Squares and square roots
6718 * Algebra Answer 2::       Building polynomial from roots
6719 * Algebra Answer 3::       Integral of x sin(pi x)
6720 * Algebra Answer 4::       Simpson's rule
6721 * Rewrites Answer 1::      Multiplying by conjugate
6722 * Rewrites Answer 2::      Alternative fib rule
6723 * Rewrites Answer 3::      Rewriting opt(a) + opt(b) x
6724 * Rewrites Answer 4::      Sequence of integers
6725 * Rewrites Answer 5::      Number of terms in sum
6726 * Rewrites Answer 6::      Defining 0^0 = 1
6727 * Rewrites Answer 7::      Truncated Taylor series
6728 * Programming Answer 1::   Fresnel's C(x)
6729 * Programming Answer 2::   Negate third stack element
6730 * Programming Answer 3::   Compute sin(x) / x, etc.
6731 * Programming Answer 4::   Average value of a list
6732 * Programming Answer 5::   Continued fraction phi
6733 * Programming Answer 6::   Matrix Fibonacci numbers
6734 * Programming Answer 7::   Harmonic number greater than 4
6735 * Programming Answer 8::   Newton's method
6736 * Programming Answer 9::   Digamma function
6737 * Programming Answer 10::  Unpacking a polynomial
6738 * Programming Answer 11::  Recursive Stirling numbers
6739 * Programming Answer 12::  Stirling numbers with rewrites
6740 @end menu
6742 @c The following kludgery prevents the individual answers from
6743 @c being entered on the table of contents.
6744 @tex
6745 \global\let\oldwrite=\write
6746 \gdef\skipwrite#1#2{\let\write=\oldwrite}
6747 \global\let\oldchapternofonts=\chapternofonts
6748 \gdef\chapternofonts{\let\write=\skipwrite\oldchapternofonts}
6749 @end tex
6751 @node RPN Answer 1, RPN Answer 2, Answers to Exercises, Answers to Exercises
6752 @subsection RPN Tutorial Exercise 1
6754 @noindent
6755 @kbd{1 @key{RET} 2 @key{RET} 3 @key{RET} 4 + * -}
6757 The result is @c{$1 - (2 \times (3 + 4)) = -13$}
6758 @cite{1 - (2 * (3 + 4)) = -13}.
6760 @node RPN Answer 2, RPN Answer 3, RPN Answer 1, Answers to Exercises
6761 @subsection RPN Tutorial Exercise 2
6763 @noindent
6764 @c{$2\times4 + 7\times9.5 + {5\over4} = 75.75$}
6765 @cite{2*4 + 7*9.5 + 5/4 = 75.75}
6767 After computing the intermediate term @c{$2\times4 = 8$}
6768 @cite{2*4 = 8}, you can leave
6769 that result on the stack while you compute the second term.  With
6770 both of these results waiting on the stack you can then compute the
6771 final term, then press @kbd{+ +} to add everything up.
6773 @group
6774 @smallexample
6775 2:  2          1:  8          3:  8          2:  8
6776 1:  4              .          2:  7          1:  66.5
6777     .                         1:  9.5            .
6778                                   .
6780   2 RET 4          *          7 RET 9.5          *
6782 @end smallexample
6783 @end group
6784 @noindent
6785 @group
6786 @smallexample
6787 4:  8          3:  8          2:  8          1:  75.75
6788 3:  66.5       2:  66.5       1:  67.75          .
6789 2:  5          1:  1.25           .
6790 1:  4              .
6791     .
6793   5 RET 4          /              +              +
6794 @end smallexample
6795 @end group
6797 Alternatively, you could add the first two terms before going on
6798 with the third term.
6800 @group
6801 @smallexample
6802 2:  8          1:  74.5       3:  74.5       2:  74.5       1:  75.75
6803 1:  66.5           .          2:  5          1:  1.25           .
6804     .                         1:  4              .
6805                                   .
6807    ...             +            5 RET 4          /              +
6808 @end smallexample
6809 @end group
6811 On an old-style RPN calculator this second method would have the
6812 advantage of using only three stack levels.  But since Calc's stack
6813 can grow arbitrarily large this isn't really an issue.  Which method
6814 you choose is purely a matter of taste.
6816 @node RPN Answer 3, RPN Answer 4, RPN Answer 2, Answers to Exercises
6817 @subsection RPN Tutorial Exercise 3
6819 @noindent
6820 The @key{TAB} key provides a way to operate on the number in level 2.
6822 @group
6823 @smallexample
6824 3:  10         3:  10         4:  10         3:  10         3:  10
6825 2:  20         2:  30         3:  30         2:  30         2:  21
6826 1:  30         1:  20         2:  20         1:  21         1:  30
6827     .              .          1:  1              .              .
6828                                   .
6830                   TAB             1              +             TAB
6831 @end smallexample
6832 @end group
6834 Similarly, @key{M-TAB} gives you access to the number in level 3.
6836 @group
6837 @smallexample
6838 3:  10         3:  21         3:  21         3:  30         3:  11
6839 2:  21         2:  30         2:  30         2:  11         2:  21
6840 1:  30         1:  10         1:  11         1:  21         1:  30
6841     .              .              .              .              .
6843                   M-TAB           1 +           M-TAB          M-TAB
6844 @end smallexample
6845 @end group
6847 @node RPN Answer 4, Algebraic Answer 1, RPN Answer 3, Answers to Exercises
6848 @subsection RPN Tutorial Exercise 4
6850 @noindent
6851 Either @kbd{( 2 , 3 )} or @kbd{( 2 @key{SPC} 3 )} would have worked,
6852 but using both the comma and the space at once yields:
6854 @group
6855 @smallexample
6856 1:  ( ...      2:  ( ...      1:  (2, ...    2:  (2, ...    2:  (2, ...
6857     .          1:  2              .          1:  (2, ...    1:  (2, 3)
6858                    .                             .              .
6860     (              2              ,             SPC            3 )
6861 @end smallexample
6862 @end group
6864 Joe probably tried to type @kbd{@key{TAB} @key{DEL}} to swap the
6865 extra incomplete object to the top of the stack and delete it.
6866 But a feature of Calc is that @key{DEL} on an incomplete object
6867 deletes just one component out of that object, so he had to press
6868 @key{DEL} twice to finish the job.
6870 @group
6871 @smallexample
6872 2:  (2, ...    2:  (2, 3)     2:  (2, 3)     1:  (2, 3)
6873 1:  (2, 3)     1:  (2, ...    1:  ( ...          .
6874     .              .              .
6876                   TAB            DEL            DEL
6877 @end smallexample
6878 @end group
6880 (As it turns out, deleting the second-to-top stack entry happens often
6881 enough that Calc provides a special key, @kbd{M-DEL}, to do just that.
6882 @kbd{M-DEL} is just like @kbd{TAB DEL}, except that it doesn't exhibit
6883 the ``feature'' that tripped poor Joe.)
6885 @node Algebraic Answer 1, Algebraic Answer 2, RPN Answer 4, Answers to Exercises
6886 @subsection Algebraic Entry Tutorial Exercise 1
6888 @noindent
6889 Type @kbd{' sqrt($) @key{RET}}.
6891 If the @kbd{Q} key is broken, you could use @kbd{' $^0.5 @key{RET}}.
6892 Or, RPN style, @kbd{0.5 ^}.
6894 (Actually, @samp{$^1:2}, using the fraction one-half as the power, is
6895 a closer equivalent, since @samp{9^0.5} yields @cite{3.0} whereas
6896 @samp{sqrt(9)} and @samp{9^1:2} yield the exact integer @cite{3}.)
6898 @node Algebraic Answer 2, Algebraic Answer 3, Algebraic Answer 1, Answers to Exercises
6899 @subsection Algebraic Entry Tutorial Exercise 2
6901 @noindent
6902 In the formula @samp{2 x (1+y)}, @samp{x} was interpreted as a function
6903 name with @samp{1+y} as its argument.  Assigning a value to a variable
6904 has no relation to a function by the same name.  Joe needed to use an
6905 explicit @samp{*} symbol here:  @samp{2 x*(1+y)}.
6907 @node Algebraic Answer 3, Modes Answer 1, Algebraic Answer 2, Answers to Exercises
6908 @subsection Algebraic Entry Tutorial Exercise 3
6910 @noindent
6911 The result from @kbd{1 @key{RET} 0 /} will be the formula @cite{1 / 0}.
6912 The ``function'' @samp{/} cannot be evaluated when its second argument
6913 is zero, so it is left in symbolic form.  When you now type @kbd{0 *},
6914 the result will be zero because Calc uses the general rule that ``zero
6915 times anything is zero.''
6917 @c [fix-ref Infinities]
6918 The @kbd{m i} command enables an @dfn{infinite mode} in which @cite{1 / 0}
6919 results in a special symbol that represents ``infinity.''  If you
6920 multiply infinity by zero, Calc uses another special new symbol to
6921 show that the answer is ``indeterminate.''  @xref{Infinities}, for
6922 further discussion of infinite and indeterminate values.
6924 @node Modes Answer 1, Modes Answer 2, Algebraic Answer 3, Answers to Exercises
6925 @subsection Modes Tutorial Exercise 1
6927 @noindent
6928 Calc always stores its numbers in decimal, so even though one-third has
6929 an exact base-3 representation (@samp{3#0.1}), it is still stored as
6930 0.3333333 (chopped off after 12 or however many decimal digits) inside
6931 the calculator's memory.  When this inexact number is converted back
6932 to base 3 for display, it may still be slightly inexact.  When we
6933 multiply this number by 3, we get 0.999999, also an inexact value.
6935 When Calc displays a number in base 3, it has to decide how many digits
6936 to show.  If the current precision is 12 (decimal) digits, that corresponds
6937 to @samp{12 / log10(3) = 25.15} base-3 digits.  Because 25.15 is not an
6938 exact integer, Calc shows only 25 digits, with the result that stored
6939 numbers carry a little bit of extra information that may not show up on
6940 the screen.  When Joe entered @samp{3#0.2}, the stored number 0.666666
6941 happened to round to a pleasing value when it lost that last 0.15 of a
6942 digit, but it was still inexact in Calc's memory.  When he divided by 2,
6943 he still got the dreaded inexact value 0.333333.  (Actually, he divided
6944 0.666667 by 2 to get 0.333334, which is why he got something a little
6945 higher than @code{3#0.1} instead of a little lower.)
6947 If Joe didn't want to be bothered with all this, he could have typed
6948 @kbd{M-24 d n} to display with one less digit than the default.  (If
6949 you give @kbd{d n} a negative argument, it uses default-minus-that,
6950 so @kbd{M-- d n} would be an easier way to get the same effect.)  Those
6951 inexact results would still be lurking there, but they would now be
6952 rounded to nice, natural-looking values for display purposes.  (Remember,
6953 @samp{0.022222} in base 3 is like @samp{0.099999} in base 10; rounding
6954 off one digit will round the number up to @samp{0.1}.)  Depending on the
6955 nature of your work, this hiding of the inexactness may be a benefit or
6956 a danger.  With the @kbd{d n} command, Calc gives you the choice.
6958 Incidentally, another consequence of all this is that if you type
6959 @kbd{M-30 d n} to display more digits than are ``really there,''
6960 you'll see garbage digits at the end of the number.  (In decimal
6961 display mode, with decimally-stored numbers, these garbage digits are
6962 always zero so they vanish and you don't notice them.)  Because Calc
6963 rounds off that 0.15 digit, there is the danger that two numbers could
6964 be slightly different internally but still look the same.  If you feel
6965 uneasy about this, set the @kbd{d n} precision to be a little higher
6966 than normal; you'll get ugly garbage digits, but you'll always be able
6967 to tell two distinct numbers apart.
6969 An interesting side note is that most computers store their
6970 floating-point numbers in binary, and convert to decimal for display.
6971 Thus everyday programs have the same problem:  Decimal 0.1 cannot be
6972 represented exactly in binary (try it: @kbd{0.1 d 2}), so @samp{0.1 * 10}
6973 comes out as an inexact approximation to 1 on some machines (though
6974 they generally arrange to hide it from you by rounding off one digit as
6975 we did above).  Because Calc works in decimal instead of binary, you can
6976 be sure that numbers that look exact @emph{are} exact as long as you stay
6977 in decimal display mode.
6979 It's not hard to show that any number that can be represented exactly
6980 in binary, octal, or hexadecimal is also exact in decimal, so the kinds
6981 of problems we saw in this exercise are likely to be severe only when
6982 you use a relatively unusual radix like 3.
6984 @node Modes Answer 2, Modes Answer 3, Modes Answer 1, Answers to Exercises
6985 @subsection Modes Tutorial Exercise 2
6987 If the radix is 15 or higher, we can't use the letter @samp{e} to mark
6988 the exponent because @samp{e} is interpreted as a digit.  When Calc
6989 needs to display scientific notation in a high radix, it writes
6990 @samp{16#F.E8F*16.^15}.  You can enter a number like this as an
6991 algebraic entry.  Also, pressing @kbd{e} without any digits before it
6992 normally types @kbd{1e}, but in a high radix it types @kbd{16.^} and
6993 puts you in algebraic entry:  @kbd{16#f.e8f RET e 15 RET *} is another
6994 way to enter this number.
6996 The reason Calc puts a decimal point in the @samp{16.^} is to prevent
6997 huge integers from being generated if the exponent is large (consider
6998 @samp{16#1.23*16^1000}, where we compute @samp{16^1000} as a giant
6999 exact integer and then throw away most of the digits when we multiply
7000 it by the floating-point @samp{16#1.23}).  While this wouldn't normally
7001 matter for display purposes, it could give you a nasty surprise if you
7002 copied that number into a file and later moved it back into Calc.
7004 @node Modes Answer 3, Modes Answer 4, Modes Answer 2, Answers to Exercises
7005 @subsection Modes Tutorial Exercise 3
7007 @noindent
7008 The answer he got was @cite{0.5000000000006399}.
7010 The problem is not that the square operation is inexact, but that the
7011 sine of 45 that was already on the stack was accurate to only 12 places.
7012 Arbitrary-precision calculations still only give answers as good as
7013 their inputs.
7015 The real problem is that there is no 12-digit number which, when
7016 squared, comes out to 0.5 exactly.  The @kbd{f [} and @kbd{f ]}
7017 commands decrease or increase a number by one unit in the last
7018 place (according to the current precision).  They are useful for
7019 determining facts like this.
7021 @group
7022 @smallexample
7023 1:  0.707106781187      1:  0.500000000001
7024     .                       .
7026     45 S                    2 ^
7028 @end smallexample
7029 @end group
7030 @noindent
7031 @group
7032 @smallexample
7033 1:  0.707106781187      1:  0.707106781186      1:  0.499999999999
7034     .                       .                       .
7036     U  DEL                  f [                     2 ^
7037 @end smallexample
7038 @end group
7040 A high-precision calculation must be carried out in high precision
7041 all the way.  The only number in the original problem which was known
7042 exactly was the quantity 45 degrees, so the precision must be raised
7043 before anything is done after the number 45 has been entered in order
7044 for the higher precision to be meaningful.
7046 @node Modes Answer 4, Arithmetic Answer 1, Modes Answer 3, Answers to Exercises
7047 @subsection Modes Tutorial Exercise 4
7049 @noindent
7050 Many calculations involve real-world quantities, like the width and
7051 height of a piece of wood or the volume of a jar.  Such quantities
7052 can't be measured exactly anyway, and if the data that is input to
7053 a calculation is inexact, doing exact arithmetic on it is a waste
7054 of time.
7056 Fractions become unwieldy after too many calculations have been
7057 done with them.  For example, the sum of the reciprocals of the
7058 integers from 1 to 10 is 7381:2520.  The sum from 1 to 30 is
7059 9304682830147:2329089562800.  After a point it will take a long
7060 time to add even one more term to this sum, but a floating-point
7061 calculation of the sum will not have this problem.
7063 Also, rational numbers cannot express the results of all calculations.
7064 There is no fractional form for the square root of two, so if you type
7065 @w{@kbd{2 Q}}, Calc has no choice but to give you a floating-point answer.
7067 @node Arithmetic Answer 1, Arithmetic Answer 2, Modes Answer 4, Answers to Exercises
7068 @subsection Arithmetic Tutorial Exercise 1
7070 @noindent
7071 Dividing two integers that are larger than the current precision may
7072 give a floating-point result that is inaccurate even when rounded
7073 down to an integer.  Consider @cite{123456789 / 2} when the current
7074 precision is 6 digits.  The true answer is @cite{61728394.5}, but
7075 with a precision of 6 this will be rounded to @c{$12345700.0/2.0 = 61728500.0$}
7076 @cite{12345700.@: / 2.@: = 61728500.}.
7077 The result, when converted to an integer, will be off by 106.
7079 Here are two solutions:  Raise the precision enough that the
7080 floating-point round-off error is strictly to the right of the
7081 decimal point.  Or, convert to fraction mode so that @cite{123456789 / 2}
7082 produces the exact fraction @cite{123456789:2}, which can be rounded
7083 down by the @kbd{F} command without ever switching to floating-point
7084 format.
7086 @node Arithmetic Answer 2, Vector Answer 1, Arithmetic Answer 1, Answers to Exercises
7087 @subsection Arithmetic Tutorial Exercise 2
7089 @noindent
7090 @kbd{27 @key{RET} 9 B} could give the exact result @cite{3:2}, but it
7091 does a floating-point calculation instead and produces @cite{1.5}.
7093 Calc will find an exact result for a logarithm if the result is an integer
7094 or the reciprocal of an integer.  But there is no efficient way to search
7095 the space of all possible rational numbers for an exact answer, so Calc
7096 doesn't try.
7098 @node Vector Answer 1, Vector Answer 2, Arithmetic Answer 2, Answers to Exercises
7099 @subsection Vector Tutorial Exercise 1
7101 @noindent
7102 Duplicate the vector, compute its length, then divide the vector
7103 by its length:  @kbd{@key{RET} A /}.
7105 @group
7106 @smallexample
7107 1:  [1, 2, 3]  2:  [1, 2, 3]      1:  [0.27, 0.53, 0.80]  1:  1.
7108     .          1:  3.74165738677      .                       .
7109                    .
7111     r 1            RET A              /                       A
7112 @end smallexample
7113 @end group
7115 The final @kbd{A} command shows that the normalized vector does
7116 indeed have unit length.
7118 @node Vector Answer 2, Matrix Answer 1, Vector Answer 1, Answers to Exercises
7119 @subsection Vector Tutorial Exercise 2
7121 @noindent
7122 The average position is equal to the sum of the products of the
7123 positions times their corresponding probabilities.  This is the
7124 definition of the dot product operation.  So all you need to do
7125 is to put the two vectors on the stack and press @kbd{*}.
7127 @node Matrix Answer 1, Matrix Answer 2, Vector Answer 2, Answers to Exercises
7128 @subsection Matrix Tutorial Exercise 1
7130 @noindent
7131 The trick is to multiply by a vector of ones.  Use @kbd{r 4 [1 1 1] *} to
7132 get the row sum.  Similarly, use @kbd{[1 1] r 4 *} to get the column sum.
7134 @node Matrix Answer 2, Matrix Answer 3, Matrix Answer 1, Answers to Exercises
7135 @subsection Matrix Tutorial Exercise 2
7137 @ifinfo
7138 @group
7139 @example
7140    x + a y = 6
7141    x + b y = 10
7142 @end example
7143 @end group
7144 @end ifinfo
7145 @tex
7146 \turnoffactive
7147 \beforedisplay
7148 $$ \eqalign{ x &+ a y = 6 \cr
7149              x &+ b y = 10}
7151 \afterdisplay
7152 @end tex
7154 Just enter the righthand side vector, then divide by the lefthand side
7155 matrix as usual.
7157 @group
7158 @smallexample
7159 1:  [6, 10]    2:  [6, 10]         1:  [6 - 4 a / (b - a), 4 / (b - a) ]
7160     .          1:  [ [ 1, a ]          .
7161                      [ 1, b ] ]
7162                    .
7164 ' [6 10] RET     ' [1 a; 1 b] RET      /
7165 @end smallexample
7166 @end group
7168 This can be made more readable using @kbd{d B} to enable ``big'' display
7169 mode:
7171 @group
7172 @smallexample
7173           4 a     4
7174 1:  [6 - -----, -----]
7175          b - a  b - a
7176 @end smallexample
7177 @end group
7179 Type @kbd{d N} to return to ``normal'' display mode afterwards.
7181 @node Matrix Answer 3, List Answer 1, Matrix Answer 2, Answers to Exercises
7182 @subsection Matrix Tutorial Exercise 3
7184 @noindent
7185 To solve @c{$A^T A \, X = A^T B$}
7186 @cite{trn(A) * A * X = trn(A) * B}, first we compute
7187 @c{$A' = A^T A$}
7188 @cite{A2 = trn(A) * A} and @c{$B' = A^T B$}
7189 @cite{B2 = trn(A) * B}; now, we have a
7190 system @c{$A' X = B'$}
7191 @cite{A2 * X = B2} which we can solve using Calc's @samp{/}
7192 command.
7194 @ifinfo
7195 @group
7196 @example
7197     a + 2b + 3c = 6
7198    4a + 5b + 6c = 2
7199    7a + 6b      = 3
7200    2a + 4b + 6c = 11
7201 @end example
7202 @end group
7203 @end ifinfo
7204 @tex
7205 \turnoffactive
7206 \beforedisplayh
7207 $$ \openup1\jot \tabskip=0pt plus1fil
7208 \halign to\displaywidth{\tabskip=0pt
7209    $\hfil#$&$\hfil{}#{}$&
7210    $\hfil#$&$\hfil{}#{}$&
7211    $\hfil#$&${}#\hfil$\tabskip=0pt plus1fil\cr
7212   a&+&2b&+&3c&=6 \cr
7213  4a&+&5b&+&6c&=2 \cr
7214  7a&+&6b& &  &=3 \cr
7215  2a&+&4b&+&6c&=11 \cr}
7217 \afterdisplayh
7218 @end tex
7220 The first step is to enter the coefficient matrix.  We'll store it in
7221 quick variable number 7 for later reference.  Next, we compute the
7222 @c{$B'$}
7223 @cite{B2} vector.
7225 @group
7226 @smallexample
7227 1:  [ [ 1, 2, 3 ]             2:  [ [ 1, 4, 7, 2 ]     1:  [57, 84, 96]
7228       [ 4, 5, 6 ]                   [ 2, 5, 6, 4 ]         .
7229       [ 7, 6, 0 ]                   [ 3, 6, 0, 6 ] ]
7230       [ 2, 4, 6 ] ]           1:  [6, 2, 3, 11]
7231     .                             .
7233 ' [1 2 3; 4 5 6; 7 6 0; 2 4 6] RET  s 7  v t  [6 2 3 11]   *
7234 @end smallexample
7235 @end group
7237 @noindent
7238 Now we compute the matrix @c{$A'$}
7239 @cite{A2} and divide.
7241 @group
7242 @smallexample
7243 2:  [57, 84, 96]          1:  [-11.64, 14.08, -3.64]
7244 1:  [ [ 70, 72, 39 ]          .
7245       [ 72, 81, 60 ]
7246       [ 39, 60, 81 ] ]
7247     .
7249     r 7 v t r 7 *             /
7250 @end smallexample
7251 @end group
7253 @noindent
7254 (The actual computed answer will be slightly inexact due to
7255 round-off error.)
7257 Notice that the answers are similar to those for the @c{$3\times3$}
7258 @asis{3x3} system
7259 solved in the text.  That's because the fourth equation that was
7260 added to the system is almost identical to the first one multiplied
7261 by two.  (If it were identical, we would have gotten the exact same
7262 answer since the @c{$4\times3$}
7263 @asis{4x3} system would be equivalent to the original @c{$3\times3$}
7264 @asis{3x3}
7265 system.)
7267 Since the first and fourth equations aren't quite equivalent, they
7268 can't both be satisfied at once.  Let's plug our answers back into
7269 the original system of equations to see how well they match.
7271 @group
7272 @smallexample
7273 2:  [-11.64, 14.08, -3.64]     1:  [5.6, 2., 3., 11.2]
7274 1:  [ [ 1, 2, 3 ]                  .
7275       [ 4, 5, 6 ]
7276       [ 7, 6, 0 ]
7277       [ 2, 4, 6 ] ]
7278     .
7280     r 7                            TAB *
7281 @end smallexample
7282 @end group
7284 @noindent
7285 This is reasonably close to our original @cite{B} vector,
7286 @cite{[6, 2, 3, 11]}.
7288 @node List Answer 1, List Answer 2, Matrix Answer 3, Answers to Exercises
7289 @subsection List Tutorial Exercise 1
7291 @noindent
7292 We can use @kbd{v x} to build a vector of integers.  This needs to be
7293 adjusted to get the range of integers we desire.  Mapping @samp{-}
7294 across the vector will accomplish this, although it turns out the
7295 plain @samp{-} key will work just as well.
7297 @group
7298 @smallexample
7299 2:  2                              2:  2
7300 1:  [1, 2, 3, 4, 5, 6, 7, 8, 9]    1:  [-4, -3, -2, -1, 0, 1, 2, 3, 4]
7301     .                                  .
7303     2  v x 9 RET                       5 V M -   or   5 -
7304 @end smallexample
7305 @end group
7307 @noindent
7308 Now we use @kbd{V M ^} to map the exponentiation operator across the
7309 vector.
7311 @group
7312 @smallexample
7313 1:  [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16]
7314     .
7316     V M ^
7317 @end smallexample
7318 @end group
7320 @node List Answer 2, List Answer 3, List Answer 1, Answers to Exercises
7321 @subsection List Tutorial Exercise 2
7323 @noindent
7324 Given @cite{x} and @cite{y} vectors in quick variables 1 and 2 as before,
7325 the first job is to form the matrix that describes the problem.
7327 @ifinfo
7328 @example
7329    m*x + b*1 = y
7330 @end example
7331 @end ifinfo
7332 @tex
7333 \turnoffactive
7334 \beforedisplay
7335 $$ m \times x + b \times 1 = y $$
7336 \afterdisplay
7337 @end tex
7339 Thus we want a @c{$19\times2$}
7340 @asis{19x2} matrix with our @cite{x} vector as one column and
7341 ones as the other column.  So, first we build the column of ones, then
7342 we combine the two columns to form our @cite{A} matrix.
7344 @group
7345 @smallexample
7346 2:  [1.34, 1.41, 1.49, ... ]    1:  [ [ 1.34, 1 ]
7347 1:  [1, 1, 1, ...]                    [ 1.41, 1 ]
7348     .                                 [ 1.49, 1 ]
7349                                       @dots{}
7351     r 1 1 v b 19 RET                M-2 v p v t   s 3
7352 @end smallexample
7353 @end group
7355 @noindent
7356 Now we compute @c{$A^T y$}
7357 @cite{trn(A) * y} and @c{$A^T A$}
7358 @cite{trn(A) * A} and divide.
7360 @group
7361 @smallexample
7362 1:  [33.36554, 13.613]    2:  [33.36554, 13.613]
7363     .                     1:  [ [ 98.0003, 41.63 ]
7364                                 [  41.63,   19   ] ]
7365                               .
7367  v t r 2 *                    r 3 v t r 3 *
7368 @end smallexample
7369 @end group
7371 @noindent
7372 (Hey, those numbers look familiar!)
7374 @group
7375 @smallexample
7376 1:  [0.52141679, -0.425978]
7377     .
7379     /
7380 @end smallexample
7381 @end group
7383 Since we were solving equations of the form @c{$m \times x + b \times 1 = y$}
7384 @cite{m*x + b*1 = y}, these
7385 numbers should be @cite{m} and @cite{b}, respectively.  Sure enough, they
7386 agree exactly with the result computed using @kbd{V M} and @kbd{V R}!
7388 The moral of this story:  @kbd{V M} and @kbd{V R} will probably solve
7389 your problem, but there is often an easier way using the higher-level
7390 arithmetic functions!
7392 @c [fix-ref Curve Fitting]
7393 In fact, there is a built-in @kbd{a F} command that does least-squares
7394 fits.  @xref{Curve Fitting}.
7396 @node List Answer 3, List Answer 4, List Answer 2, Answers to Exercises
7397 @subsection List Tutorial Exercise 3
7399 @noindent
7400 Move to one end of the list and press @kbd{C-@@} (or @kbd{C-SPC} or
7401 whatever) to set the mark, then move to the other end of the list
7402 and type @w{@kbd{M-# g}}.
7404 @group
7405 @smallexample
7406 1:  [2.3, 6, 22, 15.1, 7, 15, 14, 7.5, 2.5]
7407     .
7408 @end smallexample
7409 @end group
7411 To make things interesting, let's assume we don't know at a glance
7412 how many numbers are in this list.  Then we could type:
7414 @group
7415 @smallexample
7416 2:  [2.3, 6, 22, ... ]     2:  [2.3, 6, 22, ... ]
7417 1:  [2.3, 6, 22, ... ]     1:  126356422.5
7418     .                          .
7420     RET                        V R *
7422 @end smallexample
7423 @end group
7424 @noindent
7425 @group
7426 @smallexample
7427 2:  126356422.5            2:  126356422.5     1:  7.94652913734
7428 1:  [2.3, 6, 22, ... ]     1:  9                   .
7429     .                          .
7431     TAB                        v l                 I ^
7432 @end smallexample
7433 @end group
7435 @noindent
7436 (The @kbd{I ^} command computes the @var{n}th root of a number.
7437 You could also type @kbd{& ^} to take the reciprocal of 9 and
7438 then raise the number to that power.)
7440 @node List Answer 4, List Answer 5, List Answer 3, Answers to Exercises
7441 @subsection List Tutorial Exercise 4
7443 @noindent
7444 A number @cite{j} is a divisor of @cite{n} if @c{$n \mathbin{\hbox{\code{\%}}} j = 0$}
7445 @samp{n % j = 0}.  The first
7446 step is to get a vector that identifies the divisors.
7448 @group
7449 @smallexample
7450 2:  30                  2:  [0, 0, 0, 2, ...]    1:  [1, 1, 1, 0, ...]
7451 1:  [1, 2, 3, 4, ...]   1:  0                        .
7452     .                       .
7454  30 RET v x 30 RET   s 1    V M %  0                 V M a =  s 2
7455 @end smallexample
7456 @end group
7458 @noindent
7459 This vector has 1's marking divisors of 30 and 0's marking non-divisors.
7461 The zeroth divisor function is just the total number of divisors.
7462 The first divisor function is the sum of the divisors.
7464 @group
7465 @smallexample
7466 1:  8      3:  8                    2:  8                    2:  8
7467            2:  [1, 2, 3, 4, ...]    1:  [1, 2, 3, 0, ...]    1:  72
7468            1:  [1, 1, 1, 0, ...]        .                        .
7469                .
7471    V R +       r 1 r 2                  V M *                  V R +
7472 @end smallexample
7473 @end group
7475 @noindent
7476 Once again, the last two steps just compute a dot product for which
7477 a simple @kbd{*} would have worked equally well.
7479 @node List Answer 5, List Answer 6, List Answer 4, Answers to Exercises
7480 @subsection List Tutorial Exercise 5
7482 @noindent
7483 The obvious first step is to obtain the list of factors with @kbd{k f}.
7484 This list will always be in sorted order, so if there are duplicates
7485 they will be right next to each other.  A suitable method is to compare
7486 the list with a copy of itself shifted over by one.
7488 @group
7489 @smallexample
7490 1:  [3, 7, 7, 7, 19]   2:  [3, 7, 7, 7, 19]     2:  [3, 7, 7, 7, 19, 0]
7491     .                  1:  [3, 7, 7, 7, 19, 0]  1:  [0, 3, 7, 7, 7, 19]
7492                            .                        .
7494     19551 k f              RET 0 |                  TAB 0 TAB |
7496 @end smallexample
7497 @end group
7498 @noindent
7499 @group
7500 @smallexample
7501 1:  [0, 0, 1, 1, 0, 0]   1:  2          1:  0
7502     .                        .              .
7504     V M a =                  V R +          0 a =
7505 @end smallexample
7506 @end group
7508 @noindent
7509 Note that we have to arrange for both vectors to have the same length
7510 so that the mapping operation works; no prime factor will ever be
7511 zero, so adding zeros on the left and right is safe.  From then on
7512 the job is pretty straightforward.
7514 Incidentally, Calc provides the @c{\dfn{M\"obius} $\mu$}
7515 @dfn{Moebius mu} function which is
7516 zero if and only if its argument is square-free.  It would be a much
7517 more convenient way to do the above test in practice.
7519 @node List Answer 6, List Answer 7, List Answer 5, Answers to Exercises
7520 @subsection List Tutorial Exercise 6
7522 @noindent
7523 First use @kbd{v x 6 RET} to get a list of integers, then @kbd{V M v x}
7524 to get a list of lists of integers!
7526 @node List Answer 7, List Answer 8, List Answer 6, Answers to Exercises
7527 @subsection List Tutorial Exercise 7
7529 @noindent
7530 Here's one solution.  First, compute the triangular list from the previous
7531 exercise and type @kbd{1 -} to subtract one from all the elements.
7533 @group
7534 @smallexample
7535 1:  [ [0],
7536       [0, 1],
7537       [0, 1, 2],
7538       @dots{}
7540     1 -
7541 @end smallexample
7542 @end group
7544 The numbers down the lefthand edge of the list we desire are called
7545 the ``triangular numbers'' (now you know why!).  The @cite{n}th
7546 triangular number is the sum of the integers from 1 to @cite{n}, and
7547 can be computed directly by the formula @c{$n (n+1) \over 2$}
7548 @cite{n * (n+1) / 2}.
7550 @group
7551 @smallexample
7552 2:  [ [0], [0, 1], ... ]    2:  [ [0], [0, 1], ... ]
7553 1:  [0, 1, 2, 3, 4, 5]      1:  [0, 1, 3, 6, 10, 15]
7554     .                           .
7556     v x 6 RET 1 -               V M ' $ ($+1)/2 RET
7557 @end smallexample
7558 @end group
7560 @noindent
7561 Adding this list to the above list of lists produces the desired
7562 result:
7564 @group
7565 @smallexample
7566 1:  [ [0],
7567       [1, 2],
7568       [3, 4, 5],
7569       [6, 7, 8, 9],
7570       [10, 11, 12, 13, 14],
7571       [15, 16, 17, 18, 19, 20] ]
7572       .
7574       V M +
7575 @end smallexample
7576 @end group
7578 If we did not know the formula for triangular numbers, we could have
7579 computed them using a @kbd{V U +} command.  We could also have
7580 gotten them the hard way by mapping a reduction across the original
7581 triangular list.
7583 @group
7584 @smallexample
7585 2:  [ [0], [0, 1], ... ]    2:  [ [0], [0, 1], ... ]
7586 1:  [ [0], [0, 1], ... ]    1:  [0, 1, 3, 6, 10, 15]
7587     .                           .
7589     RET                         V M V R +
7590 @end smallexample
7591 @end group
7593 @noindent
7594 (This means ``map a @kbd{V R +} command across the vector,'' and
7595 since each element of the main vector is itself a small vector,
7596 @kbd{V R +} computes the sum of its elements.)
7598 @node List Answer 8, List Answer 9, List Answer 7, Answers to Exercises
7599 @subsection List Tutorial Exercise 8
7601 @noindent
7602 The first step is to build a list of values of @cite{x}.
7604 @group
7605 @smallexample
7606 1:  [1, 2, 3, ..., 21]  1:  [0, 1, 2, ..., 20]  1:  [0, 0.25, 0.5, ..., 5]
7607     .                       .                       .
7609     v x 21 RET              1 -                     4 /  s 1
7610 @end smallexample
7611 @end group
7613 Next, we compute the Bessel function values.
7615 @group
7616 @smallexample
7617 1:  [0., 0.124, 0.242, ..., -0.328]
7618     .
7620     V M ' besJ(1,$) RET
7621 @end smallexample
7622 @end group
7624 @noindent
7625 (Another way to do this would be @kbd{1 TAB V M f j}.)
7627 A way to isolate the maximum value is to compute the maximum using
7628 @kbd{V R X}, then compare all the Bessel values with that maximum.
7630 @group
7631 @smallexample
7632 2:  [0., 0.124, 0.242, ... ]   1:  [0, 0, 0, ... ]    2:  [0, 0, 0, ... ]
7633 1:  0.5801562                      .                  1:  1
7634     .                                                     .
7636     RET V R X                      V M a =                RET V R +    DEL
7637 @end smallexample
7638 @end group
7640 @noindent
7641 It's a good idea to verify, as in the last step above, that only
7642 one value is equal to the maximum.  (After all, a plot of @c{$\sin x$}
7643 @cite{sin(x)}
7644 might have many points all equal to the maximum value, 1.)
7646 The vector we have now has a single 1 in the position that indicates
7647 the maximum value of @cite{x}.  Now it is a simple matter to convert
7648 this back into the corresponding value itself.
7650 @group
7651 @smallexample
7652 2:  [0, 0, 0, ... ]         1:  [0, 0., 0., ... ]    1:  1.75
7653 1:  [0, 0.25, 0.5, ... ]        .                        .
7654     .
7656     r 1                         V M *                    V R +
7657 @end smallexample
7658 @end group
7660 If @kbd{a =} had produced more than one @cite{1} value, this method
7661 would have given the sum of all maximum @cite{x} values; not very
7662 useful!  In this case we could have used @kbd{v m} (@code{calc-mask-vector})
7663 instead.  This command deletes all elements of a ``data'' vector that
7664 correspond to zeros in a ``mask'' vector, leaving us with, in this
7665 example, a vector of maximum @cite{x} values.
7667 The built-in @kbd{a X} command maximizes a function using more
7668 efficient methods.  Just for illustration, let's use @kbd{a X}
7669 to maximize @samp{besJ(1,x)} over this same interval.
7671 @group
7672 @smallexample
7673 2:  besJ(1, x)                 1:  [1.84115, 0.581865]
7674 1:  [0 .. 5]                       .
7675     .
7677 ' besJ(1,x), [0..5] RET            a X x RET
7678 @end smallexample
7679 @end group
7681 @noindent
7682 The output from @kbd{a X} is a vector containing the value of @cite{x}
7683 that maximizes the function, and the function's value at that maximum.
7684 As you can see, our simple search got quite close to the right answer.
7686 @node List Answer 9, List Answer 10, List Answer 8, Answers to Exercises
7687 @subsection List Tutorial Exercise 9
7689 @noindent
7690 Step one is to convert our integer into vector notation.
7692 @group
7693 @smallexample
7694 1:  25129925999           3:  25129925999
7695     .                     2:  10
7696                           1:  [11, 10, 9, ..., 1, 0]
7697                               .
7699     25129925999 RET           10 RET 12 RET v x 12 RET -
7701 @end smallexample
7702 @end group
7703 @noindent
7704 @group
7705 @smallexample
7706 1:  25129925999              1:  [0, 2, 25, 251, 2512, ... ]
7707 2:  [100000000000, ... ]         .
7708     .
7710     V M ^   s 1                  V M \
7711 @end smallexample
7712 @end group
7714 @noindent
7715 (Recall, the @kbd{\} command computes an integer quotient.)
7717 @group
7718 @smallexample
7719 1:  [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
7720     .
7722     10 V M %   s 2
7723 @end smallexample
7724 @end group
7726 Next we must increment this number.  This involves adding one to
7727 the last digit, plus handling carries.  There is a carry to the
7728 left out of a digit if that digit is a nine and all the digits to
7729 the right of it are nines.
7731 @group
7732 @smallexample
7733 1:  [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1]   1:  [1, 1, 1, 0, 0, 1, ... ]
7734     .                                          .
7736     9 V M a =                                  v v
7738 @end smallexample
7739 @end group
7740 @noindent
7741 @group
7742 @smallexample
7743 1:  [1, 1, 1, 0, 0, 0, ... ]   1:  [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
7744     .                              .
7746     V U *                          v v 1 |
7747 @end smallexample
7748 @end group
7750 @noindent
7751 Accumulating @kbd{*} across a vector of ones and zeros will preserve
7752 only the initial run of ones.  These are the carries into all digits
7753 except the rightmost digit.  Concatenating a one on the right takes
7754 care of aligning the carries properly, and also adding one to the
7755 rightmost digit.
7757 @group
7758 @smallexample
7759 2:  [0, 0, 0, 0, ... ]     1:  [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
7760 1:  [0, 0, 2, 5, ... ]         .
7761     .
7763     0 r 2 |                    V M +  10 V M %
7764 @end smallexample
7765 @end group
7767 @noindent
7768 Here we have concatenated 0 to the @emph{left} of the original number;
7769 this takes care of shifting the carries by one with respect to the
7770 digits that generated them.
7772 Finally, we must convert this list back into an integer.
7774 @group
7775 @smallexample
7776 3:  [0, 0, 2, 5, ... ]        2:  [0, 0, 2, 5, ... ]
7777 2:  1000000000000             1:  [1000000000000, 100000000000, ... ]
7778 1:  [100000000000, ... ]          .
7779     .
7781     10 RET 12 ^  r 1              |
7783 @end smallexample
7784 @end group
7785 @noindent
7786 @group
7787 @smallexample
7788 1:  [0, 0, 20000000000, 5000000000, ... ]    1:  25129926000
7789     .                                            .
7791     V M *                                        V R +
7792 @end smallexample
7793 @end group
7795 @noindent
7796 Another way to do this final step would be to reduce the formula
7797 @w{@samp{10 $$ + $}} across the vector of digits.
7799 @group
7800 @smallexample
7801 1:  [0, 0, 2, 5, ... ]        1:  25129926000
7802     .                             .
7804                                   V R ' 10 $$ + $ RET
7805 @end smallexample
7806 @end group
7808 @node List Answer 10, List Answer 11, List Answer 9, Answers to Exercises
7809 @subsection List Tutorial Exercise 10
7811 @noindent
7812 For the list @cite{[a, b, c, d]}, the result is @cite{((a = b) = c) = d},
7813 which will compare @cite{a} and @cite{b} to produce a 1 or 0, which is
7814 then compared with @cite{c} to produce another 1 or 0, which is then
7815 compared with @cite{d}.  This is not at all what Joe wanted.
7817 Here's a more correct method:
7819 @group
7820 @smallexample
7821 1:  [7, 7, 7, 8, 7]      2:  [7, 7, 7, 8, 7]
7822     .                    1:  7
7823                              .
7825   ' [7,7,7,8,7] RET          RET v r 1 RET
7827 @end smallexample
7828 @end group
7829 @noindent
7830 @group
7831 @smallexample
7832 1:  [1, 1, 1, 0, 1]      1:  0
7833     .                        .
7835     V M a =                  V R *
7836 @end smallexample
7837 @end group
7839 @node List Answer 11, List Answer 12, List Answer 10, Answers to Exercises
7840 @subsection List Tutorial Exercise 11
7842 @noindent
7843 The circle of unit radius consists of those points @cite{(x,y)} for which
7844 @cite{x^2 + y^2 < 1}.  We start by generating a vector of @cite{x^2}
7845 and a vector of @cite{y^2}.
7847 We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7848 commands.
7850 @group
7851 @smallexample
7852 2:  [2., 2., ..., 2.]          2:  [2., 2., ..., 2.]
7853 1:  [2., 2., ..., 2.]          1:  [1.16, 1.98, ..., 0.81]
7854     .                              .
7856  v . t .  2. v b 100 RET RET       V M k r
7858 @end smallexample
7859 @end group
7860 @noindent
7861 @group
7862 @smallexample
7863 2:  [2., 2., ..., 2.]          1:  [0.026, 0.96, ..., 0.036]
7864 1:  [0.026, 0.96, ..., 0.036]  2:  [0.53, 0.81, ..., 0.094]
7865     .                              .
7867     1 -  2 V M ^                   TAB  V M k r  1 -  2 V M ^
7868 @end smallexample
7869 @end group
7871 Now we sum the @cite{x^2} and @cite{y^2} values, compare with 1 to
7872 get a vector of 1/0 truth values, then sum the truth values.
7874 @group
7875 @smallexample
7876 1:  [0.56, 1.78, ..., 0.13]    1:  [1, 0, ..., 1]    1:  84
7877     .                              .                     .
7879     +                              1 V M a <             V R +
7880 @end smallexample
7881 @end group
7883 @noindent
7884 The ratio @cite{84/100} should approximate the ratio @c{$\pi/4$}
7885 @cite{pi/4}.
7887 @group
7888 @smallexample
7889 1:  0.84       1:  3.36       2:  3.36       1:  1.0695
7890     .              .          1:  3.14159        .
7892     100 /          4 *            P              /
7893 @end smallexample
7894 @end group
7896 @noindent
7897 Our estimate, 3.36, is off by about 7%.  We could get a better estimate
7898 by taking more points (say, 1000), but it's clear that this method is
7899 not very efficient!
7901 (Naturally, since this example uses random numbers your own answer
7902 will be slightly different from the one shown here!)
7904 If you typed @kbd{v .} and @kbd{t .} before, type them again to
7905 return to full-sized display of vectors.
7907 @node List Answer 12, List Answer 13, List Answer 11, Answers to Exercises
7908 @subsection List Tutorial Exercise 12
7910 @noindent
7911 This problem can be made a lot easier by taking advantage of some
7912 symmetries.  First of all, after some thought it's clear that the
7913 @cite{y} axis can be ignored altogether.  Just pick a random @cite{x}
7914 component for one end of the match, pick a random direction @c{$\theta$}
7915 @cite{theta},
7916 and see if @cite{x} and @c{$x + \cos \theta$}
7917 @cite{x + cos(theta)} (which is the @cite{x}
7918 coordinate of the other endpoint) cross a line.  The lines are at
7919 integer coordinates, so this happens when the two numbers surround
7920 an integer.
7922 Since the two endpoints are equivalent, we may as well choose the leftmost
7923 of the two endpoints as @cite{x}.  Then @cite{theta} is an angle pointing
7924 to the right, in the range -90 to 90 degrees.  (We could use radians, but
7925 it would feel like cheating to refer to @c{$\pi/2$}
7926 @cite{pi/2} radians while trying
7927 to estimate @c{$\pi$}
7928 @cite{pi}!)
7930 In fact, since the field of lines is infinite we can choose the
7931 coordinates 0 and 1 for the lines on either side of the leftmost
7932 endpoint.  The rightmost endpoint will be between 0 and 1 if the
7933 match does not cross a line, or between 1 and 2 if it does.  So:
7934 Pick random @cite{x} and @c{$\theta$}
7935 @cite{theta}, compute @c{$x + \cos \theta$}
7936 @cite{x + cos(theta)},
7937 and count how many of the results are greater than one.  Simple!
7939 We can make this go a bit faster by using the @kbd{v .} and @kbd{t .}
7940 commands.
7942 @group
7943 @smallexample
7944 1:  [0.52, 0.71, ..., 0.72]    2:  [0.52, 0.71, ..., 0.72]
7945     .                          1:  [78.4, 64.5, ..., -42.9]
7946                                    .
7948 v . t . 1. v b 100 RET  V M k r    180. v b 100 RET  V M k r  90 -
7949 @end smallexample
7950 @end group
7952 @noindent
7953 (The next step may be slow, depending on the speed of your computer.)
7955 @group
7956 @smallexample
7957 2:  [0.52, 0.71, ..., 0.72]    1:  [0.72, 1.14, ..., 1.45]
7958 1:  [0.20, 0.43, ..., 0.73]        .
7959     .
7961     m d  V M C                     +
7963 @end smallexample
7964 @end group
7965 @noindent
7966 @group
7967 @smallexample
7968 1:  [0, 1, ..., 1]       1:  0.64            1:  3.125
7969     .                        .                   .
7971     1 V M a >                V R + 100 /         2 TAB /
7972 @end smallexample
7973 @end group
7975 Let's try the third method, too.  We'll use random integers up to
7976 one million.  The @kbd{k r} command with an integer argument picks
7977 a random integer.
7979 @group
7980 @smallexample
7981 2:  [1000000, 1000000, ..., 1000000]   2:  [78489, 527587, ..., 814975]
7982 1:  [1000000, 1000000, ..., 1000000]   1:  [324014, 358783, ..., 955450]
7983     .                                      .
7985     1000000 v b 100 RET RET                V M k r  TAB  V M k r
7987 @end smallexample
7988 @end group
7989 @noindent
7990 @group
7991 @smallexample
7992 1:  [1, 1, ..., 25]      1:  [1, 1, ..., 0]     1:  0.56
7993     .                        .                      .
7995     V M k g                  1 V M a =              V R + 100 /
7997 @end smallexample
7998 @end group
7999 @noindent
8000 @group
8001 @smallexample
8002 1:  10.714        1:  3.273
8003     .                 .
8005     6 TAB /           Q
8006 @end smallexample
8007 @end group
8009 For a proof of this property of the GCD function, see section 4.5.2,
8010 exercise 10, of Knuth's @emph{Art of Computer Programming}, volume II.
8012 If you typed @kbd{v .} and @kbd{t .} before, type them again to
8013 return to full-sized display of vectors.
8015 @node List Answer 13, List Answer 14, List Answer 12, Answers to Exercises
8016 @subsection List Tutorial Exercise 13
8018 @noindent
8019 First, we put the string on the stack as a vector of ASCII codes.
8021 @group
8022 @smallexample
8023 1:  [84, 101, 115, ..., 51]
8024     .
8026     "Testing, 1, 2, 3 RET
8027 @end smallexample
8028 @end group
8030 @noindent
8031 Note that the @kbd{"} key, like @kbd{$}, initiates algebraic entry so
8032 there was no need to type an apostrophe.  Also, Calc didn't mind that
8033 we omitted the closing @kbd{"}.  (The same goes for all closing delimiters
8034 like @kbd{)} and @kbd{]} at the end of a formula.
8036 We'll show two different approaches here.  In the first, we note that
8037 if the input vector is @cite{[a, b, c, d]}, then the hash code is
8038 @cite{3 (3 (3a + b) + c) + d = 27a + 9b + 3c + d}.  In other words,
8039 it's a sum of descending powers of three times the ASCII codes.
8041 @group
8042 @smallexample
8043 2:  [84, 101, 115, ..., 51]    2:  [84, 101, 115, ..., 51]
8044 1:  16                         1:  [15, 14, 13, ..., 0]
8045     .                              .
8047     RET v l                        v x 16 RET -
8049 @end smallexample
8050 @end group
8051 @noindent
8052 @group
8053 @smallexample
8054 2:  [84, 101, 115, ..., 51]    1:  1960915098    1:  121
8055 1:  [14348907, ..., 1]             .                 .
8056     .
8058     3 TAB V M ^                    *                 511 %
8059 @end smallexample
8060 @end group
8062 @noindent
8063 Once again, @kbd{*} elegantly summarizes most of the computation.
8064 But there's an even more elegant approach:  Reduce the formula
8065 @kbd{3 $$ + $} across the vector.  Recall that this represents a
8066 function of two arguments that computes its first argument times three
8067 plus its second argument.
8069 @group
8070 @smallexample
8071 1:  [84, 101, 115, ..., 51]    1:  1960915098
8072     .                              .
8074     "Testing, 1, 2, 3 RET          V R ' 3$$+$ RET
8075 @end smallexample
8076 @end group
8078 @noindent
8079 If you did the decimal arithmetic exercise, this will be familiar.
8080 Basically, we're turning a base-3 vector of digits into an integer,
8081 except that our ``digits'' are much larger than real digits.
8083 Instead of typing @kbd{511 %} again to reduce the result, we can be
8084 cleverer still and notice that rather than computing a huge integer
8085 and taking the modulo at the end, we can take the modulo at each step
8086 without affecting the result.  While this means there are more
8087 arithmetic operations, the numbers we operate on remain small so
8088 the operations are faster.
8090 @group
8091 @smallexample
8092 1:  [84, 101, 115, ..., 51]    1:  121
8093     .                              .
8095     "Testing, 1, 2, 3 RET          V R ' (3$$+$)%511 RET
8096 @end smallexample
8097 @end group
8099 Why does this work?  Think about a two-step computation:
8100 @w{@cite{3 (3a + b) + c}}.  Taking a result modulo 511 basically means
8101 subtracting off enough 511's to put the result in the desired range.
8102 So the result when we take the modulo after every step is,
8104 @ifinfo
8105 @example
8106 3 (3 a + b - 511 m) + c - 511 n
8107 @end example
8108 @end ifinfo
8109 @tex
8110 \turnoffactive
8111 \beforedisplay
8112 $$ 3 (3 a + b - 511 m) + c - 511 n $$
8113 \afterdisplay
8114 @end tex
8116 @noindent
8117 for some suitable integers @cite{m} and @cite{n}.  Expanding out by
8118 the distributive law yields
8120 @ifinfo
8121 @example
8122 9 a + 3 b + c - 511*3 m - 511 n
8123 @end example
8124 @end ifinfo
8125 @tex
8126 \turnoffactive
8127 \beforedisplay
8128 $$ 9 a + 3 b + c - 511\times3 m - 511 n $$
8129 \afterdisplay
8130 @end tex
8132 @noindent
8133 The @cite{m} term in the latter formula is redundant because any
8134 contribution it makes could just as easily be made by the @cite{n}
8135 term.  So we can take it out to get an equivalent formula with
8136 @cite{n' = 3m + n},
8138 @ifinfo
8139 @example
8140 9 a + 3 b + c - 511 n'
8141 @end example
8142 @end ifinfo
8143 @tex
8144 \turnoffactive
8145 \beforedisplay
8146 $$ 9 a + 3 b + c - 511 n' $$
8147 \afterdisplay
8148 @end tex
8150 @noindent
8151 which is just the formula for taking the modulo only at the end of
8152 the calculation.  Therefore the two methods are essentially the same.
8154 Later in the tutorial we will encounter @dfn{modulo forms}, which
8155 basically automate the idea of reducing every intermediate result
8156 modulo some value @i{M}.
8158 @node List Answer 14, Types Answer 1, List Answer 13, Answers to Exercises
8159 @subsection List Tutorial Exercise 14
8161 We want to use @kbd{H V U} to nest a function which adds a random
8162 step to an @cite{(x,y)} coordinate.  The function is a bit long, but
8163 otherwise the problem is quite straightforward.
8165 @group
8166 @smallexample
8167 2:  [0, 0]     1:  [ [    0,       0    ]
8168 1:  50               [  0.4288, -0.1695 ]
8169     .                [ -0.4787, -0.9027 ]
8170                      ...
8172     [0,0] 50       H V U ' <# + [random(2.0)-1, random(2.0)-1]> RET
8173 @end smallexample
8174 @end group
8176 Just as the text recommended, we used @samp{< >} nameless function
8177 notation to keep the two @code{random} calls from being evaluated
8178 before nesting even begins.
8180 We now have a vector of @cite{[x, y]} sub-vectors, which by Calc's
8181 rules acts like a matrix.  We can transpose this matrix and unpack
8182 to get a pair of vectors, @cite{x} and @cite{y}, suitable for graphing.
8184 @group
8185 @smallexample
8186 2:  [ 0, 0.4288, -0.4787, ... ]
8187 1:  [ 0, -0.1696, -0.9027, ... ]
8188     .
8190     v t  v u  g f
8191 @end smallexample
8192 @end group
8194 Incidentally, because the @cite{x} and @cite{y} are completely
8195 independent in this case, we could have done two separate commands
8196 to create our @cite{x} and @cite{y} vectors of numbers directly.
8198 To make a random walk of unit steps, we note that @code{sincos} of
8199 a random direction exactly gives us an @cite{[x, y]} step of unit
8200 length; in fact, the new nesting function is even briefer, though
8201 we might want to lower the precision a bit for it.
8203 @group
8204 @smallexample
8205 2:  [0, 0]     1:  [ [    0,      0    ]
8206 1:  50               [  0.1318, 0.9912 ]
8207     .                [ -0.5965, 0.3061 ]
8208                      ...
8210     [0,0] 50   m d  p 6 RET   H V U ' <# + sincos(random(360.0))> RET
8211 @end smallexample
8212 @end group
8214 Another @kbd{v t v u g f} sequence will graph this new random walk.
8216 An interesting twist on these random walk functions would be to use
8217 complex numbers instead of 2-vectors to represent points on the plane.
8218 In the first example, we'd use something like @samp{random + random*(0,1)},
8219 and in the second we could use polar complex numbers with random phase
8220 angles.  (This exercise was first suggested in this form by Randal
8221 Schwartz.)
8223 @node Types Answer 1, Types Answer 2, List Answer 14, Answers to Exercises
8224 @subsection Types Tutorial Exercise 1
8226 @noindent
8227 If the number is the square root of @c{$\pi$}
8228 @cite{pi} times a rational number,
8229 then its square, divided by @c{$\pi$}
8230 @cite{pi}, should be a rational number.
8232 @group
8233 @smallexample
8234 1:  1.26508260337    1:  0.509433962268   1:  2486645810:4881193627
8235     .                    .                    .
8237                          2 ^ P /              c F
8238 @end smallexample
8239 @end group
8241 @noindent
8242 Technically speaking this is a rational number, but not one that is
8243 likely to have arisen in the original problem.  More likely, it just
8244 happens to be the fraction which most closely represents some
8245 irrational number to within 12 digits.
8247 But perhaps our result was not quite exact.  Let's reduce the
8248 precision slightly and try again:
8250 @group
8251 @smallexample
8252 1:  0.509433962268     1:  27:53
8253     .                      .
8255     U p 10 RET             c F
8256 @end smallexample
8257 @end group
8259 @noindent
8260 Aha!  It's unlikely that an irrational number would equal a fraction
8261 this simple to within ten digits, so our original number was probably
8262 @c{$\sqrt{27 \pi / 53}$}
8263 @cite{sqrt(27 pi / 53)}.
8265 Notice that we didn't need to re-round the number when we reduced the
8266 precision.  Remember, arithmetic operations always round their inputs
8267 to the current precision before they begin.
8269 @node Types Answer 2, Types Answer 3, Types Answer 1, Answers to Exercises
8270 @subsection Types Tutorial Exercise 2
8272 @noindent
8273 @samp{inf / inf = nan}.  Perhaps @samp{1} is the ``obvious'' answer.
8274 But if @w{@samp{17 inf = inf}}, then @samp{17 inf / inf = inf / inf = 17}, too.
8276 @samp{exp(inf) = inf}.  It's tempting to say that the exponential
8277 of infinity must be ``bigger'' than ``regular'' infinity, but as
8278 far as Calc is concerned all infinities are as just as big.
8279 In other words, as @cite{x} goes to infinity, @cite{e^x} also goes
8280 to infinity, but the fact the @cite{e^x} grows much faster than
8281 @cite{x} is not relevant here.
8283 @samp{exp(-inf) = 0}.  Here we have a finite answer even though
8284 the input is infinite.
8286 @samp{sqrt(-inf) = (0, 1) inf}.  Remember that @cite{(0, 1)}
8287 represents the imaginary number @cite{i}.  Here's a derivation:
8288 @samp{sqrt(-inf) = @w{sqrt((-1) * inf)} = sqrt(-1) * sqrt(inf)}.
8289 The first part is, by definition, @cite{i}; the second is @code{inf}
8290 because, once again, all infinities are the same size.
8292 @samp{sqrt(uinf) = uinf}.  In fact, we do know something about the
8293 direction because @code{sqrt} is defined to return a value in the
8294 right half of the complex plane.  But Calc has no notation for this,
8295 so it settles for the conservative answer @code{uinf}.
8297 @samp{abs(uinf) = inf}.  No matter which direction @cite{x} points,
8298 @samp{abs(x)} always points along the positive real axis.
8300 @samp{ln(0) = -inf}.  Here we have an infinite answer to a finite
8301 input.  As in the @cite{1 / 0} case, Calc will only use infinities
8302 here if you have turned on ``infinite'' mode.  Otherwise, it will
8303 treat @samp{ln(0)} as an error.
8305 @node Types Answer 3, Types Answer 4, Types Answer 2, Answers to Exercises
8306 @subsection Types Tutorial Exercise 3
8308 @noindent
8309 We can make @samp{inf - inf} be any real number we like, say,
8310 @cite{a}, just by claiming that we added @cite{a} to the first
8311 infinity but not to the second.  This is just as true for complex
8312 values of @cite{a}, so @code{nan} can stand for a complex number.
8313 (And, similarly, @code{uinf} can stand for an infinity that points
8314 in any direction in the complex plane, such as @samp{(0, 1) inf}).
8316 In fact, we can multiply the first @code{inf} by two.  Surely
8317 @w{@samp{2 inf - inf = inf}}, but also @samp{2 inf - inf = inf - inf = nan}.
8318 So @code{nan} can even stand for infinity.  Obviously it's just
8319 as easy to make it stand for minus infinity as for plus infinity.
8321 The moral of this story is that ``infinity'' is a slippery fish
8322 indeed, and Calc tries to handle it by having a very simple model
8323 for infinities (only the direction counts, not the ``size''); but
8324 Calc is careful to write @code{nan} any time this simple model is
8325 unable to tell what the true answer is.
8327 @node Types Answer 4, Types Answer 5, Types Answer 3, Answers to Exercises
8328 @subsection Types Tutorial Exercise 4
8330 @group
8331 @smallexample
8332 2:  0@@ 47' 26"              1:  0@@ 2' 47.411765"
8333 1:  17                          .
8334     .
8336     0@@ 47' 26" RET 17           /
8337 @end smallexample
8338 @end group
8340 @noindent
8341 The average song length is two minutes and 47.4 seconds.
8343 @group
8344 @smallexample
8345 2:  0@@ 2' 47.411765"     1:  0@@ 3' 7.411765"    1:  0@@ 53' 6.000005"
8346 1:  0@@ 0' 20"                .                      .
8347     .
8349     20"                      +                      17 *
8350 @end smallexample
8351 @end group
8353 @noindent
8354 The album would be 53 minutes and 6 seconds long.
8356 @node Types Answer 5, Types Answer 6, Types Answer 4, Answers to Exercises
8357 @subsection Types Tutorial Exercise 5
8359 @noindent
8360 Let's suppose it's January 14, 1991.  The easiest thing to do is
8361 to keep trying 13ths of months until Calc reports a Friday.
8362 We can do this by manually entering dates, or by using @kbd{t I}:
8364 @group
8365 @smallexample
8366 1:  <Wed Feb 13, 1991>    1:  <Wed Mar 13, 1991>   1:  <Sat Apr 13, 1991>
8367     .                         .                        .
8369     ' <2/13> RET       DEL    ' <3/13> RET             t I
8370 @end smallexample
8371 @end group
8373 @noindent
8374 (Calc assumes the current year if you don't say otherwise.)
8376 This is getting tedious---we can keep advancing the date by typing
8377 @kbd{t I} over and over again, but let's automate the job by using
8378 vector mapping.  The @kbd{t I} command actually takes a second
8379 ``how-many-months'' argument, which defaults to one.  This
8380 argument is exactly what we want to map over:
8382 @group
8383 @smallexample
8384 2:  <Sat Apr 13, 1991>     1:  [<Mon May 13, 1991>, <Thu Jun 13, 1991>,
8385 1:  [1, 2, 3, 4, 5, 6]          <Sat Jul 13, 1991>, <Tue Aug 13, 1991>,
8386     .                           <Fri Sep 13, 1991>, <Sun Oct 13, 1991>]
8387                                .
8389     v x 6 RET                  V M t I
8390 @end smallexample
8391 @end group
8393 @ifinfo
8394 @noindent
8395 Et voila, September 13, 1991 is a Friday.
8396 @end ifinfo
8397 @tex
8398 \noindent
8399 {\it Et voil{\accent"12 a}}, September 13, 1991 is a Friday.
8400 @end tex
8402 @group
8403 @smallexample
8404 1:  242
8405     .
8407 ' <sep 13> - <jan 14> RET
8408 @end smallexample
8409 @end group
8411 @noindent
8412 And the answer to our original question:  242 days to go.
8414 @node Types Answer 6, Types Answer 7, Types Answer 5, Answers to Exercises
8415 @subsection Types Tutorial Exercise 6
8417 @noindent
8418 The full rule for leap years is that they occur in every year divisible
8419 by four, except that they don't occur in years divisible by 100, except
8420 that they @emph{do} in years divisible by 400.  We could work out the
8421 answer by carefully counting the years divisible by four and the
8422 exceptions, but there is a much simpler way that works even if we
8423 don't know the leap year rule.
8425 Let's assume the present year is 1991.  Years have 365 days, except
8426 that leap years (whenever they occur) have 366 days.  So let's count
8427 the number of days between now and then, and compare that to the
8428 number of years times 365.  The number of extra days we find must be
8429 equal to the number of leap years there were.
8431 @group
8432 @smallexample
8433 1:  <Mon Jan 1, 10001>     2:  <Mon Jan 1, 10001>     1:  2925593
8434     .                      1:  <Tue Jan 1, 1991>          .
8435                                .
8437   ' <jan 1 10001> RET         ' <jan 1 1991> RET          -
8439 @end smallexample
8440 @end group
8441 @noindent
8442 @group
8443 @smallexample
8444 3:  2925593       2:  2925593     2:  2925593     1:  1943
8445 2:  10001         1:  8010        1:  2923650         .
8446 1:  1991              .               .
8447     .
8449   10001 RET 1991      -               365 *           -
8450 @end smallexample
8451 @end group
8453 @c [fix-ref Date Forms]
8454 @noindent
8455 There will be 1943 leap years before the year 10001.  (Assuming,
8456 of course, that the algorithm for computing leap years remains
8457 unchanged for that long.  @xref{Date Forms}, for some interesting
8458 background information in that regard.)
8460 @node Types Answer 7, Types Answer 8, Types Answer 6, Answers to Exercises
8461 @subsection Types Tutorial Exercise 7
8463 @noindent
8464 The relative errors must be converted to absolute errors so that
8465 @samp{+/-} notation may be used.
8467 @group
8468 @smallexample
8469 1:  1.              2:  1.
8470     .               1:  0.2
8471                         .
8473     20 RET .05 *        4 RET .05 *
8474 @end smallexample
8475 @end group
8477 Now we simply chug through the formula.
8479 @group
8480 @smallexample
8481 1:  19.7392088022    1:  394.78 +/- 19.739    1:  6316.5 +/- 706.21
8482     .                    .                        .
8484     2 P 2 ^ *            20 p 1 *                 4 p .2 RET 2 ^ *
8485 @end smallexample
8486 @end group
8488 It turns out the @kbd{v u} command will unpack an error form as
8489 well as a vector.  This saves us some retyping of numbers.
8491 @group
8492 @smallexample
8493 3:  6316.5 +/- 706.21     2:  6316.5 +/- 706.21
8494 2:  6316.5                1:  0.1118
8495 1:  706.21                    .
8496     .
8498     RET v u                   TAB /
8499 @end smallexample
8500 @end group
8502 @noindent
8503 Thus the volume is 6316 cubic centimeters, within about 11 percent.
8505 @node Types Answer 8, Types Answer 9, Types Answer 7, Answers to Exercises
8506 @subsection Types Tutorial Exercise 8
8508 @noindent
8509 The first answer is pretty simple:  @samp{1 / (0 .. 10) = (0.1 .. inf)}.
8510 Since a number in the interval @samp{(0 .. 10)} can get arbitrarily
8511 close to zero, its reciprocal can get arbitrarily large, so the answer
8512 is an interval that effectively means, ``any number greater than 0.1''
8513 but with no upper bound.
8515 The second answer, similarly, is @samp{1 / (-10 .. 0) = (-inf .. -0.1)}.
8517 Calc normally treats division by zero as an error, so that the formula
8518 @w{@samp{1 / 0}} is left unsimplified.  Our third problem,
8519 @w{@samp{1 / [0 .. 10]}}, also (potentially) divides by zero because zero
8520 is now a member of the interval.  So Calc leaves this one unevaluated, too.
8522 If you turn on ``infinite'' mode by pressing @kbd{m i}, you will
8523 instead get the answer @samp{[0.1 .. inf]}, which includes infinity
8524 as a possible value.
8526 The fourth calculation, @samp{1 / (-10 .. 10)}, has the same problem.
8527 Zero is buried inside the interval, but it's still a possible value.
8528 It's not hard to see that the actual result of @samp{1 / (-10 .. 10)}
8529 will be either greater than @i{0.1}, or less than @i{-0.1}.  Thus
8530 the interval goes from minus infinity to plus infinity, with a ``hole''
8531 in it from @i{-0.1} to @i{0.1}.  Calc doesn't have any way to
8532 represent this, so it just reports @samp{[-inf .. inf]} as the answer.
8533 It may be disappointing to hear ``the answer lies somewhere between
8534 minus infinity and plus infinity, inclusive,'' but that's the best
8535 that interval arithmetic can do in this case.
8537 @node Types Answer 9, Types Answer 10, Types Answer 8, Answers to Exercises
8538 @subsection Types Tutorial Exercise 9
8540 @group
8541 @smallexample
8542 1:  [-3 .. 3]       2:  [-3 .. 3]     2:  [0 .. 9]
8543     .               1:  [0 .. 9]      1:  [-9 .. 9]
8544                         .                 .
8546     [ 3 n .. 3 ]        RET 2 ^           TAB RET *
8547 @end smallexample
8548 @end group
8550 @noindent
8551 In the first case the result says, ``if a number is between @i{-3} and
8552 3, its square is between 0 and 9.''  The second case says, ``the product
8553 of two numbers each between @i{-3} and 3 is between @i{-9} and 9.''
8555 An interval form is not a number; it is a symbol that can stand for
8556 many different numbers.  Two identical-looking interval forms can stand
8557 for different numbers.
8559 The same issue arises when you try to square an error form.
8561 @node Types Answer 10, Types Answer 11, Types Answer 9, Answers to Exercises
8562 @subsection Types Tutorial Exercise 10
8564 @noindent
8565 Testing the first number, we might arbitrarily choose 17 for @cite{x}.
8567 @group
8568 @smallexample
8569 1:  17 mod 811749613   2:  17 mod 811749613   1:  533694123 mod 811749613
8570     .                      811749612              .
8571                            .
8573     17 M 811749613 RET     811749612              ^
8574 @end smallexample
8575 @end group
8577 @noindent
8578 Since 533694123 is (considerably) different from 1, the number 811749613
8579 must not be prime.
8581 It's awkward to type the number in twice as we did above.  There are
8582 various ways to avoid this, and algebraic entry is one.  In fact, using
8583 a vector mapping operation we can perform several tests at once.  Let's
8584 use this method to test the second number.
8586 @group
8587 @smallexample
8588 2:  [17, 42, 100000]               1:  [1 mod 15485863, 1 mod ... ]
8589 1:  15485863                           .
8590     .
8592  [17 42 100000] 15485863 RET           V M ' ($$ mod $)^($-1) RET
8593 @end smallexample
8594 @end group
8596 @noindent
8597 The result is three ones (modulo @cite{n}), so it's very probable that
8598 15485863 is prime.  (In fact, this number is the millionth prime.)
8600 Note that the functions @samp{($$^($-1)) mod $} or @samp{$$^($-1) % $}
8601 would have been hopelessly inefficient, since they would have calculated
8602 the power using full integer arithmetic.
8604 Calc has a @kbd{k p} command that does primality testing.  For small
8605 numbers it does an exact test; for large numbers it uses a variant
8606 of the Fermat test we used here.  You can use @kbd{k p} repeatedly
8607 to prove that a large integer is prime with any desired probability.
8609 @node Types Answer 11, Types Answer 12, Types Answer 10, Answers to Exercises
8610 @subsection Types Tutorial Exercise 11
8612 @noindent
8613 There are several ways to insert a calculated number into an HMS form.
8614 One way to convert a number of seconds to an HMS form is simply to
8615 multiply the number by an HMS form representing one second:
8617 @group
8618 @smallexample
8619 1:  31415926.5359     2:  31415926.5359     1:  8726@@ 38' 46.5359"
8620     .                 1:  0@@ 0' 1"              .
8621                           .
8623     P 1e7 *               0@@ 0' 1"              *
8625 @end smallexample
8626 @end group
8627 @noindent
8628 @group
8629 @smallexample
8630 2:  8726@@ 38' 46.5359"             1:  6@@ 6' 2.5359" mod 24@@ 0' 0"
8631 1:  15@@ 27' 16" mod 24@@ 0' 0"          .
8632     .
8634     x time RET                         +
8635 @end smallexample
8636 @end group
8638 @noindent
8639 It will be just after six in the morning.
8641 The algebraic @code{hms} function can also be used to build an
8642 HMS form:
8644 @group
8645 @smallexample
8646 1:  hms(0, 0, 10000000. pi)       1:  8726@@ 38' 46.5359"
8647     .                                 .
8649   ' hms(0, 0, 1e7 pi) RET             =
8650 @end smallexample
8651 @end group
8653 @noindent
8654 The @kbd{=} key is necessary to evaluate the symbol @samp{pi} to
8655 the actual number 3.14159...
8657 @node Types Answer 12, Types Answer 13, Types Answer 11, Answers to Exercises
8658 @subsection Types Tutorial Exercise 12
8660 @noindent
8661 As we recall, there are 17 songs of about 2 minutes and 47 seconds
8662 each.
8664 @group
8665 @smallexample
8666 2:  0@@ 2' 47"                    1:  [0@@ 3' 7" .. 0@@ 3' 47"]
8667 1:  [0@@ 0' 20" .. 0@@ 1' 0"]          .
8668     .
8670     [ 0@@ 20" .. 0@@ 1' ]              +
8672 @end smallexample
8673 @end group
8674 @noindent
8675 @group
8676 @smallexample
8677 1:  [0@@ 52' 59." .. 1@@ 4' 19."]
8678     .
8680     17 *
8681 @end smallexample
8682 @end group
8684 @noindent
8685 No matter how long it is, the album will fit nicely on one CD.
8687 @node Types Answer 13, Types Answer 14, Types Answer 12, Answers to Exercises
8688 @subsection Types Tutorial Exercise 13
8690 @noindent
8691 Type @kbd{' 1 yr RET u c s RET}.  The answer is 31557600 seconds.
8693 @node Types Answer 14, Types Answer 15, Types Answer 13, Answers to Exercises
8694 @subsection Types Tutorial Exercise 14
8696 @noindent
8697 How long will it take for a signal to get from one end of the computer
8698 to the other?
8700 @group
8701 @smallexample
8702 1:  m / c         1:  3.3356 ns
8703     .                 .
8705  ' 1 m / c RET        u c ns RET
8706 @end smallexample
8707 @end group
8709 @noindent
8710 (Recall, @samp{c} is a ``unit'' corresponding to the speed of light.)
8712 @group
8713 @smallexample
8714 1:  3.3356 ns     1:  0.81356 ns / ns     1:  0.81356
8715 2:  4.1 ns            .                       .
8716     .
8718   ' 4.1 ns RET        /                       u s
8719 @end smallexample
8720 @end group
8722 @noindent
8723 Thus a signal could take up to 81 percent of a clock cycle just to
8724 go from one place to another inside the computer, assuming the signal
8725 could actually attain the full speed of light.  Pretty tight!
8727 @node Types Answer 15, Algebra Answer 1, Types Answer 14, Answers to Exercises
8728 @subsection Types Tutorial Exercise 15
8730 @noindent
8731 The speed limit is 55 miles per hour on most highways.  We want to
8732 find the ratio of Sam's speed to the US speed limit.
8734 @group
8735 @smallexample
8736 1:  55 mph         2:  55 mph           3:  11 hr mph / yd
8737     .              1:  5 yd / hr            .
8738                        .
8740   ' 55 mph RET       ' 5 yd/hr RET          /
8741 @end smallexample
8742 @end group
8744 The @kbd{u s} command cancels out these units to get a plain
8745 number.  Now we take the logarithm base two to find the final
8746 answer, assuming that each successive pill doubles his speed.
8748 @group
8749 @smallexample
8750 1:  19360.       2:  19360.       1:  14.24
8751     .            1:  2                .
8752                      .
8754     u s              2                B
8755 @end smallexample
8756 @end group
8758 @noindent
8759 Thus Sam can take up to 14 pills without a worry.
8761 @node Algebra Answer 1, Algebra Answer 2, Types Answer 15, Answers to Exercises
8762 @subsection Algebra Tutorial Exercise 1
8764 @noindent
8765 @c [fix-ref Declarations]
8766 The result @samp{sqrt(x)^2} is simplified back to @cite{x} by the
8767 Calculator, but @samp{sqrt(x^2)} is not.  (Consider what happens
8768 if @w{@cite{x = -4}}.)  If @cite{x} is real, this formula could be
8769 simplified to @samp{abs(x)}, but for general complex arguments even
8770 that is not safe.  (@xref{Declarations}, for a way to tell Calc
8771 that @cite{x} is known to be real.)
8773 @node Algebra Answer 2, Algebra Answer 3, Algebra Answer 1, Answers to Exercises
8774 @subsection Algebra Tutorial Exercise 2
8776 @noindent
8777 Suppose our roots are @cite{[a, b, c]}.  We want a polynomial which
8778 is zero when @cite{x} is any of these values.  The trivial polynomial
8779 @cite{x-a} is zero when @cite{x=a}, so the product @cite{(x-a)(x-b)(x-c)}
8780 will do the job.  We can use @kbd{a c x} to write this in a more
8781 familiar form.
8783 @group
8784 @smallexample
8785 1:  34 x - 24 x^3          1:  [1.19023, -1.19023, 0]
8786     .                          .
8788     r 2                        a P x RET
8790 @end smallexample
8791 @end group
8792 @noindent
8793 @group
8794 @smallexample
8795 1:  [x - 1.19023, x + 1.19023, x]     1:  (x - 1.19023) (x + 1.19023) x
8796     .                                     .
8798     V M ' x-$ RET                         V R *
8800 @end smallexample
8801 @end group
8802 @noindent
8803 @group
8804 @smallexample
8805 1:  x^3 - 1.41666 x        1:  34 x - 24 x^3
8806     .                          .
8808     a c x RET                  24 n *  a x
8809 @end smallexample
8810 @end group
8812 @noindent
8813 Sure enough, our answer (multiplied by a suitable constant) is the
8814 same as the original polynomial.
8816 @node Algebra Answer 3, Algebra Answer 4, Algebra Answer 2, Answers to Exercises
8817 @subsection Algebra Tutorial Exercise 3
8819 @group
8820 @smallexample
8821 1:  x sin(pi x)         1:  (sin(pi x) - pi x cos(pi x)) / pi^2
8822     .                       .
8824   ' x sin(pi x) RET   m r   a i x RET
8826 @end smallexample
8827 @end group
8828 @noindent
8829 @group
8830 @smallexample
8831 1:  [y, 1]
8832 2:  (sin(pi x) - pi x cos(pi x)) / pi^2
8833     .
8835   ' [y,1] RET TAB
8837 @end smallexample
8838 @end group
8839 @noindent
8840 @group
8841 @smallexample
8842 1:  [(sin(pi y) - pi y cos(pi y)) / pi^2, (sin(pi) - pi cos(pi)) / pi^2]
8843     .
8845     V M $ RET
8847 @end smallexample
8848 @end group
8849 @noindent
8850 @group
8851 @smallexample
8852 1:  (sin(pi y) - pi y cos(pi y)) / pi^2 + (pi cos(pi) - sin(pi)) / pi^2
8853     .
8855     V R -
8857 @end smallexample
8858 @end group
8859 @noindent
8860 @group
8861 @smallexample
8862 1:  (sin(3.14159 y) - 3.14159 y cos(3.14159 y)) / 9.8696 - 0.3183
8863     .
8865     =
8867 @end smallexample
8868 @end group
8869 @noindent
8870 @group
8871 @smallexample
8872 1:  [0., -0.95493, 0.63662, -1.5915, 1.2732]
8873     .
8875     v x 5 RET  TAB  V M $ RET
8876 @end smallexample
8877 @end group
8879 @node Algebra Answer 4, Rewrites Answer 1, Algebra Answer 3, Answers to Exercises
8880 @subsection Algebra Tutorial Exercise 4
8882 @noindent
8883 The hard part is that @kbd{V R +} is no longer sufficient to add up all
8884 the contributions from the slices, since the slices have varying
8885 coefficients.  So first we must come up with a vector of these
8886 coefficients.  Here's one way:
8888 @group
8889 @smallexample
8890 2:  -1                 2:  3                    1:  [4, 2, ..., 4]
8891 1:  [1, 2, ..., 9]     1:  [-1, 1, ..., -1]         .
8892     .                      .
8894     1 n v x 9 RET          V M ^  3 TAB             -
8896 @end smallexample
8897 @end group
8898 @noindent
8899 @group
8900 @smallexample
8901 1:  [4, 2, ..., 4, 1]      1:  [1, 4, 2, ..., 4, 1]
8902     .                          .
8904     1 |                        1 TAB |
8905 @end smallexample
8906 @end group
8908 @noindent
8909 Now we compute the function values.  Note that for this method we need
8910 eleven values, including both endpoints of the desired interval.
8912 @group
8913 @smallexample
8914 2:  [1, 4, 2, ..., 4, 1]
8915 1:  [1, 1.1, 1.2,  ...  , 1.8, 1.9, 2.]
8916     .
8918  11 RET 1 RET .1 RET  C-u v x
8920 @end smallexample
8921 @end group
8922 @noindent
8923 @group
8924 @smallexample
8925 2:  [1, 4, 2, ..., 4, 1]
8926 1:  [0., 0.084941, 0.16993, ... ]
8927     .
8929     ' sin(x) ln(x) RET   m r  p 5 RET   V M $ RET
8930 @end smallexample
8931 @end group
8933 @noindent
8934 Once again this calls for @kbd{V M * V R +}; a simple @kbd{*} does the
8935 same thing.
8937 @group
8938 @smallexample
8939 1:  11.22      1:  1.122      1:  0.374
8940     .              .              .
8942     *              .1 *           3 /
8943 @end smallexample
8944 @end group
8946 @noindent
8947 Wow!  That's even better than the result from the Taylor series method.
8949 @node Rewrites Answer 1, Rewrites Answer 2, Algebra Answer 4, Answers to Exercises
8950 @subsection Rewrites Tutorial Exercise 1
8952 @noindent
8953 We'll use Big mode to make the formulas more readable.
8955 @group
8956 @smallexample
8957                                                ___
8958                                           2 + V 2
8959 1:  (2 + sqrt(2)) / (1 + sqrt(2))     1:  --------
8960     .                                          ___
8961                                           1 + V 2
8963                                           .
8965   ' (2+sqrt(2)) / (1+sqrt(2)) RET         d B
8966 @end smallexample
8967 @end group
8969 @noindent
8970 Multiplying by the conjugate helps because @cite{(a+b) (a-b) = a^2 - b^2}.
8972 @group
8973 @smallexample
8974           ___    ___
8975 1:  (2 + V 2 ) (V 2  - 1)
8976     .
8978   a r a/(b+c) := a*(b-c) / (b^2-c^2) RET
8980 @end smallexample
8981 @end group
8982 @noindent
8983 @group
8984 @smallexample
8985          ___                         ___
8986 1:  2 + V 2  - 2                1:  V 2
8987     .                               .
8989   a r a*(b+c) := a*b + a*c          a s
8990 @end smallexample
8991 @end group
8993 @noindent
8994 (We could have used @kbd{a x} instead of a rewrite rule for the
8995 second step.)
8997 The multiply-by-conjugate rule turns out to be useful in many
8998 different circumstances, such as when the denominator involves
8999 sines and cosines or the imaginary constant @code{i}.
9001 @node Rewrites Answer 2, Rewrites Answer 3, Rewrites Answer 1, Answers to Exercises
9002 @subsection Rewrites Tutorial Exercise 2
9004 @noindent
9005 Here is the rule set:
9007 @group
9008 @smallexample
9009 [ fib(n) := fib(n, 1, 1) :: integer(n) :: n >= 1,
9010   fib(1, x, y) := x,
9011   fib(n, x, y) := fib(n-1, y, x+y) ]
9012 @end smallexample
9013 @end group
9015 @noindent
9016 The first rule turns a one-argument @code{fib} that people like to write
9017 into a three-argument @code{fib} that makes computation easier.  The
9018 second rule converts back from three-argument form once the computation
9019 is done.  The third rule does the computation itself.  It basically
9020 says that if @cite{x} and @cite{y} are two consecutive Fibonacci numbers,
9021 then @cite{y} and @cite{x+y} are the next (overlapping) pair of Fibonacci
9022 numbers.
9024 Notice that because the number @cite{n} was ``validated'' by the
9025 conditions on the first rule, there is no need to put conditions on
9026 the other rules because the rule set would never get that far unless
9027 the input were valid.  That further speeds computation, since no
9028 extra conditions need to be checked at every step.
9030 Actually, a user with a nasty sense of humor could enter a bad
9031 three-argument @code{fib} call directly, say, @samp{fib(0, 1, 1)},
9032 which would get the rules into an infinite loop.  One thing that would
9033 help keep this from happening by accident would be to use something like
9034 @samp{ZzFib} instead of @code{fib} as the name of the three-argument
9035 function.
9037 @node Rewrites Answer 3, Rewrites Answer 4, Rewrites Answer 2, Answers to Exercises
9038 @subsection Rewrites Tutorial Exercise 3
9040 @noindent
9041 He got an infinite loop.  First, Calc did as expected and rewrote
9042 @w{@samp{2 + 3 x}} to @samp{f(2, 3, x)}.  Then it looked for ways to
9043 apply the rule again, and found that @samp{f(2, 3, x)} looks like
9044 @samp{a + b x} with @w{@samp{a = 0}} and @samp{b = 1}, so it rewrote to
9045 @samp{f(0, 1, f(2, 3, x))}.  It then wrapped another @samp{f(0, 1, ...)}
9046 around that, and so on, ad infinitum.  Joe should have used @kbd{M-1 a r}
9047 to make sure the rule applied only once.
9049 (Actually, even the first step didn't work as he expected.  What Calc
9050 really gives for @kbd{M-1 a r} in this situation is @samp{f(3 x, 1, 2)},
9051 treating 2 as the ``variable,'' and @samp{3 x} as a constant being added
9052 to it.  While this may seem odd, it's just as valid a solution as the
9053 ``obvious'' one.  One way to fix this would be to add the condition
9054 @samp{:: variable(x)} to the rule, to make sure the thing that matches
9055 @samp{x} is indeed a variable, or to change @samp{x} to @samp{quote(x)}
9056 on the lefthand side, so that the rule matches the actual variable
9057 @samp{x} rather than letting @samp{x} stand for something else.)
9059 @node Rewrites Answer 4, Rewrites Answer 5, Rewrites Answer 3, Answers to Exercises
9060 @subsection Rewrites Tutorial Exercise 4
9062 @noindent
9063 @c @starindex
9064 @tindex seq
9065 Here is a suitable set of rules to solve the first part of the problem:
9067 @group
9068 @smallexample
9069 [ seq(n, c) := seq(n/2,  c+1) :: n%2 = 0,
9070   seq(n, c) := seq(3n+1, c+1) :: n%2 = 1 :: n > 1 ]
9071 @end smallexample
9072 @end group
9074 Given the initial formula @samp{seq(6, 0)}, application of these
9075 rules produces the following sequence of formulas:
9077 @example
9078 seq( 3, 1)
9079 seq(10, 2)
9080 seq( 5, 3)
9081 seq(16, 4)
9082 seq( 8, 5)
9083 seq( 4, 6)
9084 seq( 2, 7)
9085 seq( 1, 8)
9086 @end example
9088 @noindent
9089 whereupon neither of the rules match, and rewriting stops.
9091 We can pretty this up a bit with a couple more rules:
9093 @group
9094 @smallexample
9095 [ seq(n) := seq(n, 0),
9096   seq(1, c) := c,
9097   ... ]
9098 @end smallexample
9099 @end group
9101 @noindent
9102 Now, given @samp{seq(6)} as the starting configuration, we get 8
9103 as the result.
9105 The change to return a vector is quite simple:
9107 @group
9108 @smallexample
9109 [ seq(n) := seq(n, []) :: integer(n) :: n > 0,
9110   seq(1, v) := v | 1,
9111   seq(n, v) := seq(n/2,  v | n) :: n%2 = 0,
9112   seq(n, v) := seq(3n+1, v | n) :: n%2 = 1 ]
9113 @end smallexample
9114 @end group
9116 @noindent
9117 Given @samp{seq(6)}, the result is @samp{[6, 3, 10, 5, 16, 8, 4, 2, 1]}.
9119 Notice that the @cite{n > 1} guard is no longer necessary on the last
9120 rule since the @cite{n = 1} case is now detected by another rule.
9121 But a guard has been added to the initial rule to make sure the
9122 initial value is suitable before the computation begins.
9124 While still a good idea, this guard is not as vitally important as it
9125 was for the @code{fib} function, since calling, say, @samp{seq(x, [])}
9126 will not get into an infinite loop.  Calc will not be able to prove
9127 the symbol @samp{x} is either even or odd, so none of the rules will
9128 apply and the rewrites will stop right away.
9130 @node Rewrites Answer 5, Rewrites Answer 6, Rewrites Answer 4, Answers to Exercises
9131 @subsection Rewrites Tutorial Exercise 5
9133 @noindent
9134 @c @starindex
9135 @tindex nterms
9136 If @cite{x} is the sum @cite{a + b}, then `@t{nterms(}@i{x}@t{)}' must
9137 be `@t{nterms(}@i{a}@t{)}' plus `@t{nterms(}@i{b}@t{)}'.  If @cite{x}
9138 is not a sum, then `@t{nterms(}@i{x}@t{)}' = 1.
9140 @group
9141 @smallexample
9142 [ nterms(a + b) := nterms(a) + nterms(b),
9143   nterms(x)     := 1 ]
9144 @end smallexample
9145 @end group
9147 @noindent
9148 Here we have taken advantage of the fact that earlier rules always
9149 match before later rules; @samp{nterms(x)} will only be tried if we
9150 already know that @samp{x} is not a sum.
9152 @node Rewrites Answer 6, Rewrites Answer 7, Rewrites Answer 5, Answers to Exercises
9153 @subsection Rewrites Tutorial Exercise 6
9155 Just put the rule @samp{0^0 := 1} into @code{EvalRules}.  For example,
9156 before making this definition we have:
9158 @group
9159 @smallexample
9160 2:  [-2, -1, 0, 1, 2]                1:  [1, 1, 0^0, 1, 1]
9161 1:  0                                    .
9162     .
9164     v x 5 RET  3 -  0                    V M ^
9165 @end smallexample
9166 @end group
9168 @noindent
9169 But then:
9171 @group
9172 @smallexample
9173 2:  [-2, -1, 0, 1, 2]                1:  [1, 1, 1, 1, 1]
9174 1:  0                                    .
9175     .
9177     U  ' 0^0:=1 RET s t EvalRules RET    V M ^
9178 @end smallexample
9179 @end group
9181 Perhaps more surprisingly, this rule still works with infinite mode
9182 turned on.  Calc tries @code{EvalRules} before any built-in rules for
9183 a function.  This allows you to override the default behavior of any
9184 Calc feature:  Even though Calc now wants to evaluate @cite{0^0} to
9185 @code{nan}, your rule gets there first and evaluates it to 1 instead.
9187 Just for kicks, try adding the rule @code{2+3 := 6} to @code{EvalRules}.
9188 What happens?  (Be sure to remove this rule afterward, or you might get
9189 a nasty surprise when you use Calc to balance your checkbook!)
9191 @node Rewrites Answer 7, Programming Answer 1, Rewrites Answer 6, Answers to Exercises
9192 @subsection Rewrites Tutorial Exercise 7
9194 @noindent
9195 Here is a rule set that will do the job:
9197 @group
9198 @smallexample
9199 [ a*(b + c) := a*b + a*c,
9200   opt(a) O(x^n) + opt(b) O(x^m) := O(x^n) :: n <= m
9201      :: constant(a) :: constant(b),
9202   opt(a) O(x^n) + opt(b) x^m := O(x^n) :: n <= m
9203      :: constant(a) :: constant(b),
9204   a O(x^n) := O(x^n) :: constant(a),
9205   x^opt(m) O(x^n) := O(x^(n+m)),
9206   O(x^n) O(x^m) := O(x^(n+m)) ]
9207 @end smallexample
9208 @end group
9210 If we really want the @kbd{+} and @kbd{*} keys to operate naturally
9211 on power series, we should put these rules in @code{EvalRules}.  For
9212 testing purposes, it is better to put them in a different variable,
9213 say, @code{O}, first.
9215 The first rule just expands products of sums so that the rest of the
9216 rules can assume they have an expanded-out polynomial to work with.
9217 Note that this rule does not mention @samp{O} at all, so it will
9218 apply to any product-of-sum it encounters---this rule may surprise
9219 you if you put it into @code{EvalRules}!
9221 In the second rule, the sum of two O's is changed to the smaller O.
9222 The optional constant coefficients are there mostly so that
9223 @samp{O(x^2) - O(x^3)} and @samp{O(x^3) - O(x^2)} are handled
9224 as well as @samp{O(x^2) + O(x^3)}.
9226 The third rule absorbs higher powers of @samp{x} into O's.
9228 The fourth rule says that a constant times a negligible quantity
9229 is still negligible.  (This rule will also match @samp{O(x^3) / 4},
9230 with @samp{a = 1/4}.)
9232 The fifth rule rewrites, for example, @samp{x^2 O(x^3)} to @samp{O(x^5)}.
9233 (It is easy to see that if one of these forms is negligible, the other
9234 is, too.)  Notice the @samp{x^opt(m)} to pick up terms like
9235 @w{@samp{x O(x^3)}}.  Optional powers will match @samp{x} as @samp{x^1}
9236 but not 1 as @samp{x^0}.  This turns out to be exactly what we want here.
9238 The sixth rule is the corresponding rule for products of two O's.
9240 Another way to solve this problem would be to create a new ``data type''
9241 that represents truncated power series.  We might represent these as
9242 function calls @samp{series(@var{coefs}, @var{x})} where @var{coefs} is
9243 a vector of coefficients for @cite{x^0}, @cite{x^1}, @cite{x^2}, and so
9244 on.  Rules would exist for sums and products of such @code{series}
9245 objects, and as an optional convenience could also know how to combine a
9246 @code{series} object with a normal polynomial.  (With this, and with a
9247 rule that rewrites @samp{O(x^n)} to the equivalent @code{series} form,
9248 you could still enter power series in exactly the same notation as
9249 before.)  Operations on such objects would probably be more efficient,
9250 although the objects would be a bit harder to read.
9252 @c [fix-ref Compositions]
9253 Some other symbolic math programs provide a power series data type
9254 similar to this.  Mathematica, for example, has an object that looks
9255 like @samp{PowerSeries[@var{x}, @var{x0}, @var{coefs}, @var{nmin},
9256 @var{nmax}, @var{den}]}, where @var{x0} is the point about which the
9257 power series is taken (we've been assuming this was always zero),
9258 and @var{nmin}, @var{nmax}, and @var{den} allow pseudo-power-series
9259 with fractional or negative powers.  Also, the @code{PowerSeries}
9260 objects have a special display format that makes them look like
9261 @samp{2 x^2 + O(x^4)} when they are printed out.  (@xref{Compositions},
9262 for a way to do this in Calc, although for something as involved as
9263 this it would probably be better to write the formatting routine
9264 in Lisp.)
9266 @node Programming Answer 1, Programming Answer 2, Rewrites Answer 7, Answers to Exercises
9267 @subsection Programming Tutorial Exercise 1
9269 @noindent
9270 Just enter the formula @samp{ninteg(sin(t)/t, t, 0, x)}, type
9271 @kbd{Z F}, and answer the questions.  Since this formula contains two
9272 variables, the default argument list will be @samp{(t x)}.  We want to
9273 change this to @samp{(x)} since @cite{t} is really a dummy variable
9274 to be used within @code{ninteg}.
9276 The exact keystrokes are @kbd{Z F s Si RET RET C-b C-b DEL DEL RET y}.
9277 (The @kbd{C-b C-b DEL DEL} are what fix the argument list.)
9279 @node Programming Answer 2, Programming Answer 3, Programming Answer 1, Answers to Exercises
9280 @subsection Programming Tutorial Exercise 2
9282 @noindent
9283 One way is to move the number to the top of the stack, operate on
9284 it, then move it back:  @kbd{C-x ( M-TAB n M-TAB M-TAB C-x )}.
9286 Another way is to negate the top three stack entries, then negate
9287 again the top two stack entries:  @kbd{C-x ( M-3 n M-2 n C-x )}.
9289 Finally, it turns out that a negative prefix argument causes a
9290 command like @kbd{n} to operate on the specified stack entry only,
9291 which is just what we want:  @kbd{C-x ( M-- 3 n C-x )}.
9293 Just for kicks, let's also do it algebraically:
9294 @w{@kbd{C-x ( ' -$$$, $$, $ RET C-x )}}.
9296 @node Programming Answer 3, Programming Answer 4, Programming Answer 2, Answers to Exercises
9297 @subsection Programming Tutorial Exercise 3
9299 @noindent
9300 Each of these functions can be computed using the stack, or using
9301 algebraic entry, whichever way you prefer:
9303 @noindent
9304 Computing @c{$\displaystyle{\sin x \over x}$}
9305 @cite{sin(x) / x}:
9307 Using the stack:  @kbd{C-x (  RET S TAB /  C-x )}.
9309 Using algebraic entry:  @kbd{C-x (  ' sin($)/$ RET  C-x )}.
9311 @noindent
9312 Computing the logarithm:
9314 Using the stack:  @kbd{C-x (  TAB B  C-x )}
9316 Using algebraic entry:  @kbd{C-x (  ' log($,$$) RET  C-x )}.
9318 @noindent
9319 Computing the vector of integers:
9321 Using the stack:  @kbd{C-x (  1 RET 1  C-u v x  C-x )}.  (Recall that
9322 @kbd{C-u v x} takes the vector size, starting value, and increment
9323 from the stack.)
9325 Alternatively:  @kbd{C-x (  ~ v x  C-x )}.  (The @kbd{~} key pops a
9326 number from the stack and uses it as the prefix argument for the
9327 next command.)
9329 Using algebraic entry:  @kbd{C-x (  ' index($) RET  C-x )}.
9331 @node Programming Answer 4, Programming Answer 5, Programming Answer 3, Answers to Exercises
9332 @subsection Programming Tutorial Exercise 4
9334 @noindent
9335 Here's one way:  @kbd{C-x ( RET V R + TAB v l / C-x )}.
9337 @node Programming Answer 5, Programming Answer 6, Programming Answer 4, Answers to Exercises
9338 @subsection Programming Tutorial Exercise 5
9340 @group
9341 @smallexample
9342 2:  1              1:  1.61803398502         2:  1.61803398502
9343 1:  20                 .                     1:  1.61803398875
9344     .                                            .
9346    1 RET 20         Z < & 1 + Z >                I H P
9347 @end smallexample
9348 @end group
9350 @noindent
9351 This answer is quite accurate.
9353 @node Programming Answer 6, Programming Answer 7, Programming Answer 5, Answers to Exercises
9354 @subsection Programming Tutorial Exercise 6
9356 @noindent
9357 Here is the matrix:
9359 @example
9360 [ [ 0, 1 ]   * [a, b] = [b, a + b]
9361   [ 1, 1 ] ]
9362 @end example
9364 @noindent
9365 Thus @samp{[0, 1; 1, 1]^n * [1, 1]} computes Fibonacci numbers @cite{n+1}
9366 and @cite{n+2}.  Here's one program that does the job:
9368 @example
9369 C-x ( ' [0, 1; 1, 1] ^ ($-1) * [1, 1] RET v u DEL C-x )
9370 @end example
9372 @noindent
9373 This program is quite efficient because Calc knows how to raise a
9374 matrix (or other value) to the power @cite{n} in only @c{$\log_2 n$}
9375 @cite{log(n,2)}
9376 steps.  For example, this program can compute the 1000th Fibonacci
9377 number (a 209-digit integer!) in about 10 steps; even though the
9378 @kbd{Z < ... Z >} solution had much simpler steps, it would have
9379 required so many steps that it would not have been practical.
9381 @node Programming Answer 7, Programming Answer 8, Programming Answer 6, Answers to Exercises
9382 @subsection Programming Tutorial Exercise 7
9384 @noindent
9385 The trick here is to compute the harmonic numbers differently, so that
9386 the loop counter itself accumulates the sum of reciprocals.  We use
9387 a separate variable to hold the integer counter.
9389 @group
9390 @smallexample
9391 1:  1          2:  1       1:  .
9392     .          1:  4
9393                    .
9395     1 t 1       1 RET 4      Z ( t 2 r 1 1 + s 1 & Z )
9396 @end smallexample
9397 @end group
9399 @noindent
9400 The body of the loop goes as follows:  First save the harmonic sum
9401 so far in variable 2.  Then delete it from the stack; the for loop
9402 itself will take care of remembering it for us.  Next, recall the
9403 count from variable 1, add one to it, and feed its reciprocal to
9404 the for loop to use as the step value.  The for loop will increase
9405 the ``loop counter'' by that amount and keep going until the
9406 loop counter exceeds 4.
9408 @group
9409 @smallexample
9410 2:  31                  3:  31
9411 1:  3.99498713092       2:  3.99498713092
9412     .                   1:  4.02724519544
9413                             .
9415     r 1 r 2                 RET 31 & +
9416 @end smallexample
9417 @end group
9419 Thus we find that the 30th harmonic number is 3.99, and the 31st
9420 harmonic number is 4.02.
9422 @node Programming Answer 8, Programming Answer 9, Programming Answer 7, Answers to Exercises
9423 @subsection Programming Tutorial Exercise 8
9425 @noindent
9426 The first step is to compute the derivative @cite{f'(x)} and thus
9427 the formula @c{$\displaystyle{x - {f(x) \over f'(x)}}$}
9428 @cite{x - f(x)/f'(x)}.
9430 (Because this definition is long, it will be repeated in concise form
9431 below.  You can use @w{@kbd{M-# m}} to load it from there.  While you are
9432 entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9433 keystrokes without executing them.  In the following diagrams we'll
9434 pretend Calc actually executed the keystrokes as you typed them,
9435 just for purposes of illustration.)
9437 @group
9438 @smallexample
9439 2:  sin(cos(x)) - 0.5            3:  4.5
9440 1:  4.5                          2:  sin(cos(x)) - 0.5
9441     .                            1:  -(sin(x) cos(cos(x)))
9442                                      .
9444 ' sin(cos(x))-0.5 RET 4.5  m r  C-x ( Z `  TAB RET a d x RET
9446 @end smallexample
9447 @end group
9448 @noindent
9449 @group
9450 @smallexample
9451 2:  4.5
9452 1:  x + (sin(cos(x)) - 0.5) / sin(x) cos(cos(x))
9453     .
9455     /  ' x RET TAB -   t 1
9456 @end smallexample
9457 @end group
9459 Now, we enter the loop.  We'll use a repeat loop with a 20-repetition
9460 limit just in case the method fails to converge for some reason.
9461 (Normally, the @w{@kbd{Z /}} command will stop the loop before all 20
9462 repetitions are done.)
9464 @group
9465 @smallexample
9466 1:  4.5         3:  4.5                     2:  4.5
9467     .           2:  x + (sin(cos(x)) ...    1:  5.24196456928
9468                 1:  4.5                         .
9469                     .
9471   20 Z <          RET r 1 TAB                 s l x RET
9472 @end smallexample
9473 @end group
9475 This is the new guess for @cite{x}.  Now we compare it with the
9476 old one to see if we've converged.
9478 @group
9479 @smallexample
9480 3:  5.24196     2:  5.24196     1:  5.24196     1:  5.26345856348
9481 2:  5.24196     1:  0               .               .
9482 1:  4.5             .
9483     .
9485   RET M-TAB         a =             Z /             Z > Z ' C-x )
9486 @end smallexample
9487 @end group
9489 The loop converges in just a few steps to this value.  To check
9490 the result, we can simply substitute it back into the equation.
9492 @group
9493 @smallexample
9494 2:  5.26345856348
9495 1:  0.499999999997
9496     .
9498  RET ' sin(cos($)) RET
9499 @end smallexample
9500 @end group
9502 Let's test the new definition again:
9504 @group
9505 @smallexample
9506 2:  x^2 - 9           1:  3.
9507 1:  1                     .
9508     .
9510   ' x^2-9 RET 1           X
9511 @end smallexample
9512 @end group
9514 Once again, here's the full Newton's Method definition:
9516 @group
9517 @example
9518 C-x ( Z `  TAB RET a d x RET  /  ' x RET TAB -  t 1
9519            20 Z <  RET r 1 TAB  s l x RET
9520                    RET M-TAB  a =  Z /
9521               Z >
9522       Z '
9523 C-x )
9524 @end example
9525 @end group
9527 @c [fix-ref Nesting and Fixed Points]
9528 It turns out that Calc has a built-in command for applying a formula
9529 repeatedly until it converges to a number.  @xref{Nesting and Fixed Points},
9530 to see how to use it.
9532 @c [fix-ref Root Finding]
9533 Also, of course, @kbd{a R} is a built-in command that uses Newton's
9534 method (among others) to look for numerical solutions to any equation.
9535 @xref{Root Finding}.
9537 @node Programming Answer 9, Programming Answer 10, Programming Answer 8, Answers to Exercises
9538 @subsection Programming Tutorial Exercise 9
9540 @noindent
9541 The first step is to adjust @cite{z} to be greater than 5.  A simple
9542 ``for'' loop will do the job here.  If @cite{z} is less than 5, we
9543 reduce the problem using @c{$\psi(z) = \psi(z+1) - 1/z$}
9544 @cite{psi(z) = psi(z+1) - 1/z}.  We go
9545 on to compute @c{$\psi(z+1)$}
9546 @cite{psi(z+1)}, and remember to add back a factor of
9547 @cite{-1/z} when we're done.  This step is repeated until @cite{z > 5}.
9549 (Because this definition is long, it will be repeated in concise form
9550 below.  You can use @w{@kbd{M-# m}} to load it from there.  While you are
9551 entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9552 keystrokes without executing them.  In the following diagrams we'll
9553 pretend Calc actually executed the keystrokes as you typed them,
9554 just for purposes of illustration.)
9556 @group
9557 @smallexample
9558 1:  1.             1:  1.
9559     .                  .
9561  1.0 RET       C-x ( Z `  s 1  0 t 2
9562 @end smallexample
9563 @end group
9565 Here, variable 1 holds @cite{z} and variable 2 holds the adjustment
9566 factor.  If @cite{z < 5}, we use a loop to increase it.
9568 (By the way, we started with @samp{1.0} instead of the integer 1 because
9569 otherwise the calculation below will try to do exact fractional arithmetic,
9570 and will never converge because fractions compare equal only if they
9571 are exactly equal, not just equal to within the current precision.)
9573 @group
9574 @smallexample
9575 3:  1.      2:  1.       1:  6.
9576 2:  1.      1:  1            .
9577 1:  5           .
9578     .
9580   RET 5        a <    Z [  5 Z (  & s + 2  1 s + 1  1 Z ) r 1  Z ]
9581 @end smallexample
9582 @end group
9584 Now we compute the initial part of the sum:  @c{$\ln z - {1 \over 2z}$}
9585 @cite{ln(z) - 1/2z}
9586 minus the adjustment factor.
9588 @group
9589 @smallexample
9590 2:  1.79175946923      2:  1.7084261359      1:  -0.57490719743
9591 1:  0.0833333333333    1:  2.28333333333         .
9592     .                      .
9594     L  r 1 2 * &           -  r 2                -
9595 @end smallexample
9596 @end group
9598 Now we evaluate the series.  We'll use another ``for'' loop counting
9599 up the value of @cite{2 n}.  (Calc does have a summation command,
9600 @kbd{a +}, but we'll use loops just to get more practice with them.)
9602 @group
9603 @smallexample
9604 3:  -0.5749       3:  -0.5749        4:  -0.5749      2:  -0.5749
9605 2:  2             2:  1:6            3:  1:6          1:  2.3148e-3
9606 1:  40            1:  2              2:  2                .
9607     .                 .              1:  36.
9608                                          .
9610    2 RET 40        Z ( RET k b TAB     RET r 1 TAB ^      * /
9612 @end smallexample
9613 @end group
9614 @noindent
9615 @group
9616 @smallexample
9617 3:  -0.5749       3:  -0.5772      2:  -0.5772     1:  -0.577215664892
9618 2:  -0.5749       2:  -0.5772      1:  0               .
9619 1:  2.3148e-3     1:  -0.5749          .
9620     .                 .
9622   TAB RET M-TAB       - RET M-TAB      a =     Z /    2  Z )  Z ' C-x )
9623 @end smallexample
9624 @end group
9626 This is the value of @c{$-\gamma$}
9627 @cite{- gamma}, with a slight bit of roundoff error.
9628 To get a full 12 digits, let's use a higher precision:
9630 @group
9631 @smallexample
9632 2:  -0.577215664892      2:  -0.577215664892
9633 1:  1.                   1:  -0.577215664901532
9635     1. RET                   p 16 RET X
9636 @end smallexample
9637 @end group
9639 Here's the complete sequence of keystrokes:
9641 @group
9642 @example
9643 C-x ( Z `  s 1  0 t 2
9644            RET 5 a <  Z [  5 Z (  & s + 2  1 s + 1  1 Z ) r 1  Z ]
9645            L r 1 2 * & - r 2 -
9646            2 RET 40  Z (  RET k b TAB RET r 1 TAB ^ * /
9647                           TAB RET M-TAB - RET M-TAB a = Z /
9648                   2  Z )
9649       Z '
9650 C-x )
9651 @end example
9652 @end group
9654 @node Programming Answer 10, Programming Answer 11, Programming Answer 9, Answers to Exercises
9655 @subsection Programming Tutorial Exercise 10
9657 @noindent
9658 Taking the derivative of a term of the form @cite{x^n} will produce
9659 a term like @c{$n x^{n-1}$}
9660 @cite{n x^(n-1)}.  Taking the derivative of a constant
9661 produces zero.  From this it is easy to see that the @cite{n}th
9662 derivative of a polynomial, evaluated at @cite{x = 0}, will equal the
9663 coefficient on the @cite{x^n} term times @cite{n!}.
9665 (Because this definition is long, it will be repeated in concise form
9666 below.  You can use @w{@kbd{M-# m}} to load it from there.  While you are
9667 entering a @kbd{Z ` Z '} body in a macro, Calc simply collects
9668 keystrokes without executing them.  In the following diagrams we'll
9669 pretend Calc actually executed the keystrokes as you typed them,
9670 just for purposes of illustration.)
9672 @group
9673 @smallexample
9674 2:  5 x^4 + (x + 1)^2          3:  5 x^4 + (x + 1)^2
9675 1:  6                          2:  0
9676     .                          1:  6
9677                                    .
9679   ' 5 x^4 + (x+1)^2 RET 6        C-x ( Z `  [ ] t 1  0 TAB
9680 @end smallexample
9681 @end group
9683 @noindent
9684 Variable 1 will accumulate the vector of coefficients.
9686 @group
9687 @smallexample
9688 2:  0              3:  0                  2:  5 x^4 + ...
9689 1:  5 x^4 + ...    2:  5 x^4 + ...        1:  1
9690     .              1:  1                      .
9691                        .
9693    Z ( TAB         RET 0 s l x RET            M-TAB ! /  s | 1
9694 @end smallexample
9695 @end group
9697 @noindent
9698 Note that @kbd{s | 1} appends the top-of-stack value to the vector
9699 in a variable; it is completely analogous to @kbd{s + 1}.  We could
9700 have written instead, @kbd{r 1 TAB | t 1}.
9702 @group
9703 @smallexample
9704 1:  20 x^3 + 2 x + 2      1:  0         1:  [1, 2, 1, 0, 5, 0, 0]
9705     .                         .             .
9707     a d x RET                 1 Z )         DEL r 1  Z ' C-x )
9708 @end smallexample
9709 @end group
9711 To convert back, a simple method is just to map the coefficients
9712 against a table of powers of @cite{x}.
9714 @group
9715 @smallexample
9716 2:  [1, 2, 1, 0, 5, 0, 0]    2:  [1, 2, 1, 0, 5, 0, 0]
9717 1:  6                        1:  [0, 1, 2, 3, 4, 5, 6]
9718     .                            .
9720     6 RET                        1 + 0 RET 1 C-u v x
9722 @end smallexample
9723 @end group
9724 @noindent
9725 @group
9726 @smallexample
9727 2:  [1, 2, 1, 0, 5, 0, 0]    2:  1 + 2 x + x^2 + 5 x^4
9728 1:  [1, x, x^2, x^3, ... ]       .
9729     .
9731     ' x RET TAB V M ^            *
9732 @end smallexample
9733 @end group
9735 Once again, here are the whole polynomial to/from vector programs:
9737 @group
9738 @example
9739 C-x ( Z `  [ ] t 1  0 TAB
9740            Z (  TAB RET 0 s l x RET M-TAB ! /  s | 1
9741                 a d x RET
9742          1 Z ) r 1
9743       Z '
9744 C-x )
9746 C-x (  1 + 0 RET 1 C-u v x ' x RET TAB V M ^ *  C-x )
9747 @end example
9748 @end group
9750 @node Programming Answer 11, Programming Answer 12, Programming Answer 10, Answers to Exercises
9751 @subsection Programming Tutorial Exercise 11
9753 @noindent
9754 First we define a dummy program to go on the @kbd{z s} key.  The true
9755 @w{@kbd{z s}} key is supposed to take two numbers from the stack and
9756 return one number, so @kbd{DEL} as a dummy definition will make
9757 sure the stack comes out right.
9759 @group
9760 @smallexample
9761 2:  4          1:  4                         2:  4
9762 1:  2              .                         1:  2
9763     .                                            .
9765   4 RET 2       C-x ( DEL C-x )  Z K s RET       2
9766 @end smallexample
9767 @end group
9769 The last step replaces the 2 that was eaten during the creation
9770 of the dummy @kbd{z s} command.  Now we move on to the real
9771 definition.  The recurrence needs to be rewritten slightly,
9772 to the form @cite{s(n,m) = s(n-1,m-1) - (n-1) s(n-1,m)}.
9774 (Because this definition is long, it will be repeated in concise form
9775 below.  You can use @kbd{M-# m} to load it from there.)
9777 @group
9778 @smallexample
9779 2:  4        4:  4       3:  4       2:  4
9780 1:  2        3:  2       2:  2       1:  2
9781     .        2:  4       1:  0           .
9782              1:  2           .
9783                  .
9785   C-x (       M-2 RET        a =         Z [  DEL DEL 1  Z :
9787 @end smallexample
9788 @end group
9789 @noindent
9790 @group
9791 @smallexample
9792 4:  4       2:  4                     2:  3      4:  3    4:  3    3:  3
9793 3:  2       1:  2                     1:  2      3:  2    3:  2    2:  2
9794 2:  2           .                         .      2:  3    2:  3    1:  3
9795 1:  0                                            1:  2    1:  1        .
9796     .                                                .        .
9798   RET 0   a = Z [  DEL DEL 0  Z :  TAB 1 - TAB   M-2 RET     1 -      z s
9799 @end smallexample
9800 @end group
9802 @noindent
9803 (Note that the value 3 that our dummy @kbd{z s} produces is not correct;
9804 it is merely a placeholder that will do just as well for now.)
9806 @group
9807 @smallexample
9808 3:  3               4:  3           3:  3       2:  3      1:  -6
9809 2:  3               3:  3           2:  3       1:  9          .
9810 1:  2               2:  3           1:  3           .
9811     .               1:  2               .
9812                         .
9814  M-TAB M-TAB     TAB RET M-TAB         z s          *          -
9816 @end smallexample
9817 @end group
9818 @noindent
9819 @group
9820 @smallexample
9821 1:  -6                          2:  4          1:  11      2:  11
9822     .                           1:  2              .       1:  11
9823                                     .                          .
9825   Z ] Z ] C-x )   Z K s RET      DEL 4 RET 2       z s      M-RET k s
9826 @end smallexample
9827 @end group
9829 Even though the result that we got during the definition was highly
9830 bogus, once the definition is complete the @kbd{z s} command gets
9831 the right answers.
9833 Here's the full program once again:
9835 @group
9836 @example
9837 C-x (  M-2 RET a =
9838        Z [  DEL DEL 1
9839        Z :  RET 0 a =
9840             Z [  DEL DEL 0
9841             Z :  TAB 1 - TAB M-2 RET 1 - z s
9842                  M-TAB M-TAB TAB RET M-TAB z s * -
9843             Z ]
9844        Z ]
9845 C-x )
9846 @end example
9847 @end group
9849 You can read this definition using @kbd{M-# m} (@code{read-kbd-macro})
9850 followed by @kbd{Z K s}, without having to make a dummy definition
9851 first, because @code{read-kbd-macro} doesn't need to execute the
9852 definition as it reads it in.  For this reason, @code{M-# m} is often
9853 the easiest way to create recursive programs in Calc.
9855 @node Programming Answer 12, , Programming Answer 11, Answers to Exercises
9856 @subsection Programming Tutorial Exercise 12
9858 @noindent
9859 This turns out to be a much easier way to solve the problem.  Let's
9860 denote Stirling numbers as calls of the function @samp{s}.
9862 First, we store the rewrite rules corresponding to the definition of
9863 Stirling numbers in a convenient variable:
9865 @smallexample
9866 s e StirlingRules RET
9867 [ s(n,n) := 1  :: n >= 0,
9868   s(n,0) := 0  :: n > 0,
9869   s(n,m) := s(n-1,m-1) - (n-1) s(n-1,m) :: n >= m :: m >= 1 ]
9870 C-c C-c
9871 @end smallexample
9873 Now, it's just a matter of applying the rules:
9875 @group
9876 @smallexample
9877 2:  4          1:  s(4, 2)              1:  11
9878 1:  2              .                        .
9879     .
9881   4 RET 2       C-x (  ' s($$,$) RET     a r StirlingRules RET  C-x )
9882 @end smallexample
9883 @end group
9885 As in the case of the @code{fib} rules, it would be useful to put these
9886 rules in @code{EvalRules} and to add a @samp{:: remember} condition to
9887 the last rule.
9889 @c This ends the table-of-contents kludge from above:
9890 @tex
9891 \global\let\chapternofonts=\oldchapternofonts
9892 @end tex
9894 @c [reference]
9896 @node Introduction, Data Types, Tutorial, Top
9897 @chapter Introduction
9899 @noindent
9900 This chapter is the beginning of the Calc reference manual.
9901 It covers basic concepts such as the stack, algebraic and
9902 numeric entry, undo, numeric prefix arguments, etc.
9904 @c [when-split]
9905 @c (Chapter 2, the Tutorial, has been printed in a separate volume.)
9907 @menu
9908 * Basic Commands::
9909 * Help Commands::
9910 * Stack Basics::
9911 * Numeric Entry::
9912 * Algebraic Entry::
9913 * Quick Calculator::
9914 * Keypad Mode::
9915 * Prefix Arguments::
9916 * Undo::
9917 * Error Messages::
9918 * Multiple Calculators::
9919 * Troubleshooting Commands::
9920 @end menu
9922 @node Basic Commands, Help Commands, Introduction, Introduction
9923 @section Basic Commands
9925 @noindent
9926 @pindex calc
9927 @pindex calc-mode
9928 @cindex Starting the Calculator
9929 @cindex Running the Calculator
9930 To start the Calculator in its standard interface, type @kbd{M-x calc}.
9931 By default this creates a pair of small windows, @samp{*Calculator*}
9932 and @samp{*Calc Trail*}.  The former displays the contents of the
9933 Calculator stack and is manipulated exclusively through Calc commands.
9934 It is possible (though not usually necessary) to create several Calc
9935 Mode buffers each of which has an independent stack, undo list, and
9936 mode settings.  There is exactly one Calc Trail buffer; it records a
9937 list of the results of all calculations that have been done.  The
9938 Calc Trail buffer uses a variant of Calc Mode, so Calculator commands
9939 still work when the trail buffer's window is selected.  It is possible
9940 to turn the trail window off, but the @samp{*Calc Trail*} buffer itself
9941 still exists and is updated silently.  @xref{Trail Commands}.@refill
9943 @kindex M-# c
9944 @kindex M-# M-#
9945 @c @mindex @null
9946 @kindex M-# #
9947 In most installations, the @kbd{M-# c} key sequence is a more
9948 convenient way to start the Calculator.  Also, @kbd{M-# M-#} and
9949 @kbd{M-# #} are synonyms for @kbd{M-# c} unless you last used Calc
9950 in its ``keypad'' mode.
9952 @kindex x
9953 @kindex M-x
9954 @pindex calc-execute-extended-command
9955 Most Calc commands use one or two keystrokes.  Lower- and upper-case
9956 letters are distinct.  Commands may also be entered in full @kbd{M-x} form;
9957 for some commands this is the only form.  As a convenience, the @kbd{x}
9958 key (@code{calc-execute-extended-command})
9959 is like @kbd{M-x} except that it enters the initial string @samp{calc-}
9960 for you.  For example, the following key sequences are equivalent:
9961 @kbd{S}, @kbd{M-x calc-sin @key{RET}}, @kbd{x sin @key{RET}}.@refill
9963 @cindex Extensions module
9964 @cindex @file{calc-ext} module
9965 The Calculator exists in many parts.  When you type @kbd{M-# c}, the
9966 Emacs ``auto-load'' mechanism will bring in only the first part, which
9967 contains the basic arithmetic functions.  The other parts will be
9968 auto-loaded the first time you use the more advanced commands like trig
9969 functions or matrix operations.  This is done to improve the response time
9970 of the Calculator in the common case when all you need to do is a
9971 little arithmetic.  If for some reason the Calculator fails to load an
9972 extension module automatically, you can force it to load all the
9973 extensions by using the @kbd{M-# L} (@code{calc-load-everything})
9974 command.  @xref{Mode Settings}.@refill
9976 If you type @kbd{M-x calc} or @kbd{M-# c} with any numeric prefix argument,
9977 the Calculator is loaded if necessary, but it is not actually started.
9978 If the argument is positive, the @file{calc-ext} extensions are also
9979 loaded if necessary.  User-written Lisp code that wishes to make use
9980 of Calc's arithmetic routines can use @samp{(calc 0)} or @samp{(calc 1)}
9981 to auto-load the Calculator.@refill
9983 @kindex M-# b
9984 @pindex full-calc
9985 If you type @kbd{M-# b}, then next time you use @kbd{M-# c} you
9986 will get a Calculator that uses the full height of the Emacs screen.
9987 When full-screen mode is on, @kbd{M-# c} runs the @code{full-calc}
9988 command instead of @code{calc}.  From the Unix shell you can type
9989 @samp{emacs -f full-calc} to start a new Emacs specifically for use
9990 as a calculator.  When Calc is started from the Emacs command line
9991 like this, Calc's normal ``quit'' commands actually quit Emacs itself.
9993 @kindex M-# o
9994 @pindex calc-other-window
9995 The @kbd{M-# o} command is like @kbd{M-# c} except that the Calc
9996 window is not actually selected.  If you are already in the Calc
9997 window, @kbd{M-# o} switches you out of it.  (The regular Emacs
9998 @kbd{C-x o} command would also work for this, but it has a
9999 tendency to drop you into the Calc Trail window instead, which
10000 @kbd{M-# o} takes care not to do.)
10002 @c @mindex M-# q
10003 For one quick calculation, you can type @kbd{M-# q} (@code{quick-calc})
10004 which prompts you for a formula (like @samp{2+3/4}).  The result is
10005 displayed at the bottom of the Emacs screen without ever creating
10006 any special Calculator windows.  @xref{Quick Calculator}.
10008 @c @mindex M-# k
10009 Finally, if you are using the X window system you may want to try
10010 @kbd{M-# k} (@code{calc-keypad}) which runs Calc with a
10011 ``calculator keypad'' picture as well as a stack display.  Click on
10012 the keys with the mouse to operate the calculator.  @xref{Keypad Mode}.
10014 @kindex q
10015 @pindex calc-quit
10016 @cindex Quitting the Calculator
10017 @cindex Exiting the Calculator
10018 The @kbd{q} key (@code{calc-quit}) exits Calc Mode and closes the
10019 Calculator's window(s).  It does not delete the Calculator buffers.
10020 If you type @kbd{M-x calc} again, the Calculator will reappear with the
10021 contents of the stack intact.  Typing @kbd{M-# c} or @kbd{M-# M-#}
10022 again from inside the Calculator buffer is equivalent to executing
10023 @code{calc-quit}; you can think of @kbd{M-# M-#} as toggling the
10024 Calculator on and off.@refill
10026 @kindex M-# x
10027 The @kbd{M-# x} command also turns the Calculator off, no matter which
10028 user interface (standard, Keypad, or Embedded) is currently active.
10029 It also cancels @code{calc-edit} mode if used from there.
10031 @kindex d SPC
10032 @pindex calc-refresh
10033 @cindex Refreshing a garbled display
10034 @cindex Garbled displays, refreshing
10035 The @kbd{d SPC} key sequence (@code{calc-refresh}) redraws the contents
10036 of the Calculator buffer from memory.  Use this if the contents of the
10037 buffer have been damaged somehow.
10039 @c @mindex o
10040 The @kbd{o} key (@code{calc-realign}) moves the cursor back to its
10041 ``home'' position at the bottom of the Calculator buffer.
10043 @kindex <
10044 @kindex >
10045 @pindex calc-scroll-left
10046 @pindex calc-scroll-right
10047 @cindex Horizontal scrolling
10048 @cindex Scrolling
10049 @cindex Wide text, scrolling
10050 The @kbd{<} and @kbd{>} keys are bound to @code{calc-scroll-left} and
10051 @code{calc-scroll-right}.  These are just like the normal horizontal
10052 scrolling commands except that they scroll one half-screen at a time by
10053 default.  (Calc formats its output to fit within the bounds of the
10054 window whenever it can.)@refill
10056 @kindex @{
10057 @kindex @}
10058 @pindex calc-scroll-down
10059 @pindex calc-scroll-up
10060 @cindex Vertical scrolling
10061 The @kbd{@{} and @kbd{@}} keys are bound to @code{calc-scroll-down}
10062 and @code{calc-scroll-up}.  They scroll up or down by one-half the
10063 height of the Calc window.@refill
10065 @kindex M-# 0
10066 @pindex calc-reset
10067 The @kbd{M-# 0} command (@code{calc-reset}; that's @kbd{M-#} followed
10068 by a zero) resets the Calculator to its default state.  This clears
10069 the stack, resets all the modes, clears the caches (@pxref{Caches}),
10070 and so on.  (It does @emph{not} erase the values of any variables.)
10071 With a numeric prefix argument, @kbd{M-# 0} preserves the contents
10072 of the stack but resets everything else.
10074 @pindex calc-version
10075 The @kbd{M-x calc-version} command displays the current version number
10076 of Calc and the name of the person who installed it on your system.
10077 (This information is also present in the @samp{*Calc Trail*} buffer,
10078 and in the output of the @kbd{h h} command.)
10080 @node Help Commands, Stack Basics, Basic Commands, Introduction
10081 @section Help Commands
10083 @noindent
10084 @cindex Help commands
10085 @kindex ?
10086 @pindex calc-help
10087 The @kbd{?} key (@code{calc-help}) displays a series of brief help messages.
10088 Some keys (such as @kbd{b} and @kbd{d}) are prefix keys, like Emacs'
10089 @key{ESC} and @kbd{C-x} prefixes.  You can type
10090 @kbd{?} after a prefix to see a list of commands beginning with that
10091 prefix.  (If the message includes @samp{[MORE]}, press @kbd{?} again
10092 to see additional commands for that prefix.)
10094 @kindex h h
10095 @pindex calc-full-help
10096 The @kbd{h h} (@code{calc-full-help}) command displays all the @kbd{?}
10097 responses at once.  When printed, this makes a nice, compact (three pages)
10098 summary of Calc keystrokes.
10100 In general, the @kbd{h} key prefix introduces various commands that
10101 provide help within Calc.  Many of the @kbd{h} key functions are
10102 Calc-specific analogues to the @kbd{C-h} functions for Emacs help.
10104 @kindex h i
10105 @kindex M-# i
10106 @kindex i
10107 @pindex calc-info
10108 The @kbd{h i} (@code{calc-info}) command runs the Emacs Info system
10109 to read this manual on-line.  This is basically the same as typing
10110 @kbd{C-h i} (the regular way to run the Info system), then, if Info
10111 is not already in the Calc manual, selecting the beginning of the
10112 manual.  The @kbd{M-# i} command is another way to read the Calc
10113 manual; it is different from @kbd{h i} in that it works any time,
10114 not just inside Calc.  The plain @kbd{i} key is also equivalent to
10115 @kbd{h i}, though this key is obsolete and may be replaced with a
10116 different command in a future version of Calc.
10118 @kindex h t
10119 @kindex M-# t
10120 @pindex calc-tutorial
10121 The @kbd{h t} (@code{calc-tutorial}) command runs the Info system on
10122 the Tutorial section of the Calc manual.  It is like @kbd{h i},
10123 except that it selects the starting node of the tutorial rather
10124 than the beginning of the whole manual.  (It actually selects the
10125 node ``Interactive Tutorial'' which tells a few things about
10126 using the Info system before going on to the actual tutorial.)
10127 The @kbd{M-# t} key is equivalent to @kbd{h t} (but it works at
10128 all times).
10130 @kindex h s
10131 @kindex M-# s
10132 @pindex calc-info-summary
10133 The @kbd{h s} (@code{calc-info-summary}) command runs the Info system
10134 on the Summary node of the Calc manual.  @xref{Summary}.  The @kbd{M-# s}
10135 key is equivalent to @kbd{h s}.
10137 @kindex h k
10138 @pindex calc-describe-key
10139 The @kbd{h k} (@code{calc-describe-key}) command looks up a key
10140 sequence in the Calc manual.  For example, @kbd{h k H a S} looks
10141 up the documentation on the @kbd{H a S} (@code{calc-solve-for})
10142 command.  This works by looking up the textual description of
10143 the key(s) in the Key Index of the manual, then jumping to the
10144 node indicated by the index.
10146 Most Calc commands do not have traditional Emacs documentation
10147 strings, since the @kbd{h k} command is both more convenient and
10148 more instructive.  This means the regular Emacs @kbd{C-h k}
10149 (@code{describe-key}) command will not be useful for Calc keystrokes.
10151 @kindex h c
10152 @pindex calc-describe-key-briefly
10153 The @kbd{h c} (@code{calc-describe-key-briefly}) command reads a
10154 key sequence and displays a brief one-line description of it at
10155 the bottom of the screen.  It looks for the key sequence in the
10156 Summary node of the Calc manual; if it doesn't find the sequence
10157 there, it acts just like its regular Emacs counterpart @kbd{C-h c}
10158 (@code{describe-key-briefly}).  For example, @kbd{h c H a S}
10159 gives the description:
10161 @smallexample
10162 H a S runs calc-solve-for:  a `H a S' v  => fsolve(a,v)  (?=notes)
10163 @end smallexample
10165 @noindent
10166 which means the command @kbd{H a S} or @kbd{H M-x calc-solve-for}
10167 takes a value @cite{a} from the stack, prompts for a value @cite{v},
10168 then applies the algebraic function @code{fsolve} to these values.
10169 The @samp{?=notes} message means you can now type @kbd{?} to see
10170 additional notes from the summary that apply to this command.
10172 @kindex h f
10173 @pindex calc-describe-function
10174 The @kbd{h f} (@code{calc-describe-function}) command looks up an
10175 algebraic function or a command name in the Calc manual.  The
10176 prompt initially contains @samp{calcFunc-}; follow this with an
10177 algebraic function name to look up that function in the Function
10178 Index.  Or, backspace and enter a command name beginning with
10179 @samp{calc-} to look it up in the Command Index.  This command
10180 will also look up operator symbols that can appear in algebraic
10181 formulas, like @samp{%} and @samp{=>}.
10183 @kindex h v
10184 @pindex calc-describe-variable
10185 The @kbd{h v} (@code{calc-describe-variable}) command looks up a
10186 variable in the Calc manual.  The prompt initially contains the
10187 @samp{var-} prefix; just add a variable name like @code{pi} or
10188 @code{PlotRejects}.
10190 @kindex h b
10191 @pindex describe-bindings
10192 The @kbd{h b} (@code{calc-describe-bindings}) command is just like
10193 @kbd{C-h b}, except that only local (Calc-related) key bindings are
10194 listed.
10196 @kindex h n
10197 The @kbd{h n} or @kbd{h C-n} (@code{calc-view-news}) command displays
10198 the ``news'' or change history of Calc.  This is kept in the file
10199 @file{README}, which Calc looks for in the same directory as the Calc
10200 source files.
10202 @kindex h C-c
10203 @kindex h C-d
10204 @kindex h C-w
10205 The @kbd{h C-c}, @kbd{h C-d}, and @kbd{h C-w} keys display copying,
10206 distribution, and warranty information about Calc.  These work by
10207 pulling up the appropriate parts of the ``Copying'' or ``Reporting
10208 Bugs'' sections of the manual.
10210 @node Stack Basics, Numeric Entry, Help Commands, Introduction
10211 @section Stack Basics
10213 @noindent
10214 @cindex Stack basics
10215 @c [fix-tut RPN Calculations and the Stack]
10216 Calc uses RPN notation.  If you are not familar with RPN, @pxref{RPN
10217 Tutorial}.
10219 To add the numbers 1 and 2 in Calc you would type the keys:
10220 @kbd{1 @key{RET} 2 +}.
10221 (@key{RET} corresponds to the @key{ENTER} key on most calculators.)
10222 The first three keystrokes ``push'' the numbers 1 and 2 onto the stack.  The
10223 @kbd{+} key always ``pops'' the top two numbers from the stack, adds them,
10224 and pushes the result (3) back onto the stack.  This number is ready for
10225 further calculations:  @kbd{5 -} pushes 5 onto the stack, then pops the
10226 3 and 5, subtracts them, and pushes the result (@i{-2}).@refill
10228 Note that the ``top'' of the stack actually appears at the @emph{bottom}
10229 of the buffer.  A line containing a single @samp{.} character signifies
10230 the end of the buffer; Calculator commands operate on the number(s)
10231 directly above this line.  The @kbd{d t} (@code{calc-truncate-stack})
10232 command allows you to move the @samp{.} marker up and down in the stack;
10233 @pxref{Truncating the Stack}.
10235 @kindex d l
10236 @pindex calc-line-numbering
10237 Stack elements are numbered consecutively, with number 1 being the top of
10238 the stack.  These line numbers are ordinarily displayed on the lefthand side
10239 of the window.  The @kbd{d l} (@code{calc-line-numbering}) command controls
10240 whether these numbers appear.  (Line numbers may be turned off since they
10241 slow the Calculator down a bit and also clutter the display.)
10243 @kindex o
10244 @pindex calc-realign
10245 The unshifted letter @kbd{o} (@code{calc-realign}) command repositions
10246 the cursor to its top-of-stack ``home'' position.  It also undoes any
10247 horizontal scrolling in the window.  If you give it a numeric prefix
10248 argument, it instead moves the cursor to the specified stack element.
10250 The @key{RET} (or equivalent @key{SPC}) key is only required to separate
10251 two consecutive numbers.
10252 (After all, if you typed @kbd{1 2} by themselves the Calculator
10253 would enter the number 12.)  If you press @kbd{RET} or @kbd{SPC} @emph{not}
10254 right after typing a number, the key duplicates the number on the top of
10255 the stack.  @kbd{@key{RET} *} is thus a handy way to square a number.@refill
10257 The @key{DEL} key pops and throws away the top number on the stack.
10258 The @key{TAB} key swaps the top two objects on the stack.
10259 @xref{Stack and Trail}, for descriptions of these and other stack-related
10260 commands.@refill
10262 @node Numeric Entry, Algebraic Entry, Stack Basics, Introduction
10263 @section Numeric Entry
10265 @noindent
10266 @kindex 0-9
10267 @kindex .
10268 @kindex e
10269 @cindex Numeric entry
10270 @cindex Entering numbers
10271 Pressing a digit or other numeric key begins numeric entry using the
10272 minibuffer.  The number is pushed on the stack when you press the @key{RET}
10273 or @key{SPC} keys.  If you press any other non-numeric key, the number is
10274 pushed onto the stack and the appropriate operation is performed.  If
10275 you press a numeric key which is not valid, the key is ignored.
10277 @cindex Minus signs
10278 @cindex Negative numbers, entering
10279 @kindex _
10280 There are three different concepts corresponding to the word ``minus,''
10281 typified by @cite{a-b} (subtraction), @cite{-x}
10282 (change-sign), and @cite{-5} (negative number).  Calc uses three
10283 different keys for these operations, respectively:
10284 @kbd{-}, @kbd{n}, and @kbd{_} (the underscore).  The @kbd{-} key subtracts
10285 the two numbers on the top of the stack.  The @kbd{n} key changes the sign
10286 of the number on the top of the stack or the number currently being entered.
10287 The @kbd{_} key begins entry of a negative number or changes the sign of
10288 the number currently being entered.  The following sequences all enter the
10289 number @i{-5} onto the stack:  @kbd{0 @key{RET} 5 -}, @kbd{5 n @key{RET}},
10290 @kbd{5 @key{RET} n}, @kbd{_ 5 @key{RET}}, @kbd{5 _ @key{RET}}.@refill
10292 Some other keys are active during numeric entry, such as @kbd{#} for
10293 non-decimal numbers, @kbd{:} for fractions, and @kbd{@@} for HMS forms.
10294 These notations are described later in this manual with the corresponding
10295 data types.  @xref{Data Types}.
10297 During numeric entry, the only editing key available is @kbd{DEL}.
10299 @node Algebraic Entry, Quick Calculator, Numeric Entry, Introduction
10300 @section Algebraic Entry
10302 @noindent
10303 @kindex '
10304 @pindex calc-algebraic-entry
10305 @cindex Algebraic notation
10306 @cindex Formulas, entering
10307 Calculations can also be entered in algebraic form.  This is accomplished
10308 by typing the apostrophe key, @kbd{'}, followed by the expression in
10309 standard format:  @kbd{@key{'} 2+3*4 @key{RET}} computes
10310 @c{$2+(3\times4) = 14$}
10311 @cite{2+(3*4) = 14} and pushes that on the stack.  If you wish you can
10312 ignore the RPN aspect of Calc altogether and simply enter algebraic
10313 expressions in this way.  You may want to use @key{DEL} every so often to
10314 clear previous results off the stack.@refill
10316 You can press the apostrophe key during normal numeric entry to switch
10317 the half-entered number into algebraic entry mode.  One reason to do this
10318 would be to use the full Emacs cursor motion and editing keys, which are
10319 available during algebraic entry but not during numeric entry.
10321 In the same vein, during either numeric or algebraic entry you can
10322 press @kbd{`} (backquote) to switch to @code{calc-edit} mode, where
10323 you complete your half-finished entry in a separate buffer.
10324 @xref{Editing Stack Entries}.
10326 @kindex m a
10327 @pindex calc-algebraic-mode
10328 @cindex Algebraic mode
10329 If you prefer algebraic entry, you can use the command @kbd{m a}
10330 (@code{calc-algebraic-mode}) to set Algebraic mode.  In this mode,
10331 digits and other keys that would normally start numeric entry instead
10332 start full algebraic entry; as long as your formula begins with a digit
10333 you can omit the apostrophe.  Open parentheses and square brackets also
10334 begin algebraic entry.  You can still do RPN calculations in this mode,
10335 but you will have to press @key{RET} to terminate every number:
10336 @kbd{2 @key{RET} 3 @key{RET} * 4 @key{RET} +} would accomplish the same
10337 thing as @kbd{2*3+4 @key{RET}}.@refill
10339 @cindex Incomplete algebraic mode
10340 If you give a numeric prefix argument like @kbd{C-u} to the @kbd{m a}
10341 command, it enables Incomplete Algebraic mode; this is like regular
10342 Algebraic mode except that it applies to the @kbd{(} and @kbd{[} keys
10343 only.  Numeric keys still begin a numeric entry in this mode.
10345 @kindex m t
10346 @pindex calc-total-algebraic-mode
10347 @cindex Total algebraic mode
10348 The @kbd{m t} (@code{calc-total-algebraic-mode}) gives you an even
10349 stronger algebraic-entry mode, in which @emph{all} regular letter and
10350 punctuation keys begin algebraic entry.  Use this if you prefer typing
10351 @w{@kbd{sqrt( )}} instead of @kbd{Q}, @w{@kbd{factor( )}} instead of
10352 @kbd{a f}, and so on.  To type regular Calc commands when you are in
10353 ``total'' algebraic mode, hold down the @key{META} key.  Thus @kbd{M-q}
10354 is the command to quit Calc, @kbd{M-p} sets the precision, and
10355 @kbd{M-m t} (or @kbd{M-m M-t}, if you prefer) turns total algebraic
10356 mode back off again.  Meta keys also terminate algebraic entry, so
10357 that @kbd{2+3 M-S} is equivalent to @kbd{2+3 RET M-S}.  The symbol
10358 @samp{Alg*} will appear in the mode line whenever you are in this mode.
10360 Pressing @kbd{'} (the apostrophe) a second time re-enters the previous
10361 algebraic formula.  You can then use the normal Emacs editing keys to
10362 modify this formula to your liking before pressing @key{RET}.
10364 @kindex $
10365 @cindex Formulas, referring to stack
10366 Within a formula entered from the keyboard, the symbol @kbd{$}
10367 represents the number on the top of the stack.  If an entered formula
10368 contains any @kbd{$} characters, the Calculator replaces the top of
10369 stack with that formula rather than simply pushing the formula onto the
10370 stack.  Thus, @kbd{' 1+2 @key{RET}} pushes 3 on the stack, and @kbd{$*2
10371 @key{RET}} replaces it with 6.  Note that the @kbd{$} key always
10372 initiates algebraic entry; the @kbd{'} is unnecessary if @kbd{$} is the
10373 first character in the new formula.@refill
10375 Higher stack elements can be accessed from an entered formula with the
10376 symbols @kbd{$$}, @kbd{$$$}, and so on.  The number of stack elements
10377 removed (to be replaced by the entered values) equals the number of dollar
10378 signs in the longest such symbol in the formula.  For example, @samp{$$+$$$}
10379 adds the second and third stack elements, replacing the top three elements
10380 with the answer.  (All information about the top stack element is thus lost
10381 since no single @samp{$} appears in this formula.)@refill
10383 A slightly different way to refer to stack elements is with a dollar
10384 sign followed by a number:  @samp{$1}, @samp{$2}, and so on are much
10385 like @samp{$}, @samp{$$}, etc., except that stack entries referred
10386 to numerically are not replaced by the algebraic entry.  That is, while
10387 @samp{$+1} replaces 5 on the stack with 6, @samp{$1+1} leaves the 5
10388 on the stack and pushes an additional 6.
10390 If a sequence of formulas are entered separated by commas, each formula
10391 is pushed onto the stack in turn.  For example, @samp{1,2,3} pushes
10392 those three numbers onto the stack (leaving the 3 at the top), and
10393 @samp{$+1,$-1} replaces a 5 on the stack with 4 followed by 6.  Also,
10394 @samp{$,$$} exchanges the top two elements of the stack, just like the
10395 @key{TAB} key.
10397 You can finish an algebraic entry with @kbd{M-=} or @kbd{M-RET} instead
10398 of @key{RET}.  This uses @kbd{=} to evaluate the variables in each
10399 formula that goes onto the stack.  (Thus @kbd{' pi @key{RET}} pushes
10400 the variable @samp{pi}, but @kbd{' pi M-RET} pushes 3.1415.)
10402 If you finish your algebraic entry by pressing @kbd{LFD} (or @kbd{C-j})
10403 instead of @key{RET}, Calc disables the default simplifications
10404 (as if by @kbd{m O}; @pxref{Simplification Modes}) while the entry
10405 is being pushed on the stack.  Thus @kbd{' 1+2 @key{RET}} pushes 3
10406 on the stack, but @kbd{' 1+2 @key{LFD}} pushes the formula @cite{1+2};
10407 you might then press @kbd{=} when it is time to evaluate this formula.
10409 @node Quick Calculator, Prefix Arguments, Algebraic Entry, Introduction
10410 @section ``Quick Calculator'' Mode
10412 @noindent
10413 @kindex M-# q
10414 @pindex quick-calc
10415 @cindex Quick Calculator
10416 There is another way to invoke the Calculator if all you need to do
10417 is make one or two quick calculations.  Type @kbd{M-# q} (or
10418 @kbd{M-x quick-calc}), then type any formula as an algebraic entry.
10419 The Calculator will compute the result and display it in the echo
10420 area, without ever actually putting up a Calc window.
10422 You can use the @kbd{$} character in a Quick Calculator formula to
10423 refer to the previous Quick Calculator result.  Older results are
10424 not retained; the Quick Calculator has no effect on the full
10425 Calculator's stack or trail.  If you compute a result and then
10426 forget what it was, just run @code{M-# q} again and enter
10427 @samp{$} as the formula.
10429 If this is the first time you have used the Calculator in this Emacs
10430 session, the @kbd{M-# q} command will create the @code{*Calculator*}
10431 buffer and perform all the usual initializations; it simply will
10432 refrain from putting that buffer up in a new window.  The Quick
10433 Calculator refers to the @code{*Calculator*} buffer for all mode
10434 settings.  Thus, for example, to set the precision that the Quick
10435 Calculator uses, simply run the full Calculator momentarily and use
10436 the regular @kbd{p} command.
10438 If you use @code{M-# q} from inside the Calculator buffer, the
10439 effect is the same as pressing the apostrophe key (algebraic entry).
10441 The result of a Quick calculation is placed in the Emacs ``kill ring''
10442 as well as being displayed.  A subsequent @kbd{C-y} command will
10443 yank the result into the editing buffer.  You can also use this
10444 to yank the result into the next @kbd{M-# q} input line as a more
10445 explicit alternative to @kbd{$} notation, or to yank the result
10446 into the Calculator stack after typing @kbd{M-# c}.
10448 If you finish your formula by typing @key{LFD} (or @kbd{C-j}) instead
10449 of @key{RET}, the result is inserted immediately into the current
10450 buffer rather than going into the kill ring.
10452 Quick Calculator results are actually evaluated as if by the @kbd{=}
10453 key (which replaces variable names by their stored values, if any).
10454 If the formula you enter is an assignment to a variable using the
10455 @samp{:=} operator, say, @samp{foo := 2 + 3} or @samp{foo := foo + 1},
10456 then the result of the evaluation is stored in that Calc variable.
10457 @xref{Store and Recall}.
10459 If the result is an integer and the current display radix is decimal,
10460 the number will also be displayed in hex and octal formats.  If the
10461 integer is in the range from 1 to 126, it will also be displayed as
10462 an ASCII character.
10464 For example, the quoted character @samp{"x"} produces the vector
10465 result @samp{[120]} (because 120 is the ASCII code of the lower-case
10466 `x'; @pxref{Strings}).  Since this is a vector, not an integer, it
10467 is displayed only according to the current mode settings.  But
10468 running Quick Calc again and entering @samp{120} will produce the
10469 result @samp{120 (16#78, 8#170, x)} which shows the number in its
10470 decimal, hexadecimal, octal, and ASCII forms.
10472 Please note that the Quick Calculator is not any faster at loading
10473 or computing the answer than the full Calculator; the name ``quick''
10474 merely refers to the fact that it's much less hassle to use for
10475 small calculations.
10477 @node Prefix Arguments, Undo, Quick Calculator, Introduction
10478 @section Numeric Prefix Arguments
10480 @noindent
10481 Many Calculator commands use numeric prefix arguments.  Some, such as
10482 @kbd{d s} (@code{calc-sci-notation}), set a parameter to the value of
10483 the prefix argument or use a default if you don't use a prefix.
10484 Others (like @kbd{d f} (@code{calc-fix-notation})) require an argument
10485 and prompt for a number if you don't give one as a prefix.@refill
10487 As a rule, stack-manipulation commands accept a numeric prefix argument
10488 which is interpreted as an index into the stack.  A positive argument
10489 operates on the top @var{n} stack entries; a negative argument operates
10490 on the @var{n}th stack entry in isolation; and a zero argument operates
10491 on the entire stack.
10493 Most commands that perform computations (such as the arithmetic and
10494 scientific functions) accept a numeric prefix argument that allows the
10495 operation to be applied across many stack elements.  For unary operations
10496 (that is, functions of one argument like absolute value or complex
10497 conjugate), a positive prefix argument applies that function to the top
10498 @var{n} stack entries simultaneously, and a negative argument applies it
10499 to the @var{n}th stack entry only.  For binary operations (functions of
10500 two arguments like addition, GCD, and vector concatenation), a positive
10501 prefix argument ``reduces'' the function across the top @var{n}
10502 stack elements (for example, @kbd{C-u 5 +} sums the top 5 stack entries;
10503 @pxref{Reducing and Mapping}), and a negative argument maps the next-to-top
10504 @var{n} stack elements with the top stack element as a second argument
10505 (for example, @kbd{7 c-u -5 +} adds 7 to the top 5 stack elements).
10506 This feature is not available for operations which use the numeric prefix
10507 argument for some other purpose.
10509 Numeric prefixes are specified the same way as always in Emacs:  Press
10510 a sequence of @key{META}-digits, or press @key{ESC} followed by digits,
10511 or press @kbd{C-u} followed by digits.  Some commands treat plain
10512 @kbd{C-u} (without any actual digits) specially.@refill
10514 @kindex ~
10515 @pindex calc-num-prefix
10516 You can type @kbd{~} (@code{calc-num-prefix}) to pop an integer from the
10517 top of the stack and enter it as the numeric prefix for the next command.
10518 For example, @kbd{C-u 16 p} sets the precision to 16 digits; an alternate
10519 (silly) way to do this would be @kbd{2 @key{RET} 4 ^ ~ p}, i.e., compute 2
10520 to the fourth power and set the precision to that value.@refill
10522 Conversely, if you have typed a numeric prefix argument the @kbd{~} key
10523 pushes it onto the stack in the form of an integer.
10525 @node Undo, Error Messages, Prefix Arguments, Introduction
10526 @section Undoing Mistakes
10528 @noindent
10529 @kindex U
10530 @kindex C-_
10531 @pindex calc-undo
10532 @cindex Mistakes, undoing
10533 @cindex Undoing mistakes
10534 @cindex Errors, undoing
10535 The shift-@kbd{U} key (@code{calc-undo}) undoes the most recent operation.
10536 If that operation added or dropped objects from the stack, those objects
10537 are removed or restored.  If it was a ``store'' operation, you are
10538 queried whether or not to restore the variable to its original value.
10539 The @kbd{U} key may be pressed any number of times to undo successively
10540 farther back in time; with a numeric prefix argument it undoes a
10541 specified number of operations.  The undo history is cleared only by the
10542 @kbd{q} (@code{calc-quit}) command.  (Recall that @kbd{M-# c} is
10543 synonymous with @code{calc-quit} while inside the Calculator; this
10544 also clears the undo history.)
10546 Currently the mode-setting commands (like @code{calc-precision}) are not
10547 undoable.  You can undo past a point where you changed a mode, but you
10548 will need to reset the mode yourself.
10550 @kindex D
10551 @pindex calc-redo
10552 @cindex Redoing after an Undo
10553 The shift-@kbd{D} key (@code{calc-redo}) redoes an operation that was
10554 mistakenly undone.  Pressing @kbd{U} with a negative prefix argument is
10555 equivalent to executing @code{calc-redo}.  You can redo any number of
10556 times, up to the number of recent consecutive undo commands.  Redo
10557 information is cleared whenever you give any command that adds new undo
10558 information, i.e., if you undo, then enter a number on the stack or make
10559 any other change, then it will be too late to redo.
10561 @kindex M-RET
10562 @pindex calc-last-args
10563 @cindex Last-arguments feature
10564 @cindex Arguments, restoring
10565 The @kbd{M-@key{RET}} key (@code{calc-last-args}) is like undo in that
10566 it restores the arguments of the most recent command onto the stack;
10567 however, it does not remove the result of that command.  Given a numeric
10568 prefix argument, this command applies to the @cite{n}th most recent
10569 command which removed items from the stack; it pushes those items back
10570 onto the stack.
10572 The @kbd{K} (@code{calc-keep-args}) command provides a related function
10573 to @kbd{M-@key{RET}}.  @xref{Stack and Trail}.
10575 It is also possible to recall previous results or inputs using the trail.
10576 @xref{Trail Commands}.
10578 The standard Emacs @kbd{C-_} undo key is recognized as a synonym for @kbd{U}.
10580 @node Error Messages, Multiple Calculators, Undo, Introduction
10581 @section Error Messages
10583 @noindent
10584 @kindex w
10585 @pindex calc-why
10586 @cindex Errors, messages
10587 @cindex Why did an error occur?
10588 Many situations that would produce an error message in other calculators
10589 simply create unsimplified formulas in the Emacs Calculator.  For example,
10590 @kbd{1 @key{RET} 0 /} pushes the formula @cite{1 / 0}; @w{@kbd{0 L}} pushes
10591 the formula @samp{ln(0)}.  Floating-point overflow and underflow are also
10592 reasons for this to happen.
10594 When a function call must be left in symbolic form, Calc usually
10595 produces a message explaining why.  Messages that are probably
10596 surprising or indicative of user errors are displayed automatically.
10597 Other messages are simply kept in Calc's memory and are displayed only
10598 if you type @kbd{w} (@code{calc-why}).  You can also press @kbd{w} if
10599 the same computation results in several messages.  (The first message
10600 will end with @samp{[w=more]} in this case.)
10602 @kindex d w
10603 @pindex calc-auto-why
10604 The @kbd{d w} (@code{calc-auto-why}) command controls when error messages
10605 are displayed automatically.  (Calc effectively presses @kbd{w} for you
10606 after your computation finishes.)  By default, this occurs only for
10607 ``important'' messages.  The other possible modes are to report
10608 @emph{all} messages automatically, or to report none automatically (so
10609 that you must always press @kbd{w} yourself to see the messages).
10611 @node Multiple Calculators, Troubleshooting Commands, Error Messages, Introduction
10612 @section Multiple Calculators
10614 @noindent
10615 @pindex another-calc
10616 It is possible to have any number of Calc Mode buffers at once.
10617 Usually this is done by executing @kbd{M-x another-calc}, which
10618 is similar to @kbd{M-# c} except that if a @samp{*Calculator*}
10619 buffer already exists, a new, independent one with a name of the
10620 form @samp{*Calculator*<@var{n}>} is created.  You can also use the
10621 command @code{calc-mode} to put any buffer into Calculator mode, but
10622 this would ordinarily never be done.
10624 The @kbd{q} (@code{calc-quit}) command does not destroy a Calculator buffer;
10625 it only closes its window.  Use @kbd{M-x kill-buffer} to destroy a
10626 Calculator buffer.
10628 Each Calculator buffer keeps its own stack, undo list, and mode settings
10629 such as precision, angular mode, and display formats.  In Emacs terms,
10630 variables such as @code{calc-stack} are buffer-local variables.  The
10631 global default values of these variables are used only when a new
10632 Calculator buffer is created.  The @code{calc-quit} command saves
10633 the stack and mode settings of the buffer being quit as the new defaults.
10635 There is only one trail buffer, @samp{*Calc Trail*}, used by all
10636 Calculator buffers.
10638 @node Troubleshooting Commands, , Multiple Calculators, Introduction
10639 @section Troubleshooting Commands
10641 @noindent
10642 This section describes commands you can use in case a computation
10643 incorrectly fails or gives the wrong answer.
10645 @xref{Reporting Bugs}, if you find a problem that appears to be due
10646 to a bug or deficiency in Calc.
10648 @menu
10649 * Autoloading Problems::
10650 * Recursion Depth::
10651 * Caches::
10652 * Debugging Calc::
10653 @end menu
10655 @node Autoloading Problems, Recursion Depth, Troubleshooting Commands, Troubleshooting Commands
10656 @subsection Autoloading Problems
10658 @noindent
10659 The Calc program is split into many component files; components are
10660 loaded automatically as you use various commands that require them.
10661 Occasionally Calc may lose track of when a certain component is
10662 necessary; typically this means you will type a command and it won't
10663 work because some function you've never heard of was undefined.
10665 @kindex M-# L
10666 @pindex calc-load-everything
10667 If this happens, the easiest workaround is to type @kbd{M-# L}
10668 (@code{calc-load-everything}) to force all the parts of Calc to be
10669 loaded right away.  This will cause Emacs to take up a lot more
10670 memory than it would otherwise, but it's guaranteed to fix the problem.
10672 If you seem to run into this problem no matter what you do, or if
10673 even the @kbd{M-# L} command crashes, Calc may have been improperly
10674 installed.  @xref{Installation}, for details of the installation
10675 process.
10677 @node Recursion Depth, Caches, Autoloading Problems, Troubleshooting Commands
10678 @subsection Recursion Depth
10680 @noindent
10681 @kindex M
10682 @kindex I M
10683 @pindex calc-more-recursion-depth
10684 @pindex calc-less-recursion-depth
10685 @cindex Recursion depth
10686 @cindex ``Computation got stuck'' message
10687 @cindex @code{max-lisp-eval-depth}
10688 @cindex @code{max-specpdl-size}
10689 Calc uses recursion in many of its calculations.  Emacs Lisp keeps a
10690 variable @code{max-lisp-eval-depth} which limits the amount of recursion
10691 possible in an attempt to recover from program bugs.  If a calculation
10692 ever halts incorrectly with the message ``Computation got stuck or
10693 ran too long,'' use the @kbd{M} command (@code{calc-more-recursion-depth})
10694 to increase this limit.  (Of course, this will not help if the
10695 calculation really did get stuck due to some problem inside Calc.)@refill
10697 The limit is always increased (multiplied) by a factor of two.  There
10698 is also an @kbd{I M} (@code{calc-less-recursion-depth}) command which
10699 decreases this limit by a factor of two, down to a minimum value of 200.
10700 The default value is 1000.
10702 These commands also double or halve @code{max-specpdl-size}, another
10703 internal Lisp recursion limit.  The minimum value for this limit is 600.
10705 @node Caches, Debugging Calc, Recursion Depth, Troubleshooting Commands
10706 @subsection Caches
10708 @noindent
10709 @cindex Caches
10710 @cindex Flushing caches
10711 Calc saves certain values after they have been computed once.  For
10712 example, the @kbd{P} (@code{calc-pi}) command initially ``knows'' the
10713 constant @c{$\pi$}
10714 @cite{pi} to about 20 decimal places; if the current precision
10715 is greater than this, it will recompute @c{$\pi$}
10716 @cite{pi} using a series
10717 approximation.  This value will not need to be recomputed ever again
10718 unless you raise the precision still further.  Many operations such as
10719 logarithms and sines make use of similarly cached values such as
10720 @c{$\pi \over 4$}
10721 @cite{pi/4} and @c{$\ln 2$}
10722 @cite{ln(2)}.  The visible effect of caching is that
10723 high-precision computations may seem to do extra work the first time.
10724 Other things cached include powers of two (for the binary arithmetic
10725 functions), matrix inverses and determinants, symbolic integrals, and
10726 data points computed by the graphing commands.
10728 @pindex calc-flush-caches
10729 If you suspect a Calculator cache has become corrupt, you can use the
10730 @code{calc-flush-caches} command to reset all caches to the empty state.
10731 (This should only be necessary in the event of bugs in the Calculator.)
10732 The @kbd{M-# 0} (with the zero key) command also resets caches along
10733 with all other aspects of the Calculator's state.
10735 @node Debugging Calc, , Caches, Troubleshooting Commands
10736 @subsection Debugging Calc
10738 @noindent
10739 A few commands exist to help in the debugging of Calc commands.
10740 @xref{Programming}, to see the various ways that you can write
10741 your own Calc commands.
10743 @kindex Z T
10744 @pindex calc-timing
10745 The @kbd{Z T} (@code{calc-timing}) command turns on and off a mode
10746 in which the timing of slow commands is reported in the Trail.
10747 Any Calc command that takes two seconds or longer writes a line
10748 to the Trail showing how many seconds it took.  This value is
10749 accurate only to within one second.
10751 All steps of executing a command are included; in particular, time
10752 taken to format the result for display in the stack and trail is
10753 counted.  Some prompts also count time taken waiting for them to
10754 be answered, while others do not; this depends on the exact
10755 implementation of the command.  For best results, if you are timing
10756 a sequence that includes prompts or multiple commands, define a
10757 keyboard macro to run the whole sequence at once.  Calc's @kbd{X}
10758 command (@pxref{Keyboard Macros}) will then report the time taken
10759 to execute the whole macro.
10761 Another advantage of the @kbd{X} command is that while it is
10762 executing, the stack and trail are not updated from step to step.
10763 So if you expect the output of your test sequence to leave a result
10764 that may take a long time to format and you don't wish to count
10765 this formatting time, end your sequence with a @key{DEL} keystroke
10766 to clear the result from the stack.  When you run the sequence with
10767 @kbd{X}, Calc will never bother to format the large result.
10769 Another thing @kbd{Z T} does is to increase the Emacs variable
10770 @code{gc-cons-threshold} to a much higher value (two million; the
10771 usual default in Calc is 250,000) for the duration of each command.
10772 This generally prevents garbage collection during the timing of
10773 the command, though it may cause your Emacs process to grow
10774 abnormally large.  (Garbage collection time is a major unpredictable
10775 factor in the timing of Emacs operations.)
10777 Another command that is useful when debugging your own Lisp
10778 extensions to Calc is @kbd{M-x calc-pass-errors}, which disables
10779 the error handler that changes the ``@code{max-lisp-eval-depth}
10780 exceeded'' message to the much more friendly ``Computation got
10781 stuck or ran too long.''  This handler interferes with the Emacs
10782 Lisp debugger's @code{debug-on-error} mode.  Errors are reported
10783 in the handler itself rather than at the true location of the
10784 error.  After you have executed @code{calc-pass-errors}, Lisp
10785 errors will be reported correctly but the user-friendly message
10786 will be lost.
10788 @node Data Types, Stack and Trail, Introduction, Top
10789 @chapter Data Types
10791 @noindent
10792 This chapter discusses the various types of objects that can be placed
10793 on the Calculator stack, how they are displayed, and how they are
10794 entered.  (@xref{Data Type Formats}, for information on how these data
10795 types are represented as underlying Lisp objects.)@refill
10797 Integers, fractions, and floats are various ways of describing real
10798 numbers.  HMS forms also for many purposes act as real numbers.  These
10799 types can be combined to form complex numbers, modulo forms, error forms,
10800 or interval forms.  (But these last four types cannot be combined
10801 arbitrarily:@: error forms may not contain modulo forms, for example.)
10802 Finally, all these types of numbers may be combined into vectors,
10803 matrices, or algebraic formulas.
10805 @menu
10806 * Integers::                The most basic data type.
10807 * Fractions::               This and above are called @dfn{rationals}.
10808 * Floats::                  This and above are called @dfn{reals}.
10809 * Complex Numbers::         This and above are called @dfn{numbers}.
10810 * Infinities::
10811 * Vectors and Matrices::
10812 * Strings::
10813 * HMS Forms::
10814 * Date Forms::
10815 * Modulo Forms::
10816 * Error Forms::
10817 * Interval Forms::
10818 * Incomplete Objects::
10819 * Variables::
10820 * Formulas::
10821 @end menu
10823 @node Integers, Fractions, Data Types, Data Types
10824 @section Integers
10826 @noindent
10827 @cindex Integers
10828 The Calculator stores integers to arbitrary precision.  Addition,
10829 subtraction, and multiplication of integers always yields an exact
10830 integer result.  (If the result of a division or exponentiation of
10831 integers is not an integer, it is expressed in fractional or
10832 floating-point form according to the current Fraction Mode.
10833 @xref{Fraction Mode}.)
10835 A decimal integer is represented as an optional sign followed by a
10836 sequence of digits.  Grouping (@pxref{Grouping Digits}) can be used to
10837 insert a comma at every third digit for display purposes, but you
10838 must not type commas during the entry of numbers.@refill
10840 @kindex #
10841 A non-decimal integer is represented as an optional sign, a radix
10842 between 2 and 36, a @samp{#} symbol, and one or more digits.  For radix 11
10843 and above, the letters A through Z (upper- or lower-case) count as
10844 digits and do not terminate numeric entry mode.  @xref{Radix Modes}, for how
10845 to set the default radix for display of integers.  Numbers of any radix
10846 may be entered at any time.  If you press @kbd{#} at the beginning of a
10847 number, the current display radix is used.@refill
10849 @node Fractions, Floats, Integers, Data Types
10850 @section Fractions
10852 @noindent
10853 @cindex Fractions
10854 A @dfn{fraction} is a ratio of two integers.  Fractions are traditionally
10855 written ``2/3'' but Calc uses the notation @samp{2:3}.  (The @kbd{/} key
10856 performs RPN division; the following two sequences push the number
10857 @samp{2:3} on the stack:  @kbd{2 :@: 3 @key{RET}}, or @kbd{2 @key{RET} 3 /}
10858 assuming Fraction Mode has been enabled.)
10859 When the Calculator produces a fractional result it always reduces it to
10860 simplest form, which may in fact be an integer.@refill
10862 Fractions may also be entered in a three-part form, where @samp{2:3:4}
10863 represents two-and-three-quarters.  @xref{Fraction Formats}, for fraction
10864 display formats.@refill
10866 Non-decimal fractions are entered and displayed as
10867 @samp{@var{radix}#@var{num}:@var{denom}} (or in the analogous three-part
10868 form).  The numerator and denominator always use the same radix.@refill
10870 @node Floats, Complex Numbers, Fractions, Data Types
10871 @section Floats
10873 @noindent
10874 @cindex Floating-point numbers
10875 A floating-point number or @dfn{float} is a number stored in scientific
10876 notation.  The number of significant digits in the fractional part is
10877 governed by the current floating precision (@pxref{Precision}).  The
10878 range of acceptable values is from @c{$10^{-3999999}$}
10879 @cite{10^-3999999} (inclusive)
10880 to @c{$10^{4000000}$}
10881 @cite{10^4000000}
10882 (exclusive), plus the corresponding negative
10883 values and zero.
10885 Calculations that would exceed the allowable range of values (such
10886 as @samp{exp(exp(20))}) are left in symbolic form by Calc.  The
10887 messages ``floating-point overflow'' or ``floating-point underflow''
10888 indicate that during the calculation a number would have been produced
10889 that was too large or too close to zero, respectively, to be represented
10890 by Calc.  This does not necessarily mean the final result would have
10891 overflowed, just that an overflow occurred while computing the result.
10892 (In fact, it could report an underflow even though the final result
10893 would have overflowed!)
10895 If a rational number and a float are mixed in a calculation, the result
10896 will in general be expressed as a float.  Commands that require an integer
10897 value (such as @kbd{k g} [@code{gcd}]) will also accept integer-valued
10898 floats, i.e., floating-point numbers with nothing after the decimal point.
10900 Floats are identified by the presence of a decimal point and/or an
10901 exponent.  In general a float consists of an optional sign, digits
10902 including an optional decimal point, and an optional exponent consisting
10903 of an @samp{e}, an optional sign, and up to seven exponent digits.
10904 For example, @samp{23.5e-2} is 23.5 times ten to the minus-second power,
10905 or 0.235.
10907 Floating-point numbers are normally displayed in decimal notation with
10908 all significant figures shown.  Exceedingly large or small numbers are
10909 displayed in scientific notation.  Various other display options are
10910 available.  @xref{Float Formats}.
10912 @cindex Accuracy of calculations
10913 Floating-point numbers are stored in decimal, not binary.  The result
10914 of each operation is rounded to the nearest value representable in the
10915 number of significant digits specified by the current precision,
10916 rounding away from zero in the case of a tie.  Thus (in the default
10917 display mode) what you see is exactly what you get.  Some operations such
10918 as square roots and transcendental functions are performed with several
10919 digits of extra precision and then rounded down, in an effort to make the
10920 final result accurate to the full requested precision.  However,
10921 accuracy is not rigorously guaranteed.  If you suspect the validity of a
10922 result, try doing the same calculation in a higher precision.  The
10923 Calculator's arithmetic is not intended to be IEEE-conformant in any
10924 way.@refill
10926 While floats are always @emph{stored} in decimal, they can be entered
10927 and displayed in any radix just like integers and fractions.  The
10928 notation @samp{@var{radix}#@var{ddd}.@var{ddd}} is a floating-point
10929 number whose digits are in the specified radix.  Note that the @samp{.}
10930 is more aptly referred to as a ``radix point'' than as a decimal
10931 point in this case.  The number @samp{8#123.4567} is defined as
10932 @samp{8#1234567 * 8^-4}.  If the radix is 14 or less, you can use
10933 @samp{e} notation to write a non-decimal number in scientific notation.
10934 The exponent is written in decimal, and is considered to be a power
10935 of the radix: @samp{8#1234567e-4}.  If the radix is 15 or above, the
10936 letter @samp{e} is a digit, so scientific notation must be written
10937 out, e.g., @samp{16#123.4567*16^2}.  The first two exercises of the
10938 Modes Tutorial explore some of the properties of non-decimal floats.
10940 @node Complex Numbers, Infinities, Floats, Data Types
10941 @section Complex Numbers
10943 @noindent
10944 @cindex Complex numbers
10945 There are two supported formats for complex numbers: rectangular and
10946 polar.  The default format is rectangular, displayed in the form
10947 @samp{(@var{real},@var{imag})} where @var{real} is the real part and
10948 @var{imag} is the imaginary part, each of which may be any real number.
10949 Rectangular complex numbers can also be displayed in @samp{@var{a}+@var{b}i}
10950 notation; @pxref{Complex Formats}.@refill
10952 Polar complex numbers are displayed in the form `@t{(}@var{r}@t{;}@c{$\theta$}
10953 @var{theta}@t{)}'
10954 where @var{r} is the nonnegative magnitude and @c{$\theta$}
10955 @var{theta} is the argument
10956 or phase angle.  The range of @c{$\theta$}
10957 @var{theta} depends on the current angular
10958 mode (@pxref{Angular Modes}); it is generally between @i{-180} and
10959 @i{+180} degrees or the equivalent range in radians.@refill
10961 Complex numbers are entered in stages using incomplete objects.
10962 @xref{Incomplete Objects}.
10964 Operations on rectangular complex numbers yield rectangular complex
10965 results, and similarly for polar complex numbers.  Where the two types
10966 are mixed, or where new complex numbers arise (as for the square root of
10967 a negative real), the current @dfn{Polar Mode} is used to determine the
10968 type.  @xref{Polar Mode}.
10970 A complex result in which the imaginary part is zero (or the phase angle
10971 is 0 or 180 degrees or @c{$\pi$}
10972 @cite{pi} radians) is automatically converted to a real
10973 number.
10975 @node Infinities, Vectors and Matrices, Complex Numbers, Data Types
10976 @section Infinities
10978 @noindent
10979 @cindex Infinity
10980 @cindex @code{inf} variable
10981 @cindex @code{uinf} variable
10982 @cindex @code{nan} variable
10983 @vindex inf
10984 @vindex uinf
10985 @vindex nan
10986 The word @code{inf} represents the mathematical concept of @dfn{infinity}.
10987 Calc actually has three slightly different infinity-like values:
10988 @code{inf}, @code{uinf}, and @code{nan}.  These are just regular
10989 variable names (@pxref{Variables}); you should avoid using these
10990 names for your own variables because Calc gives them special
10991 treatment.  Infinities, like all variable names, are normally
10992 entered using algebraic entry.
10994 Mathematically speaking, it is not rigorously correct to treat
10995 ``infinity'' as if it were a number, but mathematicians often do
10996 so informally.  When they say that @samp{1 / inf = 0}, what they
10997 really mean is that @cite{1 / x}, as @cite{x} becomes larger and
10998 larger, becomes arbitrarily close to zero.  So you can imagine
10999 that if @cite{x} got ``all the way to infinity,'' then @cite{1 / x}
11000 would go all the way to zero.  Similarly, when they say that
11001 @samp{exp(inf) = inf}, they mean that @c{$e^x$}
11002 @cite{exp(x)} grows without
11003 bound as @cite{x} grows.  The symbol @samp{-inf} likewise stands
11004 for an infinitely negative real value; for example, we say that
11005 @samp{exp(-inf) = 0}.  You can have an infinity pointing in any
11006 direction on the complex plane:  @samp{sqrt(-inf) = i inf}.
11008 The same concept of limits can be used to define @cite{1 / 0}.  We
11009 really want the value that @cite{1 / x} approaches as @cite{x}
11010 approaches zero.  But if all we have is @cite{1 / 0}, we can't
11011 tell which direction @cite{x} was coming from.  If @cite{x} was
11012 positive and decreasing toward zero, then we should say that
11013 @samp{1 / 0 = inf}.  But if @cite{x} was negative and increasing
11014 toward zero, the answer is @samp{1 / 0 = -inf}.  In fact, @cite{x}
11015 could be an imaginary number, giving the answer @samp{i inf} or
11016 @samp{-i inf}.  Calc uses the special symbol @samp{uinf} to mean
11017 @dfn{undirected infinity}, i.e., a value which is infinitely
11018 large but with an unknown sign (or direction on the complex plane).
11020 Calc actually has three modes that say how infinities are handled.
11021 Normally, infinities never arise from calculations that didn't
11022 already have them.  Thus, @cite{1 / 0} is treated simply as an
11023 error and left unevaluated.  The @kbd{m i} (@code{calc-infinite-mode})
11024 command (@pxref{Infinite Mode}) enables a mode in which
11025 @cite{1 / 0} evaluates to @code{uinf} instead.  There is also
11026 an alternative type of infinite mode which says to treat zeros
11027 as if they were positive, so that @samp{1 / 0 = inf}.  While this
11028 is less mathematically correct, it may be the answer you want in
11029 some cases.
11031 Since all infinities are ``as large'' as all others, Calc simplifies,
11032 e.g., @samp{5 inf} to @samp{inf}.  Another example is
11033 @samp{5 - inf = -inf}, where the @samp{-inf} is so large that
11034 adding a finite number like five to it does not affect it.
11035 Note that @samp{a - inf} also results in @samp{-inf}; Calc assumes
11036 that variables like @code{a} always stand for finite quantities.
11037 Just to show that infinities really are all the same size,
11038 note that @samp{sqrt(inf) = inf^2 = exp(inf) = inf} in Calc's
11039 notation.
11041 It's not so easy to define certain formulas like @samp{0 * inf} and
11042 @samp{inf / inf}.  Depending on where these zeros and infinities
11043 came from, the answer could be literally anything.  The latter
11044 formula could be the limit of @cite{x / x} (giving a result of one),
11045 or @cite{2 x / x} (giving two), or @cite{x^2 / x} (giving @code{inf}),
11046 or @cite{x / x^2} (giving zero).  Calc uses the symbol @code{nan}
11047 to represent such an @dfn{indeterminate} value.  (The name ``nan''
11048 comes from analogy with the ``NAN'' concept of IEEE standard
11049 arithmetic; it stands for ``Not A Number.''  This is somewhat of a
11050 misnomer, since @code{nan} @emph{does} stand for some number or
11051 infinity, it's just that @emph{which} number it stands for
11052 cannot be determined.)  In Calc's notation, @samp{0 * inf = nan}
11053 and @samp{inf / inf = nan}.  A few other common indeterminate
11054 expressions are @samp{inf - inf} and @samp{inf ^ 0}.  Also,
11055 @samp{0 / 0 = nan} if you have turned on ``infinite mode''
11056 (as described above).
11058 Infinities are especially useful as parts of @dfn{intervals}.
11059 @xref{Interval Forms}.
11061 @node Vectors and Matrices, Strings, Infinities, Data Types
11062 @section Vectors and Matrices
11064 @noindent
11065 @cindex Vectors
11066 @cindex Plain vectors
11067 @cindex Matrices
11068 The @dfn{vector} data type is flexible and general.  A vector is simply a
11069 list of zero or more data objects.  When these objects are numbers, the
11070 whole is a vector in the mathematical sense.  When these objects are
11071 themselves vectors of equal (nonzero) length, the whole is a @dfn{matrix}.
11072 A vector which is not a matrix is referred to here as a @dfn{plain vector}.
11074 A vector is displayed as a list of values separated by commas and enclosed
11075 in square brackets:  @samp{[1, 2, 3]}.  Thus the following is a 2 row by
11076 3 column matrix:  @samp{[[1, 2, 3], [4, 5, 6]]}.  Vectors, like complex
11077 numbers, are entered as incomplete objects.  @xref{Incomplete Objects}.
11078 During algebraic entry, vectors are entered all at once in the usual
11079 brackets-and-commas form.  Matrices may be entered algebraically as nested
11080 vectors, or using the shortcut notation @w{@samp{[1, 2, 3; 4, 5, 6]}},
11081 with rows separated by semicolons.  The commas may usually be omitted
11082 when entering vectors:  @samp{[1 2 3]}.  Curly braces may be used in
11083 place of brackets: @samp{@{1, 2, 3@}}, but the commas are required in
11084 this case.
11086 Traditional vector and matrix arithmetic is also supported;
11087 @pxref{Basic Arithmetic} and @pxref{Matrix Functions}.
11088 Many other operations are applied to vectors element-wise.  For example,
11089 the complex conjugate of a vector is a vector of the complex conjugates
11090 of its elements.@refill
11092 @c @starindex
11093 @tindex vec
11094 Algebraic functions for building vectors include @samp{vec(a, b, c)}
11095 to build @samp{[a, b, c]}, @samp{cvec(a, n, m)} to build an @c{$n\times m$}
11096 @asis{@var{n}x@var{m}}
11097 matrix of @samp{a}s, and @samp{index(n)} to build a vector of integers
11098 from 1 to @samp{n}.
11100 @node Strings, HMS Forms, Vectors and Matrices, Data Types
11101 @section Strings
11103 @noindent
11104 @kindex "
11105 @cindex Strings
11106 @cindex Character strings
11107 Character strings are not a special data type in the Calculator.
11108 Rather, a string is represented simply as a vector all of whose
11109 elements are integers in the range 0 to 255 (ASCII codes).  You can
11110 enter a string at any time by pressing the @kbd{"} key.  Quotation
11111 marks and backslashes are written @samp{\"} and @samp{\\}, respectively,
11112 inside strings.  Other notations introduced by backslashes are:
11114 @group
11115 @example
11116 \a     7          \^@@    0
11117 \b     8          \^a-z  1-26
11118 \e     27         \^[    27
11119 \f     12         \^\\   28
11120 \n     10         \^]    29
11121 \r     13         \^^    30
11122 \t     9          \^_    31
11123                   \^?    127
11124 @end example
11125 @end group
11127 @noindent
11128 Finally, a backslash followed by three octal digits produces any
11129 character from its ASCII code.
11131 @kindex d "
11132 @pindex calc-display-strings
11133 Strings are normally displayed in vector-of-integers form.  The
11134 @w{@kbd{d "}} (@code{calc-display-strings}) command toggles a mode in
11135 which any vectors of small integers are displayed as quoted strings
11136 instead.
11138 The backslash notations shown above are also used for displaying
11139 strings.  Characters 128 and above are not translated by Calc; unless
11140 you have an Emacs modified for 8-bit fonts, these will show up in
11141 backslash-octal-digits notation.  For characters below 32, and
11142 for character 127, Calc uses the backslash-letter combination if
11143 there is one, or otherwise uses a @samp{\^} sequence.
11145 The only Calc feature that uses strings is @dfn{compositions};
11146 @pxref{Compositions}.  Strings also provide a convenient
11147 way to do conversions between ASCII characters and integers.
11149 @c @starindex
11150 @tindex string
11151 There is a @code{string} function which provides a different display
11152 format for strings.  Basically, @samp{string(@var{s})}, where @var{s}
11153 is a vector of integers in the proper range, is displayed as the
11154 corresponding string of characters with no surrounding quotation
11155 marks or other modifications.  Thus @samp{string("ABC")} (or
11156 @samp{string([65 66 67])}) will look like @samp{ABC} on the stack.
11157 This happens regardless of whether @w{@kbd{d "}} has been used.  The
11158 only way to turn it off is to use @kbd{d U} (unformatted language
11159 mode) which will display @samp{string("ABC")} instead.
11161 Control characters are displayed somewhat differently by @code{string}.
11162 Characters below 32, and character 127, are shown using @samp{^} notation
11163 (same as shown above, but without the backslash).  The quote and
11164 backslash characters are left alone, as are characters 128 and above.
11166 @c @starindex
11167 @tindex bstring
11168 The @code{bstring} function is just like @code{string} except that
11169 the resulting string is breakable across multiple lines if it doesn't
11170 fit all on one line.  Potential break points occur at every space
11171 character in the string.
11173 @node HMS Forms, Date Forms, Strings, Data Types
11174 @section HMS Forms
11176 @noindent
11177 @cindex Hours-minutes-seconds forms
11178 @cindex Degrees-minutes-seconds forms
11179 @dfn{HMS} stands for Hours-Minutes-Seconds; when used as an angular
11180 argument, the interpretation is Degrees-Minutes-Seconds.  All functions
11181 that operate on angles accept HMS forms.  These are interpreted as
11182 degrees regardless of the current angular mode.  It is also possible to
11183 use HMS as the angular mode so that calculated angles are expressed in
11184 degrees, minutes, and seconds.
11186 @kindex @@
11187 @c @mindex @null
11188 @kindex ' (HMS forms)
11189 @c @mindex @null
11190 @kindex " (HMS forms)
11191 @c @mindex @null
11192 @kindex h (HMS forms)
11193 @c @mindex @null
11194 @kindex o (HMS forms)
11195 @c @mindex @null
11196 @kindex m (HMS forms)
11197 @c @mindex @null
11198 @kindex s (HMS forms)
11199 The default format for HMS values is
11200 @samp{@var{hours}@@ @var{mins}' @var{secs}"}.  During entry, the letters
11201 @samp{h} (for ``hours'') or
11202 @samp{o} (approximating the ``degrees'' symbol) are accepted as well as
11203 @samp{@@}, @samp{m} is accepted in place of @samp{'}, and @samp{s} is
11204 accepted in place of @samp{"}.
11205 The @var{hours} value is an integer (or integer-valued float).
11206 The @var{mins} value is an integer or integer-valued float between 0 and 59.
11207 The @var{secs} value is a real number between 0 (inclusive) and 60
11208 (exclusive).  A positive HMS form is interpreted as @var{hours} +
11209 @var{mins}/60 + @var{secs}/3600.  A negative HMS form is interpreted
11210 as @i{- @var{hours}} @i{-} @var{mins}/60 @i{-} @var{secs}/3600.
11211 Display format for HMS forms is quite flexible.  @xref{HMS Formats}.@refill
11213 HMS forms can be added and subtracted.  When they are added to numbers,
11214 the numbers are interpreted according to the current angular mode.  HMS
11215 forms can also be multiplied and divided by real numbers.  Dividing
11216 two HMS forms produces a real-valued ratio of the two angles.
11218 @pindex calc-time
11219 @cindex Time of day
11220 Just for kicks, @kbd{M-x calc-time} pushes the current time of day on
11221 the stack as an HMS form.
11223 @node Date Forms, Modulo Forms, HMS Forms, Data Types
11224 @section Date Forms
11226 @noindent
11227 @cindex Date forms
11228 A @dfn{date form} represents a date and possibly an associated time.
11229 Simple date arithmetic is supported:  Adding a number to a date
11230 produces a new date shifted by that many days; adding an HMS form to
11231 a date shifts it by that many hours.  Subtracting two date forms
11232 computes the number of days between them (represented as a simple
11233 number).  Many other operations, such as multiplying two date forms,
11234 are nonsensical and are not allowed by Calc.
11236 Date forms are entered and displayed enclosed in @samp{< >} brackets.
11237 The default format is, e.g., @samp{<Wed Jan 9, 1991>} for dates,
11238 or @samp{<3:32:20pm Wed Jan 9, 1991>} for dates with times.
11239 Input is flexible; date forms can be entered in any of the usual
11240 notations for dates and times.  @xref{Date Formats}.
11242 Date forms are stored internally as numbers, specifically the number
11243 of days since midnight on the morning of January 1 of the year 1 AD.
11244 If the internal number is an integer, the form represents a date only;
11245 if the internal number is a fraction or float, the form represents
11246 a date and time.  For example, @samp{<6:00am Wed Jan 9, 1991>}
11247 is represented by the number 726842.25.  The standard precision of
11248 12 decimal digits is enough to ensure that a (reasonable) date and
11249 time can be stored without roundoff error.
11251 If the current precision is greater than 12, date forms will keep
11252 additional digits in the seconds position.  For example, if the
11253 precision is 15, the seconds will keep three digits after the
11254 decimal point.  Decreasing the precision below 12 may cause the
11255 time part of a date form to become inaccurate.  This can also happen
11256 if astronomically high years are used, though this will not be an
11257 issue in everyday (or even everymillenium) use.  Note that date
11258 forms without times are stored as exact integers, so roundoff is
11259 never an issue for them.
11261 You can use the @kbd{v p} (@code{calc-pack}) and @kbd{v u}
11262 (@code{calc-unpack}) commands to get at the numerical representation
11263 of a date form.  @xref{Packing and Unpacking}.
11265 Date forms can go arbitrarily far into the future or past.  Negative
11266 year numbers represent years BC.  Calc uses a combination of the
11267 Gregorian and Julian calendars, following the history of Great
11268 Britain and the British colonies.  This is the same calendar that
11269 is used by the @code{cal} program in most Unix implementations.
11271 @cindex Julian calendar
11272 @cindex Gregorian calendar
11273 Some historical background:  The Julian calendar was created by
11274 Julius Caesar in the year 46 BC as an attempt to fix the gradual
11275 drift caused by the lack of leap years in the calendar used
11276 until that time.  The Julian calendar introduced an extra day in
11277 all years divisible by four.  After some initial confusion, the
11278 calendar was adopted around the year we call 8 AD.  Some centuries
11279 later it became apparent that the Julian year of 365.25 days was
11280 itself not quite right.  In 1582 Pope Gregory XIII introduced the
11281 Gregorian calendar, which added the new rule that years divisible
11282 by 100, but not by 400, were not to be considered leap years
11283 despite being divisible by four.  Many countries delayed adoption
11284 of the Gregorian calendar because of religious differences;
11285 in Britain it was put off until the year 1752, by which time
11286 the Julian calendar had fallen eleven days behind the true
11287 seasons.  So the switch to the Gregorian calendar in early
11288 September 1752 introduced a discontinuity:  The day after
11289 Sep 2, 1752 is Sep 14, 1752.  Calc follows this convention.
11290 To take another example, Russia waited until 1918 before
11291 adopting the new calendar, and thus needed to remove thirteen
11292 days (between Feb 1, 1918 and Feb 14, 1918).  This means that
11293 Calc's reckoning will be inconsistent with Russian history between
11294 1752 and 1918, and similarly for various other countries.
11296 Today's timekeepers introduce an occasional ``leap second'' as
11297 well, but Calc does not take these minor effects into account.
11298 (If it did, it would have to report a non-integer number of days
11299 between, say, @samp{<12:00am Mon Jan 1, 1900>} and
11300 @samp{<12:00am Sat Jan 1, 2000>}.)
11302 Calc uses the Julian calendar for all dates before the year 1752,
11303 including dates BC when the Julian calendar technically had not
11304 yet been invented.  Thus the claim that day number @i{-10000} is
11305 called ``August 16, 28 BC'' should be taken with a grain of salt.
11307 Please note that there is no ``year 0''; the day before
11308 @samp{<Sat Jan 1, +1>} is @samp{<Fri Dec 31, -1>}.  These are
11309 days 0 and @i{-1} respectively in Calc's internal numbering scheme.
11311 @cindex Julian day counting
11312 Another day counting system in common use is, confusingly, also
11313 called ``Julian.''  It was invented in 1583 by Joseph Justus
11314 Scaliger, who named it in honor of his father Julius Caesar
11315 Scaliger.  For obscure reasons he chose to start his day
11316 numbering on Jan 1, 4713 BC at noon, which in Calc's scheme
11317 is @i{-1721423.5} (recall that Calc starts at midnight instead
11318 of noon).  Thus to convert a Calc date code obtained by
11319 unpacking a date form into a Julian day number, simply add
11320 1721423.5.  The Julian code for @samp{6:00am Jan 9, 1991}
11321 is 2448265.75.  The built-in @kbd{t J} command performs
11322 this conversion for you.
11324 @cindex Unix time format
11325 The Unix operating system measures time as an integer number of
11326 seconds since midnight, Jan 1, 1970.  To convert a Calc date
11327 value into a Unix time stamp, first subtract 719164 (the code
11328 for @samp{<Jan 1, 1970>}), then multiply by 86400 (the number of
11329 seconds in a day) and press @kbd{R} to round to the nearest
11330 integer.  If you have a date form, you can simply subtract the
11331 day @samp{<Jan 1, 1970>} instead of unpacking and subtracting
11332 719164.  Likewise, divide by 86400 and add @samp{<Jan 1, 1970>}
11333 to convert from Unix time to a Calc date form.  (Note that
11334 Unix normally maintains the time in the GMT time zone; you may
11335 need to subtract five hours to get New York time, or eight hours
11336 for California time.  The same is usually true of Julian day
11337 counts.)  The built-in @kbd{t U} command performs these
11338 conversions.
11340 @node Modulo Forms, Error Forms, Date Forms, Data Types
11341 @section Modulo Forms
11343 @noindent
11344 @cindex Modulo forms
11345 A @dfn{modulo form} is a real number which is taken modulo (i.e., within
11346 an integer multiple of) some value @cite{M}.  Arithmetic modulo @cite{M}
11347 often arises in number theory.  Modulo forms are written
11348 `@i{a} @t{mod} @i{M}',
11349 where @cite{a} and @cite{M} are real numbers or HMS forms, and
11350 @c{$0 \le a < M$}
11351 @cite{0 <= a < @var{M}}.
11352 In many applications @cite{a} and @cite{M} will be
11353 integers but this is not required.@refill
11355 Modulo forms are not to be confused with the modulo operator @samp{%}.
11356 The expression @samp{27 % 10} means to compute 27 modulo 10 to produce
11357 the result 7.  Further computations treat this 7 as just a regular integer.
11358 The expression @samp{27 mod 10} produces the result @samp{7 mod 10};
11359 further computations with this value are again reduced modulo 10 so that
11360 the result always lies in the desired range.
11362 When two modulo forms with identical @cite{M}'s are added or multiplied,
11363 the Calculator simply adds or multiplies the values, then reduces modulo
11364 @cite{M}.  If one argument is a modulo form and the other a plain number,
11365 the plain number is treated like a compatible modulo form.  It is also
11366 possible to raise modulo forms to powers; the result is the value raised
11367 to the power, then reduced modulo @cite{M}.  (When all values involved
11368 are integers, this calculation is done much more efficiently than
11369 actually computing the power and then reducing.)
11371 @cindex Modulo division
11372 Two modulo forms `@i{a} @t{mod} @i{M}' and `@i{b} @t{mod} @i{M}'
11373 can be divided if @cite{a}, @cite{b}, and @cite{M} are all
11374 integers.  The result is the modulo form which, when multiplied by
11375 `@i{b} @t{mod} @i{M}', produces `@i{a} @t{mod} @i{M}'.  If
11376 there is no solution to this equation (which can happen only when
11377 @cite{M} is non-prime), or if any of the arguments are non-integers, the
11378 division is left in symbolic form.  Other operations, such as square
11379 roots, are not yet supported for modulo forms.  (Note that, although
11380 @w{`@t{(}@i{a} @t{mod} @i{M}@t{)^.5}'} will compute a ``modulo square root''
11381 in the sense of reducing @c{$\sqrt a$}
11382 @cite{sqrt(a)} modulo @cite{M}, this is not a
11383 useful definition from the number-theoretical point of view.)@refill
11385 @c @mindex M
11386 @kindex M (modulo forms)
11387 @c @mindex mod
11388 @tindex mod (operator)
11389 To create a modulo form during numeric entry, press the shift-@kbd{M}
11390 key to enter the word @samp{mod}.  As a special convenience, pressing
11391 shift-@kbd{M} a second time automatically enters the value of @cite{M}
11392 that was most recently used before.  During algebraic entry, either
11393 type @samp{mod} by hand or press @kbd{M-m} (that's @kbd{@key{META}-m}).
11394 Once again, pressing this a second time enters the current modulo.@refill
11396 You can also use @kbd{v p} and @kbd{%} to modify modulo forms.
11397 @xref{Building Vectors}.  @xref{Basic Arithmetic}.
11399 It is possible to mix HMS forms and modulo forms.  For example, an
11400 HMS form modulo 24 could be used to manipulate clock times; an HMS
11401 form modulo 360 would be suitable for angles.  Making the modulo @cite{M}
11402 also be an HMS form eliminates troubles that would arise if the angular
11403 mode were inadvertently set to Radians, in which case
11404 @w{@samp{2@@ 0' 0" mod 24}} would be interpreted as two degrees modulo
11405 24 radians!
11407 Modulo forms cannot have variables or formulas for components.  If you
11408 enter the formula @samp{(x + 2) mod 5}, Calc propagates the modulus
11409 to each of the coefficients:  @samp{(1 mod 5) x + (2 mod 5)}.
11411 @c @starindex
11412 @tindex makemod
11413 The algebraic function @samp{makemod(a, m)} builds the modulo form
11414 @w{@samp{a mod m}}.
11416 @node Error Forms, Interval Forms, Modulo Forms, Data Types
11417 @section Error Forms
11419 @noindent
11420 @cindex Error forms
11421 @cindex Standard deviations
11422 An @dfn{error form} is a number with an associated standard
11423 deviation, as in @samp{2.3 +/- 0.12}.  The notation
11424 `@i{x} @t{+/-} @c{$\sigma$}
11425 @asis{sigma}' stands for an uncertain value which follows a normal or
11426 Gaussian distribution of mean @cite{x} and standard deviation or
11427 ``error'' @c{$\sigma$}
11428 @cite{sigma}.  Both the mean and the error can be either numbers or
11429 formulas.  Generally these are real numbers but the mean may also be
11430 complex.  If the error is negative or complex, it is changed to its
11431 absolute value.  An error form with zero error is converted to a
11432 regular number by the Calculator.@refill
11434 All arithmetic and transcendental functions accept error forms as input.
11435 Operations on the mean-value part work just like operations on regular
11436 numbers.  The error part for any function @cite{f(x)} (such as @c{$\sin x$}
11437 @cite{sin(x)})
11438 is defined by the error of @cite{x} times the derivative of @cite{f}
11439 evaluated at the mean value of @cite{x}.  For a two-argument function
11440 @cite{f(x,y)} (such as addition) the error is the square root of the sum
11441 of the squares of the errors due to @cite{x} and @cite{y}.
11442 @tex
11443 $$ \eqalign{
11444   f(x \hbox{\code{ +/- }} \sigma)
11445     &= f(x) \hbox{\code{ +/- }} \sigma \left| {df(x) \over dx} \right| \cr
11446   f(x \hbox{\code{ +/- }} \sigma_x, y \hbox{\code{ +/- }} \sigma_y)
11447     &= f(x,y) \hbox{\code{ +/- }}
11448         \sqrt{\left(\sigma_x \left| {\partial f(x,y) \over \partial x}
11449                              \right| \right)^2
11450              +\left(\sigma_y \left| {\partial f(x,y) \over \partial y}
11451                              \right| \right)^2 } \cr
11452 } $$
11453 @end tex
11454 Note that this
11455 definition assumes the errors in @cite{x} and @cite{y} are uncorrelated.
11456 A side effect of this definition is that @samp{(2 +/- 1) * (2 +/- 1)}
11457 is not the same as @samp{(2 +/- 1)^2}; the former represents the product
11458 of two independent values which happen to have the same probability
11459 distributions, and the latter is the product of one random value with itself.
11460 The former will produce an answer with less error, since on the average
11461 the two independent errors can be expected to cancel out.@refill
11463 Consult a good text on error analysis for a discussion of the proper use
11464 of standard deviations.  Actual errors often are neither Gaussian-distributed
11465 nor uncorrelated, and the above formulas are valid only when errors
11466 are small.  As an example, the error arising from
11467 `@t{sin(}@i{x} @t{+/-} @c{$\sigma$}
11468 @i{sigma}@t{)}' is
11469 `@c{$\sigma$\nobreak}
11470 @i{sigma} @t{abs(cos(}@i{x}@t{))}'.  When @cite{x} is close to zero,
11471 @c{$\cos x$}
11472 @cite{cos(x)} is
11473 close to one so the error in the sine is close to @c{$\sigma$}
11474 @cite{sigma}; this makes sense, since @c{$\sin x$}
11475 @cite{sin(x)} is approximately @cite{x} near zero, so a given
11476 error in @cite{x} will produce about the same error in the sine.  Likewise,
11477 near 90 degrees @c{$\cos x$}
11478 @cite{cos(x)} is nearly zero and so the computed error is
11479 small:  The sine curve is nearly flat in that region, so an error in @cite{x}
11480 has relatively little effect on the value of @c{$\sin x$}
11481 @cite{sin(x)}.  However, consider
11482 @samp{sin(90 +/- 1000)}.  The cosine of 90 is zero, so Calc will report
11483 zero error!  We get an obviously wrong result because we have violated
11484 the small-error approximation underlying the error analysis.  If the error
11485 in @cite{x} had been small, the error in @c{$\sin x$}
11486 @cite{sin(x)} would indeed have been negligible.@refill
11488 @c @mindex p
11489 @kindex p (error forms)
11490 @tindex +/-
11491 To enter an error form during regular numeric entry, use the @kbd{p}
11492 (``plus-or-minus'') key to type the @samp{+/-} symbol.  (If you try actually
11493 typing @samp{+/-} the @kbd{+} key will be interpreted as the Calculator's
11494 @kbd{+} command!)  Within an algebraic formula, you can press @kbd{M-p} to
11495 type the @samp{+/-} symbol, or type it out by hand.
11497 Error forms and complex numbers can be mixed; the formulas shown above
11498 are used for complex numbers, too; note that if the error part evaluates
11499 to a complex number its absolute value (or the square root of the sum of
11500 the squares of the absolute values of the two error contributions) is
11501 used.  Mathematically, this corresponds to a radially symmetric Gaussian
11502 distribution of numbers on the complex plane.  However, note that Calc
11503 considers an error form with real components to represent a real number,
11504 not a complex distribution around a real mean.
11506 Error forms may also be composed of HMS forms.  For best results, both
11507 the mean and the error should be HMS forms if either one is.
11509 @c @starindex
11510 @tindex sdev
11511 The algebraic function @samp{sdev(a, b)} builds the error form @samp{a +/- b}.
11513 @node Interval Forms, Incomplete Objects, Error Forms, Data Types
11514 @section Interval Forms
11516 @noindent
11517 @cindex Interval forms
11518 An @dfn{interval} is a subset of consecutive real numbers.  For example,
11519 the interval @samp{[2 ..@: 4]} represents all the numbers from 2 to 4,
11520 inclusive.  If you multiply it by the interval @samp{[0.5 ..@: 2]} you
11521 obtain @samp{[1 ..@: 8]}.  This calculation represents the fact that if
11522 you multiply some number in the range @samp{[2 ..@: 4]} by some other
11523 number in the range @samp{[0.5 ..@: 2]}, your result will lie in the range
11524 from 1 to 8.  Interval arithmetic is used to get a worst-case estimate
11525 of the possible range of values a computation will produce, given the
11526 set of possible values of the input.
11528 @ifinfo
11529 Calc supports several varieties of intervals, including @dfn{closed}
11530 intervals of the type shown above, @dfn{open} intervals such as
11531 @samp{(2 ..@: 4)}, which represents the range of numbers from 2 to 4
11532 @emph{exclusive}, and @dfn{semi-open} intervals in which one end
11533 uses a round parenthesis and the other a square bracket.  In mathematical
11534 terms,
11535 @samp{[2 ..@: 4]} means @cite{2 <= x <= 4}, whereas
11536 @samp{[2 ..@: 4)} represents @cite{2 <= x < 4},
11537 @samp{(2 ..@: 4]} represents @cite{2 < x <= 4}, and
11538 @samp{(2 ..@: 4)} represents @cite{2 < x < 4}.@refill
11539 @end ifinfo
11540 @tex
11541 Calc supports several varieties of intervals, including \dfn{closed}
11542 intervals of the type shown above, \dfn{open} intervals such as
11543 \samp{(2 ..\: 4)}, which represents the range of numbers from 2 to 4
11544 \emph{exclusive}, and \dfn{semi-open} intervals in which one end
11545 uses a round parenthesis and the other a square bracket.  In mathematical
11546 terms,
11547 $$ \eqalign{
11548    [2 \hbox{\cite{..}} 4]  &\quad\hbox{means}\quad  2 \le x \le 4  \cr
11549    [2 \hbox{\cite{..}} 4)  &\quad\hbox{means}\quad  2 \le x  <  4  \cr
11550    (2 \hbox{\cite{..}} 4]  &\quad\hbox{means}\quad  2  <  x \le 4  \cr
11551    (2 \hbox{\cite{..}} 4)  &\quad\hbox{means}\quad  2  <  x  <  4  \cr
11552 } $$
11553 @end tex
11555 The lower and upper limits of an interval must be either real numbers
11556 (or HMS or date forms), or symbolic expressions which are assumed to be
11557 real-valued, or @samp{-inf} and @samp{inf}.  In general the lower limit
11558 must be less than the upper limit.  A closed interval containing only
11559 one value, @samp{[3 ..@: 3]}, is converted to a plain number (3)
11560 automatically.  An interval containing no values at all (such as
11561 @samp{[3 ..@: 2]} or @samp{[2 ..@: 2)}) can be represented but is not
11562 guaranteed to behave well when used in arithmetic.  Note that the
11563 interval @samp{[3 .. inf)} represents all real numbers greater than
11564 or equal to 3, and @samp{(-inf .. inf)} represents all real numbers.
11565 In fact, @samp{[-inf .. inf]} represents all real numbers including
11566 the real infinities.
11568 Intervals are entered in the notation shown here, either as algebraic
11569 formulas, or using incomplete forms.  (@xref{Incomplete Objects}.)
11570 In algebraic formulas, multiple periods in a row are collected from
11571 left to right, so that @samp{1...1e2} is interpreted as @samp{1.0 ..@: 1e2}
11572 rather than @samp{1 ..@: 0.1e2}.  Add spaces or zeros if you want to
11573 get the other interpretation.  If you omit the lower or upper limit,
11574 a default of @samp{-inf} or @samp{inf} (respectively) is furnished.
11576 ``Infinite mode'' also affects operations on intervals
11577 (@pxref{Infinities}).  Calc will always introduce an open infinity,
11578 as in @samp{1 / (0 .. 2] = [0.5 .. inf)}.  But closed infinities,
11579 @w{@samp{1 / [0 .. 2] = [0.5 .. inf]}}, arise only in infinite mode;
11580 otherwise they are left unevaluated.  Note that the ``direction'' of
11581 a zero is not an issue in this case since the zero is always assumed
11582 to be continuous with the rest of the interval.  For intervals that
11583 contain zero inside them Calc is forced to give the result,
11584 @samp{1 / (-2 .. 2) = [-inf .. inf]}.
11586 While it may seem that intervals and error forms are similar, they are
11587 based on entirely different concepts of inexact quantities.  An error
11588 form `@i{x} @t{+/-} @c{$\sigma$}
11589 @i{sigma}' means a variable is random, and its value could
11590 be anything but is ``probably'' within one @c{$\sigma$}
11591 @i{sigma} of the mean value @cite{x}.
11592 An interval `@t{[}@i{a} @t{..@:} @i{b}@t{]}' means a variable's value
11593 is unknown, but guaranteed to lie in the specified range.  Error forms
11594 are statistical or ``average case'' approximations; interval arithmetic
11595 tends to produce ``worst case'' bounds on an answer.@refill
11597 Intervals may not contain complex numbers, but they may contain
11598 HMS forms or date forms.
11600 @xref{Set Operations}, for commands that interpret interval forms
11601 as subsets of the set of real numbers.
11603 @c @starindex
11604 @tindex intv
11605 The algebraic function @samp{intv(n, a, b)} builds an interval form
11606 from @samp{a} to @samp{b}; @samp{n} is an integer code which must
11607 be 0 for @samp{(..)}, 1 for @samp{(..]}, 2 for @samp{[..)}, or
11608 3 for @samp{[..]}.
11610 Please note that in fully rigorous interval arithmetic, care would be
11611 taken to make sure that the computation of the lower bound rounds toward
11612 minus infinity, while upper bound computations round toward plus
11613 infinity.  Calc's arithmetic always uses a round-to-nearest mode,
11614 which means that roundoff errors could creep into an interval
11615 calculation to produce intervals slightly smaller than they ought to
11616 be.  For example, entering @samp{[1..2]} and pressing @kbd{Q 2 ^}
11617 should yield the interval @samp{[1..2]} again, but in fact it yields the
11618 (slightly too small) interval @samp{[1..1.9999999]} due to roundoff
11619 error.
11621 @node Incomplete Objects, Variables, Interval Forms, Data Types
11622 @section Incomplete Objects
11624 @noindent
11625 @c @mindex [ ]
11626 @kindex [
11627 @c @mindex ( )
11628 @kindex (
11629 @kindex ,
11630 @c @mindex @null
11631 @kindex ]
11632 @c @mindex @null
11633 @kindex )
11634 @cindex Incomplete vectors
11635 @cindex Incomplete complex numbers
11636 @cindex Incomplete interval forms
11637 When @kbd{(} or @kbd{[} is typed to begin entering a complex number or
11638 vector, respectively, the effect is to push an @dfn{incomplete} complex
11639 number or vector onto the stack.  The @kbd{,} key adds the value(s) at
11640 the top of the stack onto the current incomplete object.  The @kbd{)}
11641 and @kbd{]} keys ``close'' the incomplete object after adding any values
11642 on the top of the stack in front of the incomplete object.
11644 As a result, the sequence of keystrokes @kbd{[ 2 , 3 @key{RET} 2 * , 9 ]}
11645 pushes the vector @samp{[2, 6, 9]} onto the stack.  Likewise, @kbd{( 1 , 2 Q )}
11646 pushes the complex number @samp{(1, 1.414)} (approximately).
11648 If several values lie on the stack in front of the incomplete object,
11649 all are collected and appended to the object.  Thus the @kbd{,} key
11650 is redundant:  @kbd{[ 2 @key{RET} 3 @key{RET} 2 * 9 ]}.  Some people
11651 prefer the equivalent @key{SPC} key to @key{RET}.@refill
11653 As a special case, typing @kbd{,} immediately after @kbd{(}, @kbd{[}, or
11654 @kbd{,} adds a zero or duplicates the preceding value in the list being
11655 formed.  Typing @key{DEL} during incomplete entry removes the last item
11656 from the list.
11658 @kindex ;
11659 The @kbd{;} key is used in the same way as @kbd{,} to create polar complex
11660 numbers:  @kbd{( 1 ; 2 )}.  When entering a vector, @kbd{;} is useful for
11661 creating a matrix.  In particular, @kbd{[ [ 1 , 2 ; 3 , 4 ; 5 , 6 ] ]} is
11662 equivalent to @kbd{[ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]}.
11664 @kindex ..
11665 @pindex calc-dots
11666 Incomplete entry is also used to enter intervals.  For example,
11667 @kbd{[ 2 ..@: 4 )} enters a semi-open interval.  Note that when you type
11668 the first period, it will be interpreted as a decimal point, but when
11669 you type a second period immediately afterward, it is re-interpreted as
11670 part of the interval symbol.  Typing @kbd{..} corresponds to executing
11671 the @code{calc-dots} command.
11673 If you find incomplete entry distracting, you may wish to enter vectors
11674 and complex numbers as algebraic formulas by pressing the apostrophe key.
11676 @node Variables, Formulas, Incomplete Objects, Data Types
11677 @section Variables
11679 @noindent
11680 @cindex Variables, in formulas
11681 A @dfn{variable} is somewhere between a storage register on a conventional
11682 calculator, and a variable in a programming language.  (In fact, a Calc
11683 variable is really just an Emacs Lisp variable that contains a Calc number
11684 or formula.)  A variable's name is normally composed of letters and digits.
11685 Calc also allows apostrophes and @code{#} signs in variable names.
11686 The Calc variable @code{foo} corresponds to the Emacs Lisp variable
11687 @code{var-foo}.  Commands like @kbd{s s} (@code{calc-store}) that operate
11688 on variables can be made to use any arbitrary Lisp variable simply by
11689 backspacing over the @samp{var-} prefix in the minibuffer.@refill
11691 In a command that takes a variable name, you can either type the full
11692 name of a variable, or type a single digit to use one of the special
11693 convenience variables @code{var-q0} through @code{var-q9}.  For example,
11694 @kbd{3 s s 2} stores the number 3 in variable @code{var-q2}, and
11695 @w{@kbd{3 s s foo @key{RET}}} stores that number in variable
11696 @code{var-foo}.@refill
11698 To push a variable itself (as opposed to the variable's value) on the
11699 stack, enter its name as an algebraic expression using the apostrophe
11700 (@key{'}) key.  Variable names in algebraic formulas implicitly have
11701 @samp{var-} prefixed to their names.  The @samp{#} character in variable
11702 names used in algebraic formulas corresponds to a dash @samp{-} in the
11703 Lisp variable name.  If the name contains any dashes, the prefix @samp{var-}
11704 is @emph{not} automatically added.  Thus the two formulas @samp{foo + 1}
11705 and @samp{var#foo + 1} both refer to the same variable.
11707 @kindex =
11708 @pindex calc-evaluate
11709 @cindex Evaluation of variables in a formula
11710 @cindex Variables, evaluation
11711 @cindex Formulas, evaluation
11712 The @kbd{=} (@code{calc-evaluate}) key ``evaluates'' a formula by
11713 replacing all variables in the formula which have been given values by a
11714 @code{calc-store} or @code{calc-let} command by their stored values.
11715 Other variables are left alone.  Thus a variable that has not been
11716 stored acts like an abstract variable in algebra; a variable that has
11717 been stored acts more like a register in a traditional calculator.
11718 With a positive numeric prefix argument, @kbd{=} evaluates the top
11719 @var{n} stack entries; with a negative argument, @kbd{=} evaluates
11720 the @var{n}th stack entry.
11722 @cindex @code{e} variable
11723 @cindex @code{pi} variable
11724 @cindex @code{i} variable
11725 @cindex @code{phi} variable
11726 @cindex @code{gamma} variable
11727 @vindex e
11728 @vindex pi
11729 @vindex i
11730 @vindex phi
11731 @vindex gamma
11732 A few variables are called @dfn{special constants}.  Their names are
11733 @samp{e}, @samp{pi}, @samp{i}, @samp{phi}, and @samp{gamma}.
11734 (@xref{Scientific Functions}.)  When they are evaluated with @kbd{=},
11735 their values are calculated if necessary according to the current precision
11736 or complex polar mode.  If you wish to use these symbols for other purposes,
11737 simply undefine or redefine them using @code{calc-store}.@refill
11739 The variables @samp{inf}, @samp{uinf}, and @samp{nan} stand for
11740 infinite or indeterminate values.  It's best not to use them as
11741 regular variables, since Calc uses special algebraic rules when
11742 it manipulates them.  Calc displays a warning message if you store
11743 a value into any of these special variables.
11745 @xref{Store and Recall}, for a discussion of commands dealing with variables.
11747 @node Formulas, , Variables, Data Types
11748 @section Formulas
11750 @noindent
11751 @cindex Formulas
11752 @cindex Expressions
11753 @cindex Operators in formulas
11754 @cindex Precedence of operators
11755 When you press the apostrophe key you may enter any expression or formula
11756 in algebraic form.  (Calc uses the terms ``expression'' and ``formula''
11757 interchangeably.)  An expression is built up of numbers, variable names,
11758 and function calls, combined with various arithmetic operators.
11759 Parentheses may
11760 be used to indicate grouping.  Spaces are ignored within formulas, except
11761 that spaces are not permitted within variable names or numbers.
11762 Arithmetic operators, in order from highest to lowest precedence, and
11763 with their equivalent function names, are:
11765 @samp{_} [@code{subscr}] (subscripts);
11767 postfix @samp{%} [@code{percent}] (as in @samp{25% = 0.25});
11769 prefix @samp{+} and @samp{-} [@code{neg}] (as in @samp{-x})
11770 and prefix @samp{!} [@code{lnot}] (logical ``not,'' as in @samp{!x});
11772 @samp{+/-} [@code{sdev}] (the standard deviation symbol) and
11773 @samp{mod} [@code{makemod}] (the symbol for modulo forms);
11775 postfix @samp{!} [@code{fact}] (factorial, as in @samp{n!})
11776 and postfix @samp{!!} [@code{dfact}] (double factorial);
11778 @samp{^} [@code{pow}] (raised-to-the-power-of);
11780 @samp{*} [@code{mul}];
11782 @samp{/} [@code{div}], @samp{%} [@code{mod}] (modulo), and
11783 @samp{\} [@code{idiv}] (integer division);
11785 infix @samp{+} [@code{add}] and @samp{-} [@code{sub}] (as in @samp{x-y});
11787 @samp{|} [@code{vconcat}] (vector concatenation);
11789 relations @samp{=} [@code{eq}], @samp{!=} [@code{neq}], @samp{<} [@code{lt}],
11790 @samp{>} [@code{gt}], @samp{<=} [@code{leq}], and @samp{>=} [@code{geq}];
11792 @samp{&&} [@code{land}] (logical ``and'');
11794 @samp{||} [@code{lor}] (logical ``or'');
11796 the C-style ``if'' operator @samp{a?b:c} [@code{if}];
11798 @samp{!!!} [@code{pnot}] (rewrite pattern ``not'');
11800 @samp{&&&} [@code{pand}] (rewrite pattern ``and'');
11802 @samp{|||} [@code{por}] (rewrite pattern ``or'');
11804 @samp{:=} [@code{assign}] (for assignments and rewrite rules);
11806 @samp{::} [@code{condition}] (rewrite pattern condition);
11808 @samp{=>} [@code{evalto}].
11810 Note that, unlike in usual computer notation, multiplication binds more
11811 strongly than division:  @samp{a*b/c*d} is equivalent to @c{$a b \over c d$}
11812 @cite{(a*b)/(c*d)}.
11814 @cindex Multiplication, implicit
11815 @cindex Implicit multiplication
11816 The multiplication sign @samp{*} may be omitted in many cases.  In particular,
11817 if the righthand side is a number, variable name, or parenthesized
11818 expression, the @samp{*} may be omitted.  Implicit multiplication has the
11819 same precedence as the explicit @samp{*} operator.  The one exception to
11820 the rule is that a variable name followed by a parenthesized expression,
11821 as in @samp{f(x)},
11822 is interpreted as a function call, not an implicit @samp{*}.  In many
11823 cases you must use a space if you omit the @samp{*}:  @samp{2a} is the
11824 same as @samp{2*a}, and @samp{a b} is the same as @samp{a*b}, but @samp{ab}
11825 is a variable called @code{ab}, @emph{not} the product of @samp{a} and
11826 @samp{b}!  Also note that @samp{f (x)} is still a function call.@refill
11828 @cindex Implicit comma in vectors
11829 The rules are slightly different for vectors written with square brackets.
11830 In vectors, the space character is interpreted (like the comma) as a
11831 separator of elements of the vector.  Thus @w{@samp{[ 2a b+c d ]}} is
11832 equivalent to @samp{[2*a, b+c, d]}, whereas @samp{2a b+c d} is equivalent
11833 to @samp{2*a*b + c*d}.
11834 Note that spaces around the brackets, and around explicit commas, are
11835 ignored.  To force spaces to be interpreted as multiplication you can
11836 enclose a formula in parentheses as in @samp{[(a b) 2(c d)]}, which is
11837 interpreted as @samp{[a*b, 2*c*d]}.  An implicit comma is also inserted
11838 between @samp{][}, as in the matrix @samp{[[1 2][3 4]]}.@refill
11840 Vectors that contain commas (not embedded within nested parentheses or
11841 brackets) do not treat spaces specially:  @samp{[a b, 2 c d]} is a vector
11842 of two elements.  Also, if it would be an error to treat spaces as
11843 separators, but not otherwise, then Calc will ignore spaces:
11844 @w{@samp{[a - b]}} is a vector of one element, but @w{@samp{[a -b]}} is
11845 a vector of two elements.  Finally, vectors entered with curly braces
11846 instead of square brackets do not give spaces any special treatment.
11847 When Calc displays a vector that does not contain any commas, it will
11848 insert parentheses if necessary to make the meaning clear:
11849 @w{@samp{[(a b)]}}.
11851 The expression @samp{5%-2} is ambiguous; is this five-percent minus two,
11852 or five modulo minus-two?  Calc always interprets the leftmost symbol as
11853 an infix operator preferentially (modulo, in this case), so you would
11854 need to write @samp{(5%)-2} to get the former interpretation.
11856 @cindex Function call notation
11857 A function call is, e.g., @samp{sin(1+x)}.  Function names follow the same
11858 rules as variable names except that the default prefix @samp{calcFunc-} is
11859 used (instead of @samp{var-}) for the internal Lisp form.
11860 Most mathematical Calculator commands like
11861 @code{calc-sin} have function equivalents like @code{sin}.
11862 If no Lisp function is defined for a function called by a formula, the
11863 call is left as it is during algebraic manipulation: @samp{f(x+y)} is
11864 left alone.  Beware that many innocent-looking short names like @code{in}
11865 and @code{re} have predefined meanings which could surprise you; however,
11866 single letters or single letters followed by digits are always safe to
11867 use for your own function names.  @xref{Function Index}.@refill
11869 In the documentation for particular commands, the notation @kbd{H S}
11870 (@code{calc-sinh}) [@code{sinh}] means that the key sequence @kbd{H S}, the
11871 command @kbd{M-x calc-sinh}, and the algebraic function @code{sinh(x)} all
11872 represent the same operation.@refill
11874 Commands that interpret (``parse'') text as algebraic formulas include
11875 algebraic entry (@kbd{'}), editing commands like @kbd{`} which parse
11876 the contents of the editing buffer when you finish, the @kbd{M-# g}
11877 and @w{@kbd{M-# r}} commands, the @kbd{C-y} command, the X window system
11878 ``paste'' mouse operation, and Embedded Mode.  All of these operations
11879 use the same rules for parsing formulas; in particular, language modes
11880 (@pxref{Language Modes}) affect them all in the same way.
11882 When you read a large amount of text into the Calculator (say a vector
11883 which represents a big set of rewrite rules; @pxref{Rewrite Rules}),
11884 you may wish to include comments in the text.  Calc's formula parser
11885 ignores the symbol @samp{%%} and anything following it on a line:
11887 @example
11888 [ a + b,   %% the sum of "a" and "b"
11889   c + d,
11890   %% last line is coming up:
11891   e + f ]
11892 @end example
11894 @noindent
11895 This is parsed exactly the same as @samp{[ a + b, c + d, e + f ]}.
11897 @xref{Syntax Tables}, for a way to create your own operators and other
11898 input notations.  @xref{Compositions}, for a way to create new display
11899 formats.
11901 @xref{Algebra}, for commands for manipulating formulas symbolically.
11903 @node Stack and Trail, Mode Settings, Data Types, Top
11904 @chapter Stack and Trail Commands
11906 @noindent
11907 This chapter describes the Calc commands for manipulating objects on the
11908 stack and in the trail buffer.  (These commands operate on objects of any
11909 type, such as numbers, vectors, formulas, and incomplete objects.)
11911 @menu
11912 * Stack Manipulation::
11913 * Editing Stack Entries::
11914 * Trail Commands::
11915 * Keep Arguments::
11916 @end menu
11918 @node Stack Manipulation, Editing Stack Entries, Stack and Trail, Stack and Trail
11919 @section Stack Manipulation Commands
11921 @noindent
11922 @kindex RET
11923 @kindex SPC
11924 @pindex calc-enter
11925 @cindex Duplicating stack entries
11926 To duplicate the top object on the stack, press @key{RET} or @key{SPC}
11927 (two equivalent keys for the @code{calc-enter} command).
11928 Given a positive numeric prefix argument, these commands duplicate
11929 several elements at the top of the stack.
11930 Given a negative argument,
11931 these commands duplicate the specified element of the stack.
11932 Given an argument of zero, they duplicate the entire stack.
11933 For example, with @samp{10 20 30} on the stack,
11934 @key{RET} creates @samp{10 20 30 30},
11935 @kbd{C-u 2 @key{RET}} creates @samp{10 20 30 20 30},
11936 @kbd{C-u - 2 @key{RET}} creates @samp{10 20 30 20}, and
11937 @kbd{C-u 0 @key{RET}} creates @samp{10 20 30 10 20 30}.@refill
11939 @kindex LFD
11940 @pindex calc-over
11941 The @key{LFD} (@code{calc-over}) command (on a key marked Line-Feed if you
11942 have it, else on @kbd{C-j}) is like @code{calc-enter}
11943 except that the sign of the numeric prefix argument is interpreted
11944 oppositely.  Also, with no prefix argument the default argument is 2.
11945 Thus with @samp{10 20 30} on the stack, @key{LFD} and @kbd{C-u 2 @key{LFD}}
11946 are both equivalent to @kbd{C-u - 2 @key{RET}}, producing
11947 @samp{10 20 30 20}.@refill
11949 @kindex DEL
11950 @kindex C-d
11951 @pindex calc-pop
11952 @cindex Removing stack entries
11953 @cindex Deleting stack entries
11954 To remove the top element from the stack, press @key{DEL} (@code{calc-pop}).
11955 The @kbd{C-d} key is a synonym for @key{DEL}.
11956 (If the top element is an incomplete object with at least one element, the
11957 last element is removed from it.)  Given a positive numeric prefix argument,
11958 several elements are removed.  Given a negative argument, the specified
11959 element of the stack is deleted.  Given an argument of zero, the entire
11960 stack is emptied.
11961 For example, with @samp{10 20 30} on the stack,
11962 @key{DEL} leaves @samp{10 20},
11963 @kbd{C-u 2 @key{DEL}} leaves @samp{10},
11964 @kbd{C-u - 2 @key{DEL}} leaves @samp{10 30}, and
11965 @kbd{C-u 0 @key{DEL}} leaves an empty stack.@refill
11967 @kindex M-DEL
11968 @pindex calc-pop-above
11969 The @key{M-DEL} (@code{calc-pop-above}) command is to @key{DEL} what
11970 @key{LFD} is to @key{RET}:  It interprets the sign of the numeric
11971 prefix argument in the opposite way, and the default argument is 2.
11972 Thus @key{M-DEL} by itself removes the second-from-top stack element,
11973 leaving the first, third, fourth, and so on; @kbd{M-3 M-DEL} deletes
11974 the third stack element.
11976 @kindex TAB
11977 @pindex calc-roll-down
11978 To exchange the top two elements of the stack, press @key{TAB}
11979 (@code{calc-roll-down}).  Given a positive numeric prefix argument, the
11980 specified number of elements at the top of the stack are rotated downward.
11981 Given a negative argument, the entire stack is rotated downward the specified
11982 number of times.  Given an argument of zero, the entire stack is reversed
11983 top-for-bottom.
11984 For example, with @samp{10 20 30 40 50} on the stack,
11985 @key{TAB} creates @samp{10 20 30 50 40},
11986 @kbd{C-u 3 @key{TAB}} creates @samp{10 20 50 30 40},
11987 @kbd{C-u - 2 @key{TAB}} creates @samp{40 50 10 20 30}, and
11988 @kbd{C-u 0 @key{TAB}} creates @samp{50 40 30 20 10}.@refill
11990 @kindex M-TAB
11991 @pindex calc-roll-up
11992 The command @key{M-TAB} (@code{calc-roll-up}) is analogous to @key{TAB}
11993 except that it rotates upward instead of downward.  Also, the default
11994 with no prefix argument is to rotate the top 3 elements.
11995 For example, with @samp{10 20 30 40 50} on the stack,
11996 @key{M-TAB} creates @samp{10 20 40 50 30},
11997 @kbd{C-u 4 @key{M-TAB}} creates @samp{10 30 40 50 20},
11998 @kbd{C-u - 2 @key{M-TAB}} creates @samp{30 40 50 10 20}, and
11999 @kbd{C-u 0 @key{M-TAB}} creates @samp{50 40 30 20 10}.@refill
12001 A good way to view the operation of @key{TAB} and @key{M-TAB} is in
12002 terms of moving a particular element to a new position in the stack.
12003 With a positive argument @i{n}, @key{TAB} moves the top stack
12004 element down to level @i{n}, making room for it by pulling all the
12005 intervening stack elements toward the top.  @key{M-TAB} moves the
12006 element at level @i{n} up to the top.  (Compare with @key{LFD},
12007 which copies instead of moving the element in level @i{n}.)
12009 With a negative argument @i{-n}, @key{TAB} rotates the stack
12010 to move the object in level @i{n} to the deepest place in the
12011 stack, and the object in level @i{n+1} to the top.  @key{M-TAB}
12012 rotates the deepest stack element to be in level @i{n}, also
12013 putting the top stack element in level @i{n+1}.
12015 @xref{Selecting Subformulas}, for a way to apply these commands to
12016 any portion of a vector or formula on the stack.
12018 @node Editing Stack Entries, Trail Commands, Stack Manipulation, Stack and Trail
12019 @section Editing Stack Entries
12021 @noindent
12022 @kindex `
12023 @pindex calc-edit
12024 @pindex calc-edit-finish
12025 @cindex Editing the stack with Emacs
12026 The backquote, @kbd{`} (@code{calc-edit}) command creates a temporary
12027 buffer (@samp{*Calc Edit*}) for editing the top-of-stack value using
12028 regular Emacs commands.  With a numeric prefix argument, it edits the
12029 specified number of stack entries at once.  (An argument of zero edits
12030 the entire stack; a negative argument edits one specific stack entry.)
12032 When you are done editing, press @kbd{M-# M-#} to finish and return
12033 to Calc.  The @key{RET} and @key{LFD} keys also work to finish most
12034 sorts of editing, though in some cases Calc leaves @key{RET} with its
12035 usual meaning (``insert a newline'') if it's a situation where you
12036 might want to insert new lines into the editing buffer.  The traditional
12037 Emacs ``finish'' key sequence, @kbd{C-c C-c}, also works to finish
12038 editing and may be easier to type, depending on your keyboard.
12040 When you finish editing, the Calculator parses the lines of text in
12041 the @samp{*Calc Edit*} buffer as numbers or formulas, replaces the
12042 original stack elements in the original buffer with these new values,
12043 then kills the @samp{*Calc Edit*} buffer.  The original Calculator buffer
12044 continues to exist during editing, but for best results you should be
12045 careful not to change it until you have finished the edit.  You can
12046 also cancel the edit by pressing @kbd{M-# x}.
12048 The formula is normally reevaluated as it is put onto the stack.
12049 For example, editing @samp{a + 2} to @samp{3 + 2} and pressing
12050 @kbd{M-# M-#} will push 5 on the stack.  If you use @key{LFD} to
12051 finish, Calc will put the result on the stack without evaluating it.
12053 If you give a prefix argument to @kbd{M-# M-#} (or @kbd{C-c C-c}),
12054 Calc will not kill the @samp{*Calc Edit*} buffer.  You can switch
12055 back to that buffer and continue editing if you wish.  However, you
12056 should understand that if you initiated the edit with @kbd{`}, the
12057 @kbd{M-# M-#} operation will be programmed to replace the top of the
12058 stack with the new edited value, and it will do this even if you have
12059 rearranged the stack in the meanwhile.  This is not so much of a problem
12060 with other editing commands, though, such as @kbd{s e}
12061 (@code{calc-edit-variable}; @pxref{Operations on Variables}).
12063 If the @code{calc-edit} command involves more than one stack entry,
12064 each line of the @samp{*Calc Edit*} buffer is interpreted as a
12065 separate formula.  Otherwise, the entire buffer is interpreted as
12066 one formula, with line breaks ignored.  (You can use @kbd{C-o} or
12067 @kbd{C-q C-j} to insert a newline in the buffer without pressing @key{RET}.)
12069 The @kbd{`} key also works during numeric or algebraic entry.  The
12070 text entered so far is moved to the @code{*Calc Edit*} buffer for
12071 more extensive editing than is convenient in the minibuffer.
12073 @node Trail Commands, Keep Arguments, Editing Stack Entries, Stack and Trail
12074 @section Trail Commands
12076 @noindent
12077 @cindex Trail buffer
12078 The commands for manipulating the Calc Trail buffer are two-key sequences
12079 beginning with the @kbd{t} prefix.
12081 @kindex t d
12082 @pindex calc-trail-display
12083 The @kbd{t d} (@code{calc-trail-display}) command turns display of the
12084 trail on and off.  Normally the trail display is toggled on if it was off,
12085 off if it was on.  With a numeric prefix of zero, this command always
12086 turns the trail off; with a prefix of one, it always turns the trail on.
12087 The other trail-manipulation commands described here automatically turn
12088 the trail on.  Note that when the trail is off values are still recorded
12089 there; they are simply not displayed.  To set Emacs to turn the trail
12090 off by default, type @kbd{t d} and then save the mode settings with
12091 @kbd{m m} (@code{calc-save-modes}).
12093 @kindex t i
12094 @pindex calc-trail-in
12095 @kindex t o
12096 @pindex calc-trail-out
12097 The @kbd{t i} (@code{calc-trail-in}) and @kbd{t o}
12098 (@code{calc-trail-out}) commands switch the cursor into and out of the
12099 Calc Trail window.  In practice they are rarely used, since the commands
12100 shown below are a more convenient way to move around in the
12101 trail, and they work ``by remote control'' when the cursor is still
12102 in the Calculator window.@refill
12104 @cindex Trail pointer
12105 There is a @dfn{trail pointer} which selects some entry of the trail at
12106 any given time.  The trail pointer looks like a @samp{>} symbol right
12107 before the selected number.  The following commands operate on the
12108 trail pointer in various ways.
12110 @kindex t y
12111 @pindex calc-trail-yank
12112 @cindex Retrieving previous results
12113 The @kbd{t y} (@code{calc-trail-yank}) command reads the selected value in
12114 the trail and pushes it onto the Calculator stack.  It allows you to
12115 re-use any previously computed value without retyping.  With a numeric
12116 prefix argument @var{n}, it yanks the value @var{n} lines above the current
12117 trail pointer.
12119 @kindex t <
12120 @pindex calc-trail-scroll-left
12121 @kindex t >
12122 @pindex calc-trail-scroll-right
12123 The @kbd{t <} (@code{calc-trail-scroll-left}) and @kbd{t >}
12124 (@code{calc-trail-scroll-right}) commands horizontally scroll the trail
12125 window left or right by one half of its width.@refill
12127 @kindex t n
12128 @pindex calc-trail-next
12129 @kindex t p
12130 @pindex calc-trail-previous
12131 @kindex t f
12132 @pindex calc-trail-forward
12133 @kindex t b
12134 @pindex calc-trail-backward
12135 The @kbd{t n} (@code{calc-trail-next}) and @kbd{t p}
12136 (@code{calc-trail-previous)} commands move the trail pointer down or up
12137 one line.  The @kbd{t f} (@code{calc-trail-forward}) and @kbd{t b}
12138 (@code{calc-trail-backward}) commands move the trail pointer down or up
12139 one screenful at a time.  All of these commands accept numeric prefix
12140 arguments to move several lines or screenfuls at a time.@refill
12142 @kindex t [
12143 @pindex calc-trail-first
12144 @kindex t ]
12145 @pindex calc-trail-last
12146 @kindex t h
12147 @pindex calc-trail-here
12148 The @kbd{t [} (@code{calc-trail-first}) and @kbd{t ]}
12149 (@code{calc-trail-last}) commands move the trail pointer to the first or
12150 last line of the trail.  The @kbd{t h} (@code{calc-trail-here}) command
12151 moves the trail pointer to the cursor position; unlike the other trail
12152 commands, @kbd{t h} works only when Calc Trail is the selected window.@refill
12154 @kindex t s
12155 @pindex calc-trail-isearch-forward
12156 @kindex t r
12157 @pindex calc-trail-isearch-backward
12158 @ifinfo
12159 The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12160 (@code{calc-trail-isearch-backward}) commands perform an incremental
12161 search forward or backward through the trail.  You can press @key{RET}
12162 to terminate the search; the trail pointer moves to the current line.
12163 If you cancel the search with @kbd{C-g}, the trail pointer stays where
12164 it was when the search began.@refill
12165 @end ifinfo
12166 @tex
12167 The @kbd{t s} (@code{calc-trail-isearch-forward}) and @kbd{t r}
12168 (@code{calc-trail-isearch-backward}) com\-mands perform an incremental
12169 search forward or backward through the trail.  You can press @key{RET}
12170 to terminate the search; the trail pointer moves to the current line.
12171 If you cancel the search with @kbd{C-g}, the trail pointer stays where
12172 it was when the search began.
12173 @end tex
12175 @kindex t m
12176 @pindex calc-trail-marker
12177 The @kbd{t m} (@code{calc-trail-marker}) command allows you to enter a
12178 line of text of your own choosing into the trail.  The text is inserted
12179 after the line containing the trail pointer; this usually means it is
12180 added to the end of the trail.  Trail markers are useful mainly as the
12181 targets for later incremental searches in the trail.
12183 @kindex t k
12184 @pindex calc-trail-kill
12185 The @kbd{t k} (@code{calc-trail-kill}) command removes the selected line
12186 from the trail.  The line is saved in the Emacs kill ring suitable for
12187 yanking into another buffer, but it is not easy to yank the text back
12188 into the trail buffer.  With a numeric prefix argument, this command
12189 kills the @var{n} lines below or above the selected one.
12191 The @kbd{t .} (@code{calc-full-trail-vectors}) command is described
12192 elsewhere; @pxref{Vector and Matrix Formats}.
12194 @node Keep Arguments, , Trail Commands, Stack and Trail
12195 @section Keep Arguments
12197 @noindent
12198 @kindex K
12199 @pindex calc-keep-args
12200 The @kbd{K} (@code{calc-keep-args}) command acts like a prefix for
12201 the following command.  It prevents that command from removing its
12202 arguments from the stack.  For example, after @kbd{2 @key{RET} 3 +},
12203 the stack contains the sole number 5, but after @kbd{2 @key{RET} 3 K +},
12204 the stack contains the arguments and the result: @samp{2 3 5}.
12206 This works for all commands that take arguments off the stack.  As
12207 another example, @kbd{K a s} simplifies a formula, pushing the
12208 simplified version of the formula onto the stack after the original
12209 formula (rather than replacing the original formula).
12211 Note that you could get the same effect by typing @kbd{RET a s},
12212 copying the formula and then simplifying the copy.  One difference
12213 is that for a very large formula the time taken to format the
12214 intermediate copy in @kbd{RET a s} could be noticeable; @kbd{K a s}
12215 would avoid this extra work.
12217 Even stack manipulation commands are affected.  @key{TAB} works by
12218 popping two values and pushing them back in the opposite order,
12219 so @kbd{2 @key{RET} 3 K @key{TAB}} produces @samp{2 3 3 2}.
12221 A few Calc commands provide other ways of doing the same thing.
12222 For example, @kbd{' sin($)} replaces the number on the stack with
12223 its sine using algebraic entry; to push the sine and keep the
12224 original argument you could use either @kbd{' sin($1)} or
12225 @kbd{K ' sin($)}.  @xref{Algebraic Entry}.  Also, the @kbd{s s}
12226 command is effectively the same as @kbd{K s t}.  @xref{Storing Variables}.
12228 Keyboard macros may interact surprisingly with the @kbd{K} prefix.
12229 If you have defined a keyboard macro to be, say, @samp{Q +} to add
12230 one number to the square root of another, then typing @kbd{K X} will
12231 execute @kbd{K Q +}, probably not what you expected.  The @kbd{K}
12232 prefix will apply to just the first command in the macro rather than
12233 the whole macro.
12235 If you execute a command and then decide you really wanted to keep
12236 the argument, you can press @kbd{M-@key{RET}} (@code{calc-last-args}).
12237 This command pushes the last arguments that were popped by any command
12238 onto the stack.  Note that the order of things on the stack will be
12239 different than with @kbd{K}:  @kbd{2 @key{RET} 3 + M-@key{RET}} leaves
12240 @samp{5 2 3} on the stack instead of @samp{2 3 5}.  @xref{Undo}.
12242 @node Mode Settings, Arithmetic, Stack and Trail, Top
12243 @chapter Mode Settings
12245 @noindent
12246 This chapter describes commands that set modes in the Calculator.
12247 They do not affect the contents of the stack, although they may change
12248 the @emph{appearance} or @emph{interpretation} of the stack's contents.
12250 @menu
12251 * General Mode Commands::
12252 * Precision::
12253 * Inverse and Hyperbolic::
12254 * Calculation Modes::
12255 * Simplification Modes::
12256 * Declarations::
12257 * Display Modes::
12258 * Language Modes::
12259 * Modes Variable::
12260 * Calc Mode Line::
12261 @end menu
12263 @node General Mode Commands, Precision, Mode Settings, Mode Settings
12264 @section General Mode Commands
12266 @noindent
12267 @kindex m m
12268 @pindex calc-save-modes
12269 @cindex Continuous memory
12270 @cindex Saving mode settings
12271 @cindex Permanent mode settings
12272 @cindex @file{.emacs} file, mode settings
12273 You can save all of the current mode settings in your @file{.emacs} file
12274 with the @kbd{m m} (@code{calc-save-modes}) command.  This will cause
12275 Emacs to reestablish these modes each time it starts up.  The modes saved
12276 in the file include everything controlled by the @kbd{m} and @kbd{d}
12277 prefix keys, the current precision and binary word size, whether or not
12278 the trail is displayed, the current height of the Calc window, and more.
12279 The current interface (used when you type @kbd{M-# M-#}) is also saved.
12280 If there were already saved mode settings in the file, they are replaced.
12281 Otherwise, the new mode information is appended to the end of the file.
12283 @kindex m R
12284 @pindex calc-mode-record-mode
12285 The @kbd{m R} (@code{calc-mode-record-mode}) command tells Calc to
12286 record the new mode settings (as if by pressing @kbd{m m}) every
12287 time a mode setting changes.  If Embedded Mode is enabled, other
12288 options are available; @pxref{Mode Settings in Embedded Mode}.
12290 @kindex m F
12291 @pindex calc-settings-file-name
12292 The @kbd{m F} (@code{calc-settings-file-name}) command allows you to
12293 choose a different place than your @file{.emacs} file for @kbd{m m},
12294 @kbd{Z P}, and similar commands to save permanent information.
12295 You are prompted for a file name.  All Calc modes are then reset to
12296 their default values, then settings from the file you named are loaded
12297 if this file exists, and this file becomes the one that Calc will
12298 use in the future for commands like @kbd{m m}.  The default settings
12299 file name is @file{~/.emacs}.  You can see the current file name by
12300 giving a blank response to the @kbd{m F} prompt.  See also the
12301 discussion of the @code{calc-settings-file} variable; @pxref{Installation}.
12303 If the file name you give contains the string @samp{.emacs} anywhere
12304 inside it, @kbd{m F} will not automatically load the new file.  This
12305 is because you are presumably switching to your @file{~/.emacs} file,
12306 which may contain other things you don't want to reread.  You can give
12307 a numeric prefix argument of 1 to @kbd{m F} to force it to read the
12308 file no matter what its name.  Conversely, an argument of @i{-1} tells
12309 @kbd{m F} @emph{not} to read the new file.  An argument of 2 or @i{-2}
12310 tells @kbd{m F} not to reset the modes to their defaults beforehand,
12311 which is useful if you intend your new file to have a variant of the
12312 modes present in the file you were using before.
12314 @kindex m x
12315 @pindex calc-always-load-extensions
12316 The @kbd{m x} (@code{calc-always-load-extensions}) command enables a mode
12317 in which the first use of Calc loads the entire program, including all
12318 extensions modules.  Otherwise, the extensions modules will not be loaded
12319 until the various advanced Calc features are used.  Since this mode only
12320 has effect when Calc is first loaded, @kbd{m x} is usually followed by
12321 @kbd{m m} to make the mode-setting permanent.  To load all of Calc just
12322 once, rather than always in the future, you can press @kbd{M-# L}.
12324 @kindex m S
12325 @pindex calc-shift-prefix
12326 The @kbd{m S} (@code{calc-shift-prefix}) command enables a mode in which
12327 all of Calc's letter prefix keys may be typed shifted as well as unshifted.
12328 If you are typing, say, @kbd{a S} (@code{calc-solve-for}) quite often
12329 you might find it easier to turn this mode on so that you can type
12330 @kbd{A S} instead.  When this mode is enabled, the commands that used to
12331 be on those single shifted letters (e.g., @kbd{A} (@code{calc-abs})) can
12332 now be invoked by pressing the shifted letter twice: @kbd{A A}.  Note
12333 that the @kbd{v} prefix key always works both shifted and unshifted, and
12334 the @kbd{z} and @kbd{Z} prefix keys are always distinct.  Also, the @kbd{h}
12335 prefix is not affected by this mode.  Press @kbd{m S} again to disable
12336 shifted-prefix mode.
12338 @node Precision, Inverse and Hyperbolic, General Mode Commands, Mode Settings
12339 @section Precision
12341 @noindent
12342 @kindex p
12343 @pindex calc-precision
12344 @cindex Precision of calculations
12345 The @kbd{p} (@code{calc-precision}) command controls the precision to
12346 which floating-point calculations are carried.  The precision must be
12347 at least 3 digits and may be arbitrarily high, within the limits of
12348 memory and time.  This affects only floats:  Integer and rational
12349 calculations are always carried out with as many digits as necessary.
12351 The @kbd{p} key prompts for the current precision.  If you wish you
12352 can instead give the precision as a numeric prefix argument.
12354 Many internal calculations are carried to one or two digits higher
12355 precision than normal.  Results are rounded down afterward to the
12356 current precision.  Unless a special display mode has been selected,
12357 floats are always displayed with their full stored precision, i.e.,
12358 what you see is what you get.  Reducing the current precision does not
12359 round values already on the stack, but those values will be rounded
12360 down before being used in any calculation.  The @kbd{c 0} through
12361 @kbd{c 9} commands (@pxref{Conversions}) can be used to round an
12362 existing value to a new precision.@refill
12364 @cindex Accuracy of calculations
12365 It is important to distinguish the concepts of @dfn{precision} and
12366 @dfn{accuracy}.  In the normal usage of these words, the number
12367 123.4567 has a precision of 7 digits but an accuracy of 4 digits.
12368 The precision is the total number of digits not counting leading
12369 or trailing zeros (regardless of the position of the decimal point).
12370 The accuracy is simply the number of digits after the decimal point
12371 (again not counting trailing zeros).  In Calc you control the precision,
12372 not the accuracy of computations.  If you were to set the accuracy
12373 instead, then calculations like @samp{exp(100)} would generate many
12374 more digits than you would typically need, while @samp{exp(-100)} would
12375 probably round to zero!  In Calc, both these computations give you
12376 exactly 12 (or the requested number of) significant digits.
12378 The only Calc features that deal with accuracy instead of precision
12379 are fixed-point display mode for floats (@kbd{d f}; @pxref{Float Formats}),
12380 and the rounding functions like @code{floor} and @code{round}
12381 (@pxref{Integer Truncation}).  Also, @kbd{c 0} through @kbd{c 9}
12382 deal with both precision and accuracy depending on the magnitudes
12383 of the numbers involved.
12385 If you need to work with a particular fixed accuracy (say, dollars and
12386 cents with two digits after the decimal point), one solution is to work
12387 with integers and an ``implied'' decimal point.  For example, $8.99
12388 divided by 6 would be entered @kbd{899 RET 6 /}, yielding 149.833
12389 (actually $1.49833 with our implied decimal point); pressing @kbd{R}
12390 would round this to 150 cents, i.e., $1.50.
12392 @xref{Floats}, for still more on floating-point precision and related
12393 issues.
12395 @node Inverse and Hyperbolic, Calculation Modes, Precision, Mode Settings
12396 @section Inverse and Hyperbolic Flags
12398 @noindent
12399 @kindex I
12400 @pindex calc-inverse
12401 There is no single-key equivalent to the @code{calc-arcsin} function.
12402 Instead, you must first press @kbd{I} (@code{calc-inverse}) to set
12403 the @dfn{Inverse Flag}, then press @kbd{S} (@code{calc-sin}).
12404 The @kbd{I} key actually toggles the Inverse Flag.  When this flag
12405 is set, the word @samp{Inv} appears in the mode line.@refill
12407 @kindex H
12408 @pindex calc-hyperbolic
12409 Likewise, the @kbd{H} key (@code{calc-hyperbolic}) sets or clears the
12410 Hyperbolic Flag, which transforms @code{calc-sin} into @code{calc-sinh}.
12411 If both of these flags are set at once, the effect will be
12412 @code{calc-arcsinh}.  (The Hyperbolic flag is also used by some
12413 non-trigonometric commands; for example @kbd{H L} computes a base-10,
12414 instead of base-@i{e}, logarithm.)@refill
12416 Command names like @code{calc-arcsin} are provided for completeness, and
12417 may be executed with @kbd{x} or @kbd{M-x}.  Their effect is simply to
12418 toggle the Inverse and/or Hyperbolic flags and then execute the
12419 corresponding base command (@code{calc-sin} in this case).
12421 The Inverse and Hyperbolic flags apply only to the next Calculator
12422 command, after which they are automatically cleared.  (They are also
12423 cleared if the next keystroke is not a Calc command.)  Digits you
12424 type after @kbd{I} or @kbd{H} (or @kbd{K}) are treated as prefix
12425 arguments for the next command, not as numeric entries.  The same
12426 is true of @kbd{C-u}, but not of the minus sign (@kbd{K -} means to
12427 subtract and keep arguments).
12429 The third Calc prefix flag, @kbd{K} (keep-arguments), is discussed
12430 elsewhere.  @xref{Keep Arguments}.
12432 @node Calculation Modes, Simplification Modes, Inverse and Hyperbolic, Mode Settings
12433 @section Calculation Modes
12435 @noindent
12436 The commands in this section are two-key sequences beginning with
12437 the @kbd{m} prefix.  (That's the letter @kbd{m}, not the @key{META} key.)
12438 The @samp{m a} (@code{calc-algebraic-mode}) command is described elsewhere
12439 (@pxref{Algebraic Entry}).
12441 @menu
12442 * Angular Modes::
12443 * Polar Mode::
12444 * Fraction Mode::
12445 * Infinite Mode::
12446 * Symbolic Mode::
12447 * Matrix Mode::
12448 * Automatic Recomputation::
12449 * Working Message::
12450 @end menu
12452 @node Angular Modes, Polar Mode, Calculation Modes, Calculation Modes
12453 @subsection Angular Modes
12455 @noindent
12456 @cindex Angular mode
12457 The Calculator supports three notations for angles: radians, degrees,
12458 and degrees-minutes-seconds.  When a number is presented to a function
12459 like @code{sin} that requires an angle, the current angular mode is
12460 used to interpret the number as either radians or degrees.  If an HMS
12461 form is presented to @code{sin}, it is always interpreted as
12462 degrees-minutes-seconds.
12464 Functions that compute angles produce a number in radians, a number in
12465 degrees, or an HMS form depending on the current angular mode.  If the
12466 result is a complex number and the current mode is HMS, the number is
12467 instead expressed in degrees.  (Complex-number calculations would
12468 normally be done in radians mode, though.  Complex numbers are converted
12469 to degrees by calculating the complex result in radians and then
12470 multiplying by 180 over @c{$\pi$}
12471 @cite{pi}.)
12473 @kindex m r
12474 @pindex calc-radians-mode
12475 @kindex m d
12476 @pindex calc-degrees-mode
12477 @kindex m h
12478 @pindex calc-hms-mode
12479 The @kbd{m r} (@code{calc-radians-mode}), @kbd{m d} (@code{calc-degrees-mode}),
12480 and @kbd{m h} (@code{calc-hms-mode}) commands control the angular mode.
12481 The current angular mode is displayed on the Emacs mode line.
12482 The default angular mode is degrees.@refill
12484 @node Polar Mode, Fraction Mode, Angular Modes, Calculation Modes
12485 @subsection Polar Mode
12487 @noindent
12488 @cindex Polar mode
12489 The Calculator normally ``prefers'' rectangular complex numbers in the
12490 sense that rectangular form is used when the proper form can not be
12491 decided from the input.  This might happen by multiplying a rectangular
12492 number by a polar one, by taking the square root of a negative real
12493 number, or by entering @kbd{( 2 @key{SPC} 3 )}.
12495 @kindex m p
12496 @pindex calc-polar-mode
12497 The @kbd{m p} (@code{calc-polar-mode}) command toggles complex-number
12498 preference between rectangular and polar forms.  In polar mode, all
12499 of the above example situations would produce polar complex numbers.
12501 @node Fraction Mode, Infinite Mode, Polar Mode, Calculation Modes
12502 @subsection Fraction Mode
12504 @noindent
12505 @cindex Fraction mode
12506 @cindex Division of integers
12507 Division of two integers normally yields a floating-point number if the
12508 result cannot be expressed as an integer.  In some cases you would
12509 rather get an exact fractional answer.  One way to accomplish this is
12510 to multiply fractions instead:  @kbd{6 @key{RET} 1:4 *} produces @cite{3:2}
12511 even though @kbd{6 @key{RET} 4 /} produces @cite{1.5}.
12513 @kindex m f
12514 @pindex calc-frac-mode
12515 To set the Calculator to produce fractional results for normal integer
12516 divisions, use the @kbd{m f} (@code{calc-frac-mode}) command.
12517 For example, @cite{8/4} produces @cite{2} in either mode,
12518 but @cite{6/4} produces @cite{3:2} in Fraction Mode, @cite{1.5} in
12519 Float Mode.@refill
12521 At any time you can use @kbd{c f} (@code{calc-float}) to convert a
12522 fraction to a float, or @kbd{c F} (@code{calc-fraction}) to convert a
12523 float to a fraction.  @xref{Conversions}.
12525 @node Infinite Mode, Symbolic Mode, Fraction Mode, Calculation Modes
12526 @subsection Infinite Mode
12528 @noindent
12529 @cindex Infinite mode
12530 The Calculator normally treats results like @cite{1 / 0} as errors;
12531 formulas like this are left in unsimplified form.  But Calc can be
12532 put into a mode where such calculations instead produce ``infinite''
12533 results.
12535 @kindex m i
12536 @pindex calc-infinite-mode
12537 The @kbd{m i} (@code{calc-infinite-mode}) command turns this mode
12538 on and off.  When the mode is off, infinities do not arise except
12539 in calculations that already had infinities as inputs.  (One exception
12540 is that infinite open intervals like @samp{[0 .. inf)} can be
12541 generated; however, intervals closed at infinity (@samp{[0 .. inf]})
12542 will not be generated when infinite mode is off.)
12544 With infinite mode turned on, @samp{1 / 0} will generate @code{uinf},
12545 an undirected infinity.  @xref{Infinities}, for a discussion of the
12546 difference between @code{inf} and @code{uinf}.  Also, @cite{0 / 0}
12547 evaluates to @code{nan}, the ``indeterminate'' symbol.  Various other
12548 functions can also return infinities in this mode; for example,
12549 @samp{ln(0) = -inf}, and @samp{gamma(-7) = uinf}.  Once again,
12550 note that @samp{exp(inf) = inf} regardless of infinite mode because
12551 this calculation has infinity as an input.
12553 @cindex Positive infinite mode
12554 The @kbd{m i} command with a numeric prefix argument of zero,
12555 i.e., @kbd{C-u 0 m i}, turns on a ``positive infinite mode'' in
12556 which zero is treated as positive instead of being directionless.  
12557 Thus, @samp{1 / 0 = inf} and @samp{-1 / 0 = -inf} in this mode.
12558 Note that zero never actually has a sign in Calc; there are no
12559 separate representations for @i{+0} and @i{-0}.  Positive
12560 infinite mode merely changes the interpretation given to the
12561 single symbol, @samp{0}.  One consequence of this is that, while
12562 you might expect @samp{1 / -0 = -inf}, actually @samp{1 / -0}
12563 is equivalent to @samp{1 / 0}, which is equal to positive @code{inf}.
12565 @node Symbolic Mode, Matrix Mode, Infinite Mode, Calculation Modes
12566 @subsection Symbolic Mode
12568 @noindent
12569 @cindex Symbolic mode
12570 @cindex Inexact results
12571 Calculations are normally performed numerically wherever possible.
12572 For example, the @code{calc-sqrt} command, or @code{sqrt} function in an
12573 algebraic expression, produces a numeric answer if the argument is a
12574 number or a symbolic expression if the argument is an expression:
12575 @kbd{2 Q} pushes 1.4142 but @kbd{@key{'} x+1 @key{RET} Q} pushes @samp{sqrt(x+1)}.
12577 @kindex m s
12578 @pindex calc-symbolic-mode
12579 In @dfn{symbolic mode}, controlled by the @kbd{m s} (@code{calc-symbolic-mode})
12580 command, functions which would produce inexact, irrational results are
12581 left in symbolic form.  Thus @kbd{16 Q} pushes 4, but @kbd{2 Q} pushes
12582 @samp{sqrt(2)}.
12584 @kindex N
12585 @pindex calc-eval-num
12586 The shift-@kbd{N} (@code{calc-eval-num}) command evaluates numerically
12587 the expression at the top of the stack, by temporarily disabling
12588 @code{calc-symbolic-mode} and executing @kbd{=} (@code{calc-evaluate}).
12589 Given a numeric prefix argument, it also
12590 sets the floating-point precision to the specified value for the duration
12591 of the command.@refill
12593 To evaluate a formula numerically without expanding the variables it
12594 contains, you can use the key sequence @kbd{m s a v m s} (this uses
12595 @code{calc-alg-evaluate}, which resimplifies but doesn't evaluate
12596 variables.)
12598 @node Matrix Mode, Automatic Recomputation, Symbolic Mode, Calculation Modes
12599 @subsection Matrix and Scalar Modes
12601 @noindent
12602 @cindex Matrix mode
12603 @cindex Scalar mode
12604 Calc sometimes makes assumptions during algebraic manipulation that
12605 are awkward or incorrect when vectors and matrices are involved.
12606 Calc has two modes, @dfn{matrix mode} and @dfn{scalar mode}, which
12607 modify its behavior around vectors in useful ways.
12609 @kindex m v
12610 @pindex calc-matrix-mode
12611 Press @kbd{m v} (@code{calc-matrix-mode}) once to enter matrix mode.
12612 In this mode, all objects are assumed to be matrices unless provably
12613 otherwise.  One major effect is that Calc will no longer consider
12614 multiplication to be commutative.  (Recall that in matrix arithmetic,
12615 @samp{A*B} is not the same as @samp{B*A}.)  This assumption affects
12616 rewrite rules and algebraic simplification.  Another effect of this
12617 mode is that calculations that would normally produce constants like
12618 0 and 1 (e.g., @cite{a - a} and @cite{a / a}, respectively) will now
12619 produce function calls that represent ``generic'' zero or identity
12620 matrices: @samp{idn(0)}, @samp{idn(1)}.  The @code{idn} function
12621 @samp{idn(@var{a},@var{n})} returns @var{a} times an @var{n}x@var{n}
12622 identity matrix; if @var{n} is omitted, it doesn't know what
12623 dimension to use and so the @code{idn} call remains in symbolic
12624 form.  However, if this generic identity matrix is later combined
12625 with a matrix whose size is known, it will be converted into
12626 a true identity matrix of the appropriate size.  On the other hand,
12627 if it is combined with a scalar (as in @samp{idn(1) + 2}), Calc
12628 will assume it really was a scalar after all and produce, e.g., 3.
12630 Press @kbd{m v} a second time to get scalar mode.  Here, objects are
12631 assumed @emph{not} to be vectors or matrices unless provably so.
12632 For example, normally adding a variable to a vector, as in
12633 @samp{[x, y, z] + a}, will leave the sum in symbolic form because
12634 as far as Calc knows, @samp{a} could represent either a number or
12635 another 3-vector.  In scalar mode, @samp{a} is assumed to be a
12636 non-vector, and the addition is evaluated to @samp{[x+a, y+a, z+a]}.
12638 Press @kbd{m v} a third time to return to the normal mode of operation.
12640 If you press @kbd{m v} with a numeric prefix argument @var{n}, you
12641 get a special ``dimensioned matrix mode'' in which matrices of
12642 unknown size are assumed to be @var{n}x@var{n} square matrices.
12643 Then, the function call @samp{idn(1)} will expand into an actual
12644 matrix rather than representing a ``generic'' matrix.
12646 @cindex Declaring scalar variables
12647 Of course these modes are approximations to the true state of
12648 affairs, which is probably that some quantities will be matrices
12649 and others will be scalars.  One solution is to ``declare''
12650 certain variables or functions to be scalar-valued.
12651 @xref{Declarations}, to see how to make declarations in Calc.
12653 There is nothing stopping you from declaring a variable to be
12654 scalar and then storing a matrix in it; however, if you do, the
12655 results you get from Calc may not be valid.  Suppose you let Calc
12656 get the result @samp{[x+a, y+a, z+a]} shown above, and then stored
12657 @samp{[1, 2, 3]} in @samp{a}.  The result would not be the same as
12658 for @samp{[x, y, z] + [1, 2, 3]}, but that's because you have broken
12659 your earlier promise to Calc that @samp{a} would be scalar.
12661 Another way to mix scalars and matrices is to use selections
12662 (@pxref{Selecting Subformulas}).  Use matrix mode when operating on
12663 your formula normally; then, to apply scalar mode to a certain part
12664 of the formula without affecting the rest just select that part,
12665 change into scalar mode and press @kbd{=} to resimplify the part
12666 under this mode, then change back to matrix mode before deselecting.
12668 @node Automatic Recomputation, Working Message, Matrix Mode, Calculation Modes
12669 @subsection Automatic Recomputation
12671 @noindent
12672 The @dfn{evaluates-to} operator, @samp{=>}, has the special
12673 property that any @samp{=>} formulas on the stack are recomputed
12674 whenever variable values or mode settings that might affect them
12675 are changed.  @xref{Evaluates-To Operator}.
12677 @kindex m C
12678 @pindex calc-auto-recompute
12679 The @kbd{m C} (@code{calc-auto-recompute}) command turns this
12680 automatic recomputation on and off.  If you turn it off, Calc will
12681 not update @samp{=>} operators on the stack (nor those in the
12682 attached Embedded Mode buffer, if there is one).  They will not
12683 be updated unless you explicitly do so by pressing @kbd{=} or until
12684 you press @kbd{m C} to turn recomputation back on.  (While automatic
12685 recomputation is off, you can think of @kbd{m C m C} as a command
12686 to update all @samp{=>} operators while leaving recomputation off.)
12688 To update @samp{=>} operators in an Embedded buffer while
12689 automatic recomputation is off, use @w{@kbd{M-# u}}.
12690 @xref{Embedded Mode}.
12692 @node Working Message, , Automatic Recomputation, Calculation Modes
12693 @subsection Working Messages
12695 @noindent
12696 @cindex Performance
12697 @cindex Working messages
12698 Since the Calculator is written entirely in Emacs Lisp, which is not
12699 designed for heavy numerical work, many operations are quite slow.
12700 The Calculator normally displays the message @samp{Working...} in the
12701 echo area during any command that may be slow.  In addition, iterative
12702 operations such as square roots and trigonometric functions display the
12703 intermediate result at each step.  Both of these types of messages can
12704 be disabled if you find them distracting.
12706 @kindex m w
12707 @pindex calc-working
12708 Type @kbd{m w} (@code{calc-working}) with a numeric prefix of 0 to
12709 disable all ``working'' messages.  Use a numeric prefix of 1 to enable
12710 only the plain @samp{Working...} message.  Use a numeric prefix of 2 to
12711 see intermediate results as well.  With no numeric prefix this displays
12712 the current mode.@refill
12714 While it may seem that the ``working'' messages will slow Calc down
12715 considerably, experiments have shown that their impact is actually
12716 quite small.  But if your terminal is slow you may find that it helps
12717 to turn the messages off.
12719 @node Simplification Modes, Declarations, Calculation Modes, Mode Settings
12720 @section Simplification Modes
12722 @noindent
12723 The current @dfn{simplification mode} controls how numbers and formulas
12724 are ``normalized'' when being taken from or pushed onto the stack.
12725 Some normalizations are unavoidable, such as rounding floating-point
12726 results to the current precision, and reducing fractions to simplest
12727 form.  Others, such as simplifying a formula like @cite{a+a} (or @cite{2+3}),
12728 are done by default but can be turned off when necessary.
12730 When you press a key like @kbd{+} when @cite{2} and @cite{3} are on the
12731 stack, Calc pops these numbers, normalizes them, creates the formula
12732 @cite{2+3}, normalizes it, and pushes the result.  Of course the standard
12733 rules for normalizing @cite{2+3} will produce the result @cite{5}.
12735 Simplification mode commands consist of the lower-case @kbd{m} prefix key
12736 followed by a shifted letter.
12738 @kindex m O
12739 @pindex calc-no-simplify-mode
12740 The @kbd{m O} (@code{calc-no-simplify-mode}) command turns off all optional
12741 simplifications.  These would leave a formula like @cite{2+3} alone.  In
12742 fact, nothing except simple numbers are ever affected by normalization
12743 in this mode.
12745 @kindex m N
12746 @pindex calc-num-simplify-mode
12747 The @kbd{m N} (@code{calc-num-simplify-mode}) command turns off simplification
12748 of any formulas except those for which all arguments are constants.  For
12749 example, @cite{1+2} is simplified to @cite{3}, and @cite{a+(2-2)} is
12750 simplified to @cite{a+0} but no further, since one argument of the sum
12751 is not a constant.  Unfortunately, @cite{(a+2)-2} is @emph{not} simplified
12752 because the top-level @samp{-} operator's arguments are not both
12753 constant numbers (one of them is the formula @cite{a+2}).
12754 A constant is a number or other numeric object (such as a constant
12755 error form or modulo form), or a vector all of whose
12756 elements are constant.@refill
12758 @kindex m D
12759 @pindex calc-default-simplify-mode
12760 The @kbd{m D} (@code{calc-default-simplify-mode}) command restores the
12761 default simplifications for all formulas.  This includes many easy and
12762 fast algebraic simplifications such as @cite{a+0} to @cite{a}, and
12763 @cite{a + 2 a} to @cite{3 a}, as well as evaluating functions like
12764 @cite{@t{deriv}(x^2, x)} to @cite{2 x}.
12766 @kindex m B
12767 @pindex calc-bin-simplify-mode
12768 The @kbd{m B} (@code{calc-bin-simplify-mode}) mode applies the default
12769 simplifications to a result and then, if the result is an integer,
12770 uses the @kbd{b c} (@code{calc-clip}) command to clip the integer according
12771 to the current binary word size.  @xref{Binary Functions}.  Real numbers
12772 are rounded to the nearest integer and then clipped; other kinds of
12773 results (after the default simplifications) are left alone.
12775 @kindex m A
12776 @pindex calc-alg-simplify-mode
12777 The @kbd{m A} (@code{calc-alg-simplify-mode}) mode does algebraic
12778 simplification; it applies all the default simplifications, and also
12779 the more powerful (and slower) simplifications made by @kbd{a s}
12780 (@code{calc-simplify}).  @xref{Algebraic Simplifications}.
12782 @kindex m E
12783 @pindex calc-ext-simplify-mode
12784 The @kbd{m E} (@code{calc-ext-simplify-mode}) mode does ``extended''
12785 algebraic simplification, as by the @kbd{a e} (@code{calc-simplify-extended})
12786 command.  @xref{Unsafe Simplifications}.
12788 @kindex m U
12789 @pindex calc-units-simplify-mode
12790 The @kbd{m U} (@code{calc-units-simplify-mode}) mode does units
12791 simplification; it applies the command @kbd{u s}
12792 (@code{calc-simplify-units}), which in turn
12793 is a superset of @kbd{a s}.  In this mode, variable names which
12794 are identifiable as unit names (like @samp{mm} for ``millimeters'')
12795 are simplified with their unit definitions in mind.@refill
12797 A common technique is to set the simplification mode down to the lowest
12798 amount of simplification you will allow to be applied automatically, then
12799 use manual commands like @kbd{a s} and @kbd{c c} (@code{calc-clean}) to
12800 perform higher types of simplifications on demand.  @xref{Algebraic
12801 Definitions}, for another sample use of no-simplification mode.@refill
12803 @node Declarations, Display Modes, Simplification Modes, Mode Settings
12804 @section Declarations
12806 @noindent
12807 A @dfn{declaration} is a statement you make that promises you will
12808 use a certain variable or function in a restricted way.  This may
12809 give Calc the freedom to do things that it couldn't do if it had to
12810 take the fully general situation into account.
12812 @menu
12813 * Declaration Basics::
12814 * Kinds of Declarations::
12815 * Functions for Declarations::
12816 @end menu
12818 @node Declaration Basics, Kinds of Declarations, Declarations, Declarations
12819 @subsection Declaration Basics
12821 @noindent
12822 @kindex s d
12823 @pindex calc-declare-variable
12824 The @kbd{s d} (@code{calc-declare-variable}) command is the easiest
12825 way to make a declaration for a variable.  This command prompts for
12826 the variable name, then prompts for the declaration.  The default
12827 at the declaration prompt is the previous declaration, if any.
12828 You can edit this declaration, or press @kbd{C-k} to erase it and
12829 type a new declaration.  (Or, erase it and press @key{RET} to clear
12830 the declaration, effectively ``undeclaring'' the variable.)
12832 A declaration is in general a vector of @dfn{type symbols} and
12833 @dfn{range} values.  If there is only one type symbol or range value,
12834 you can write it directly rather than enclosing it in a vector.
12835 For example, @kbd{s d foo RET real RET} declares @code{foo} to
12836 be a real number, and @kbd{s d bar RET [int, const, [1..6]] RET}
12837 declares @code{bar} to be a constant integer between 1 and 6.
12838 (Actually, you can omit the outermost brackets and Calc will
12839 provide them for you: @kbd{s d bar RET int, const, [1..6] RET}.)
12841 @cindex @code{Decls} variable
12842 @vindex Decls
12843 Declarations in Calc are kept in a special variable called @code{Decls}.
12844 This variable encodes the set of all outstanding declarations in
12845 the form of a matrix.  Each row has two elements:  A variable or
12846 vector of variables declared by that row, and the declaration
12847 specifier as described above.  You can use the @kbd{s D} command to
12848 edit this variable if you wish to see all the declarations at once.
12849 @xref{Operations on Variables}, for a description of this command
12850 and the @kbd{s p} command that allows you to save your declarations
12851 permanently if you wish.
12853 Items being declared can also be function calls.  The arguments in
12854 the call are ignored; the effect is to say that this function returns
12855 values of the declared type for any valid arguments.  The @kbd{s d}
12856 command declares only variables, so if you wish to make a function
12857 declaration you will have to edit the @code{Decls} matrix yourself.
12859 For example, the declaration matrix
12861 @group
12862 @smallexample
12863 [ [ foo,       real       ]
12864   [ [j, k, n], int        ]
12865   [ f(1,2,3),  [0 .. inf) ] ]
12866 @end smallexample
12867 @end group
12869 @noindent
12870 declares that @code{foo} represents a real number, @code{j}, @code{k}
12871 and @code{n} represent integers, and the function @code{f} always
12872 returns a real number in the interval shown.
12874 @vindex All
12875 If there is a declaration for the variable @code{All}, then that
12876 declaration applies to all variables that are not otherwise declared.
12877 It does not apply to function names.  For example, using the row
12878 @samp{[All, real]} says that all your variables are real unless they
12879 are explicitly declared without @code{real} in some other row.
12880 The @kbd{s d} command declares @code{All} if you give a blank
12881 response to the variable-name prompt.
12883 @node Kinds of Declarations, Functions for Declarations, Declaration Basics, Declarations
12884 @subsection Kinds of Declarations
12886 @noindent
12887 The type-specifier part of a declaration (that is, the second prompt
12888 in the @kbd{s d} command) can be a type symbol, an interval, or a
12889 vector consisting of zero or more type symbols followed by zero or
12890 more intervals or numbers that represent the set of possible values
12891 for the variable.
12893 @group
12894 @smallexample
12895 [ [ a, [1, 2, 3, 4, 5] ]
12896   [ b, [1 .. 5]        ]
12897   [ c, [int, 1 .. 5]   ] ]
12898 @end smallexample
12899 @end group
12901 Here @code{a} is declared to contain one of the five integers shown;
12902 @code{b} is any number in the interval from 1 to 5 (any real number
12903 since we haven't specified), and @code{c} is any integer in that
12904 interval.  Thus the declarations for @code{a} and @code{c} are
12905 nearly equivalent (see below).
12907 The type-specifier can be the empty vector @samp{[]} to say that
12908 nothing is known about a given variable's value.  This is the same
12909 as not declaring the variable at all except that it overrides any
12910 @code{All} declaration which would otherwise apply.
12912 The initial value of @code{Decls} is the empty vector @samp{[]}.
12913 If @code{Decls} has no stored value or if the value stored in it
12914 is not valid, it is ignored and there are no declarations as far
12915 as Calc is concerned.  (The @kbd{s d} command will replace such a
12916 malformed value with a fresh empty matrix, @samp{[]}, before recording
12917 the new declaration.)  Unrecognized type symbols are ignored.
12919 The following type symbols describe what sorts of numbers will be
12920 stored in a variable:
12922 @table @code
12923 @item int
12924 Integers.
12925 @item numint
12926 Numerical integers.  (Integers or integer-valued floats.)
12927 @item frac
12928 Fractions.  (Rational numbers which are not integers.)
12929 @item rat
12930 Rational numbers.  (Either integers or fractions.)
12931 @item float
12932 Floating-point numbers.
12933 @item real
12934 Real numbers.  (Integers, fractions, or floats.  Actually,
12935 intervals and error forms with real components also count as
12936 reals here.)
12937 @item pos
12938 Positive real numbers.  (Strictly greater than zero.)
12939 @item nonneg
12940 Nonnegative real numbers.  (Greater than or equal to zero.)
12941 @item number
12942 Numbers.  (Real or complex.)
12943 @end table
12945 Calc uses this information to determine when certain simplifications
12946 of formulas are safe.  For example, @samp{(x^y)^z} cannot be
12947 simplified to @samp{x^(y z)} in general; for example,
12948 @samp{((-3)^2)^1:2} is 3, but @samp{(-3)^(2*1:2) = (-3)^1} is @i{-3}.
12949 However, this simplification @emph{is} safe if @code{z} is known
12950 to be an integer, or if @code{x} is known to be a nonnegative
12951 real number.  If you have given declarations that allow Calc to
12952 deduce either of these facts, Calc will perform this simplification
12953 of the formula.
12955 Calc can apply a certain amount of logic when using declarations.
12956 For example, @samp{(x^y)^(2n+1)} will be simplified if @code{n}
12957 has been declared @code{int}; Calc knows that an integer times an
12958 integer, plus an integer, must always be an integer.  (In fact,
12959 Calc would simplify @samp{(-x)^(2n+1)} to @samp{-(x^(2n+1))} since
12960 it is able to determine that @samp{2n+1} must be an odd integer.)
12962 Similarly, @samp{(abs(x)^y)^z} will be simplified to @samp{abs(x)^(y z)}
12963 because Calc knows that the @code{abs} function always returns a
12964 nonnegative real.  If you had a @code{myabs} function that also had
12965 this property, you could get Calc to recognize it by adding the row
12966 @samp{[myabs(), nonneg]} to the @code{Decls} matrix.
12968 One instance of this simplification is @samp{sqrt(x^2)} (since the
12969 @code{sqrt} function is effectively a one-half power).  Normally
12970 Calc leaves this formula alone.  After the command
12971 @kbd{s d x RET real RET}, however, it can simplify the formula to
12972 @samp{abs(x)}.  And after @kbd{s d x RET nonneg RET}, Calc can
12973 simplify this formula all the way to @samp{x}.
12975 If there are any intervals or real numbers in the type specifier,
12976 they comprise the set of possible values that the variable or
12977 function being declared can have.  In particular, the type symbol
12978 @code{real} is effectively the same as the range @samp{[-inf .. inf]}
12979 (note that infinity is included in the range of possible values);
12980 @code{pos} is the same as @samp{(0 .. inf]}, and @code{nonneg} is
12981 the same as @samp{[0 .. inf]}.  Saying @samp{[real, [-5 .. 5]]} is
12982 redundant because the fact that the variable is real can be
12983 deduced just from the interval, but @samp{[int, [-5 .. 5]]} and
12984 @samp{[rat, [-5 .. 5]]} are useful combinations.
12986 Note that the vector of intervals or numbers is in the same format
12987 used by Calc's set-manipulation commands.  @xref{Set Operations}.
12989 The type specifier @samp{[1, 2, 3]} is equivalent to
12990 @samp{[numint, 1, 2, 3]}, @emph{not} to @samp{[int, 1, 2, 3]}.
12991 In other words, the range of possible values means only that
12992 the variable's value must be numerically equal to a number in
12993 that range, but not that it must be equal in type as well.
12994 Calc's set operations act the same way; @samp{in(2, [1., 2., 3.])}
12995 and @samp{in(1.5, [1:2, 3:2, 5:2])} both report ``true.''
12997 If you use a conflicting combination of type specifiers, the
12998 results are unpredictable.  An example is @samp{[pos, [0 .. 5]]},
12999 where the interval does not lie in the range described by the
13000 type symbol.
13002 ``Real'' declarations mostly affect simplifications involving powers
13003 like the one described above.  Another case where they are used
13004 is in the @kbd{a P} command which returns a list of all roots of a
13005 polynomial; if the variable has been declared real, only the real
13006 roots (if any) will be included in the list.
13008 ``Integer'' declarations are used for simplifications which are valid
13009 only when certain values are integers (such as @samp{(x^y)^z}
13010 shown above).
13012 Another command that makes use of declarations is @kbd{a s}, when
13013 simplifying equations and inequalities.  It will cancel @code{x}
13014 from both sides of @samp{a x = b x} only if it is sure @code{x}
13015 is non-zero, say, because it has a @code{pos} declaration.
13016 To declare specifically that @code{x} is real and non-zero,
13017 use @samp{[[-inf .. 0), (0 .. inf]]}.  (There is no way in the
13018 current notation to say that @code{x} is nonzero but not necessarily
13019 real.)  The @kbd{a e} command does ``unsafe'' simplifications,
13020 including cancelling @samp{x} from the equation when @samp{x} is
13021 not known to be nonzero.
13023 Another set of type symbols distinguish between scalars and vectors.
13025 @table @code
13026 @item scalar
13027 The value is not a vector.
13028 @item vector
13029 The value is a vector.
13030 @item matrix
13031 The value is a matrix (a rectangular vector of vectors).
13032 @end table
13034 These type symbols can be combined with the other type symbols
13035 described above; @samp{[int, matrix]} describes an object which
13036 is a matrix of integers.
13038 Scalar/vector declarations are used to determine whether certain
13039 algebraic operations are safe.  For example, @samp{[a, b, c] + x}
13040 is normally not simplified to @samp{[a + x, b + x, c + x]}, but
13041 it will be if @code{x} has been declared @code{scalar}.  On the
13042 other hand, multiplication is usually assumed to be commutative,
13043 but the terms in @samp{x y} will never be exchanged if both @code{x}
13044 and @code{y} are known to be vectors or matrices.  (Calc currently
13045 never distinguishes between @code{vector} and @code{matrix}
13046 declarations.)
13048 @xref{Matrix Mode}, for a discussion of ``matrix mode'' and
13049 ``scalar mode,'' which are similar to declaring @samp{[All, matrix]}
13050 or @samp{[All, scalar]} but much more convenient.
13052 One more type symbol that is recognized is used with the @kbd{H a d}
13053 command for taking total derivatives of a formula.  @xref{Calculus}.
13055 @table @code
13056 @item const
13057 The value is a constant with respect to other variables.
13058 @end table
13060 Calc does not check the declarations for a variable when you store
13061 a value in it.  However, storing @i{-3.5} in a variable that has
13062 been declared @code{pos}, @code{int}, or @code{matrix} may have
13063 unexpected effects; Calc may evaluate @samp{sqrt(x^2)} to @cite{3.5}
13064 if it substitutes the value first, or to @cite{-3.5} if @code{x}
13065 was declared @code{pos} and the formula @samp{sqrt(x^2)} is
13066 simplified to @samp{x} before the value is substituted.  Before
13067 using a variable for a new purpose, it is best to use @kbd{s d}
13068 or @kbd{s D} to check to make sure you don't still have an old
13069 declaration for the variable that will conflict with its new meaning.
13071 @node Functions for Declarations, , Kinds of Declarations, Declarations
13072 @subsection Functions for Declarations
13074 @noindent
13075 Calc has a set of functions for accessing the current declarations
13076 in a convenient manner.  These functions return 1 if the argument
13077 can be shown to have the specified property, or 0 if the argument
13078 can be shown @emph{not} to have that property; otherwise they are
13079 left unevaluated.  These functions are suitable for use with rewrite
13080 rules (@pxref{Conditional Rewrite Rules}) or programming constructs
13081 (@pxref{Conditionals in Macros}).  They can be entered only using
13082 algebraic notation.  @xref{Logical Operations}, for functions
13083 that perform other tests not related to declarations.
13085 For example, @samp{dint(17)} returns 1 because 17 is an integer, as
13086 do @samp{dint(n)} and @samp{dint(2 n - 3)} if @code{n} has been declared
13087 @code{int}, but @samp{dint(2.5)} and @samp{dint(n + 0.5)} return 0.
13088 Calc consults knowledge of its own built-in functions as well as your
13089 own declarations: @samp{dint(floor(x))} returns 1.
13091 @c @starindex
13092 @tindex dint
13093 @c @starindex
13094 @tindex dnumint
13095 @c @starindex
13096 @tindex dnatnum
13097 The @code{dint} function checks if its argument is an integer.
13098 The @code{dnatnum} function checks if its argument is a natural
13099 number, i.e., a nonnegative integer.  The @code{dnumint} function
13100 checks if its argument is numerically an integer, i.e., either an
13101 integer or an integer-valued float.  Note that these and the other
13102 data type functions also accept vectors or matrices composed of
13103 suitable elements, and that real infinities @samp{inf} and @samp{-inf}
13104 are considered to be integers for the purposes of these functions.
13106 @c @starindex
13107 @tindex drat
13108 The @code{drat} function checks if its argument is rational, i.e.,
13109 an integer or fraction.  Infinities count as rational, but intervals
13110 and error forms do not.
13112 @c @starindex
13113 @tindex dreal
13114 The @code{dreal} function checks if its argument is real.  This
13115 includes integers, fractions, floats, real error forms, and intervals.
13117 @c @starindex
13118 @tindex dimag
13119 The @code{dimag} function checks if its argument is imaginary,
13120 i.e., is mathematically equal to a real number times @cite{i}.
13122 @c @starindex
13123 @tindex dpos
13124 @c @starindex
13125 @tindex dneg
13126 @c @starindex
13127 @tindex dnonneg
13128 The @code{dpos} function checks for positive (but nonzero) reals.
13129 The @code{dneg} function checks for negative reals.  The @code{dnonneg}
13130 function checks for nonnegative reals, i.e., reals greater than or
13131 equal to zero.  Note that the @kbd{a s} command can simplify an
13132 expression like @cite{x > 0} to 1 or 0 using @code{dpos}, and that
13133 @kbd{a s} is effectively applied to all conditions in rewrite rules,
13134 so the actual functions @code{dpos}, @code{dneg}, and @code{dnonneg}
13135 are rarely necessary.
13137 @c @starindex
13138 @tindex dnonzero
13139 The @code{dnonzero} function checks that its argument is nonzero.
13140 This includes all nonzero real or complex numbers, all intervals that
13141 do not include zero, all nonzero modulo forms, vectors all of whose
13142 elements are nonzero, and variables or formulas whose values can be
13143 deduced to be nonzero.  It does not include error forms, since they
13144 represent values which could be anything including zero.  (This is
13145 also the set of objects considered ``true'' in conditional contexts.)
13147 @c @starindex
13148 @tindex deven
13149 @c @starindex
13150 @tindex dodd
13151 The @code{deven} function returns 1 if its argument is known to be
13152 an even integer (or integer-valued float); it returns 0 if its argument
13153 is known not to be even (because it is known to be odd or a non-integer).
13154 The @kbd{a s} command uses this to simplify a test of the form
13155 @samp{x % 2 = 0}.  There is also an analogous @code{dodd} function.
13157 @c @starindex
13158 @tindex drange
13159 The @code{drange} function returns a set (an interval or a vector
13160 of intervals and/or numbers; @pxref{Set Operations}) that describes
13161 the set of possible values of its argument.  If the argument is
13162 a variable or a function with a declaration, the range is copied
13163 from the declaration.  Otherwise, the possible signs of the
13164 expression are determined using a method similar to @code{dpos},
13165 etc., and a suitable set like @samp{[0 .. inf]} is returned.  If
13166 the expression is not provably real, the @code{drange} function
13167 remains unevaluated.
13169 @c @starindex
13170 @tindex dscalar
13171 The @code{dscalar} function returns 1 if its argument is provably
13172 scalar, or 0 if its argument is provably non-scalar.  It is left
13173 unevaluated if this cannot be determined.  (If matrix mode or scalar
13174 mode are in effect, this function returns 1 or 0, respectively,
13175 if it has no other information.)  When Calc interprets a condition
13176 (say, in a rewrite rule) it considers an unevaluated formula to be
13177 ``false.''  Thus, @samp{dscalar(a)} is ``true'' only if @code{a} is
13178 provably scalar, and @samp{!dscalar(a)} is ``true'' only if @code{a}
13179 is provably non-scalar; both are ``false'' if there is insufficient
13180 information to tell.
13182 @node Display Modes, Language Modes, Declarations, Mode Settings
13183 @section Display Modes
13185 @noindent
13186 The commands in this section are two-key sequences beginning with the
13187 @kbd{d} prefix.  The @kbd{d l} (@code{calc-line-numbering}) and @kbd{d b}
13188 (@code{calc-line-breaking}) commands are described elsewhere;
13189 @pxref{Stack Basics} and @pxref{Normal Language Modes}, respectively.
13190 Display formats for vectors and matrices are also covered elsewhere;
13191 @pxref{Vector and Matrix Formats}.@refill
13193 One thing all display modes have in common is their treatment of the
13194 @kbd{H} prefix.  This prefix causes any mode command that would normally
13195 refresh the stack to leave the stack display alone.  The word ``Dirty''
13196 will appear in the mode line when Calc thinks the stack display may not
13197 reflect the latest mode settings.
13199 @kindex d RET
13200 @pindex calc-refresh-top
13201 The @kbd{d RET} (@code{calc-refresh-top}) command reformats the
13202 top stack entry according to all the current modes.  Positive prefix
13203 arguments reformat the top @var{n} entries; negative prefix arguments
13204 reformat the specified entry, and a prefix of zero is equivalent to
13205 @kbd{d SPC} (@code{calc-refresh}), which reformats the entire stack.
13206 For example, @kbd{H d s M-2 d RET} changes to scientific notation
13207 but reformats only the top two stack entries in the new mode.
13209 The @kbd{I} prefix has another effect on the display modes.  The mode
13210 is set only temporarily; the top stack entry is reformatted according
13211 to that mode, then the original mode setting is restored.  In other
13212 words, @kbd{I d s} is equivalent to @kbd{H d s d RET H d (@var{old mode})}.
13214 @menu
13215 * Radix Modes::
13216 * Grouping Digits::
13217 * Float Formats::
13218 * Complex Formats::
13219 * Fraction Formats::
13220 * HMS Formats::
13221 * Date Formats::
13222 * Truncating the Stack::
13223 * Justification::
13224 * Labels::
13225 @end menu
13227 @node Radix Modes, Grouping Digits, Display Modes, Display Modes
13228 @subsection Radix Modes
13230 @noindent
13231 @cindex Radix display
13232 @cindex Non-decimal numbers
13233 @cindex Decimal and non-decimal numbers
13234 Calc normally displays numbers in decimal (@dfn{base-10} or @dfn{radix-10})
13235 notation.  Calc can actually display in any radix from two (binary) to 36.
13236 When the radix is above 10, the letters @code{A} to @code{Z} are used as
13237 digits.  When entering such a number, letter keys are interpreted as
13238 potential digits rather than terminating numeric entry mode.
13240 @kindex d 2
13241 @kindex d 8
13242 @kindex d 6
13243 @kindex d 0
13244 @cindex Hexadecimal integers
13245 @cindex Octal integers
13246 The key sequences @kbd{d 2}, @kbd{d 8}, @kbd{d 6}, and @kbd{d 0} select
13247 binary, octal, hexadecimal, and decimal as the current display radix,
13248 respectively.  Numbers can always be entered in any radix, though the
13249 current radix is used as a default if you press @kbd{#} without any initial
13250 digits.  A number entered without a @kbd{#} is @emph{always} interpreted
13251 as decimal.@refill
13253 @kindex d r
13254 @pindex calc-radix
13255 To set the radix generally, use @kbd{d r} (@code{calc-radix}) and enter
13256 an integer from 2 to 36.  You can specify the radix as a numeric prefix
13257 argument; otherwise you will be prompted for it.
13259 @kindex d z
13260 @pindex calc-leading-zeros
13261 @cindex Leading zeros
13262 Integers normally are displayed with however many digits are necessary to
13263 represent the integer and no more.  The @kbd{d z} (@code{calc-leading-zeros})
13264 command causes integers to be padded out with leading zeros according to the
13265 current binary word size.  (@xref{Binary Functions}, for a discussion of
13266 word size.)  If the absolute value of the word size is @cite{w}, all integers
13267 are displayed with at least enough digits to represent @c{$2^w-1$}
13268 @cite{(2^w)-1} in the
13269 current radix.  (Larger integers will still be displayed in their entirety.)
13271 @node Grouping Digits, Float Formats, Radix Modes, Display Modes
13272 @subsection Grouping Digits
13274 @noindent
13275 @kindex d g
13276 @pindex calc-group-digits
13277 @cindex Grouping digits
13278 @cindex Digit grouping
13279 Long numbers can be hard to read if they have too many digits.  For
13280 example, the factorial of 30 is 33 digits long!  Press @kbd{d g}
13281 (@code{calc-group-digits}) to enable @dfn{grouping} mode, in which digits
13282 are displayed in clumps of 3 or 4 (depending on the current radix)
13283 separated by commas.
13285 The @kbd{d g} command toggles grouping on and off.
13286 With a numerix prefix of 0, this command displays the current state of
13287 the grouping flag; with an argument of minus one it disables grouping;
13288 with a positive argument @cite{N} it enables grouping on every @cite{N}
13289 digits.  For floating-point numbers, grouping normally occurs only
13290 before the decimal point.  A negative prefix argument @cite{-N} enables
13291 grouping every @cite{N} digits both before and after the decimal point.@refill
13293 @kindex d ,
13294 @pindex calc-group-char
13295 The @kbd{d ,} (@code{calc-group-char}) command allows you to choose any
13296 character as the grouping separator.  The default is the comma character.
13297 If you find it difficult to read vectors of large integers grouped with
13298 commas, you may wish to use spaces or some other character instead.
13299 This command takes the next character you type, whatever it is, and
13300 uses it as the digit separator.  As a special case, @kbd{d , \} selects
13301 @samp{\,} (@TeX{}'s thin-space symbol) as the digit separator.
13303 Please note that grouped numbers will not generally be parsed correctly
13304 if re-read in textual form, say by the use of @kbd{M-# y} and @kbd{M-# g}.
13305 (@xref{Kill and Yank}, for details on these commands.)  One exception is
13306 the @samp{\,} separator, which doesn't interfere with parsing because it
13307 is ignored by @TeX{} language mode.
13309 @node Float Formats, Complex Formats, Grouping Digits, Display Modes
13310 @subsection Float Formats
13312 @noindent
13313 Floating-point quantities are normally displayed in standard decimal
13314 form, with scientific notation used if the exponent is especially high
13315 or low.  All significant digits are normally displayed.  The commands
13316 in this section allow you to choose among several alternative display
13317 formats for floats.
13319 @kindex d n
13320 @pindex calc-normal-notation
13321 The @kbd{d n} (@code{calc-normal-notation}) command selects the normal
13322 display format.  All significant figures in a number are displayed.
13323 With a positive numeric prefix, numbers are rounded if necessary to
13324 that number of significant digits.  With a negative numerix prefix,
13325 the specified number of significant digits less than the current
13326 precision is used.  (Thus @kbd{C-u -2 d n} displays 10 digits if the
13327 current precision is 12.)
13329 @kindex d f
13330 @pindex calc-fix-notation
13331 The @kbd{d f} (@code{calc-fix-notation}) command selects fixed-point
13332 notation.  The numeric argument is the number of digits after the
13333 decimal point, zero or more.  This format will relax into scientific
13334 notation if a nonzero number would otherwise have been rounded all the
13335 way to zero.  Specifying a negative number of digits is the same as
13336 for a positive number, except that small nonzero numbers will be rounded
13337 to zero rather than switching to scientific notation.
13339 @kindex d s
13340 @pindex calc-sci-notation
13341 @cindex Scientific notation, display of
13342 The @kbd{d s} (@code{calc-sci-notation}) command selects scientific
13343 notation.  A positive argument sets the number of significant figures
13344 displayed, of which one will be before and the rest after the decimal
13345 point.  A negative argument works the same as for @kbd{d n} format.
13346 The default is to display all significant digits.
13348 @kindex d e
13349 @pindex calc-eng-notation
13350 @cindex Engineering notation, display of
13351 The @kbd{d e} (@code{calc-eng-notation}) command selects engineering
13352 notation.  This is similar to scientific notation except that the
13353 exponent is rounded down to a multiple of three, with from one to three
13354 digits before the decimal point.  An optional numeric prefix sets the
13355 number of significant digits to display, as for @kbd{d s}.
13357 It is important to distinguish between the current @emph{precision} and
13358 the current @emph{display format}.  After the commands @kbd{C-u 10 p}
13359 and @kbd{C-u 6 d n} the Calculator computes all results to ten
13360 significant figures but displays only six.  (In fact, intermediate
13361 calculations are often carried to one or two more significant figures,
13362 but values placed on the stack will be rounded down to ten figures.)
13363 Numbers are never actually rounded to the display precision for storage,
13364 except by commands like @kbd{C-k} and @kbd{M-# y} which operate on the
13365 actual displayed text in the Calculator buffer.
13367 @kindex d .
13368 @pindex calc-point-char
13369 The @kbd{d .} (@code{calc-point-char}) command selects the character used
13370 as a decimal point.  Normally this is a period; users in some countries
13371 may wish to change this to a comma.  Note that this is only a display
13372 style; on entry, periods must always be used to denote floating-point
13373 numbers, and commas to separate elements in a list.
13375 @node Complex Formats, Fraction Formats, Float Formats, Display Modes
13376 @subsection Complex Formats
13378 @noindent
13379 @kindex d c
13380 @pindex calc-complex-notation
13381 There are three supported notations for complex numbers in rectangular
13382 form.  The default is as a pair of real numbers enclosed in parentheses
13383 and separated by a comma: @samp{(a,b)}.  The @kbd{d c}
13384 (@code{calc-complex-notation}) command selects this style.@refill
13386 @kindex d i
13387 @pindex calc-i-notation
13388 @kindex d j
13389 @pindex calc-j-notation
13390 The other notations are @kbd{d i} (@code{calc-i-notation}), in which
13391 numbers are displayed in @samp{a+bi} form, and @kbd{d j}
13392 (@code{calc-j-notation}) which displays the form @samp{a+bj} preferred
13393 in some disciplines.@refill
13395 @cindex @code{i} variable
13396 @vindex i
13397 Complex numbers are normally entered in @samp{(a,b)} format.
13398 If you enter @samp{2+3i} as an algebraic formula, it will be stored as
13399 the formula @samp{2 + 3 * i}.  However, if you use @kbd{=} to evaluate
13400 this formula and you have not changed the variable @samp{i}, the @samp{i}
13401 will be interpreted as @samp{(0,1)} and the formula will be simplified
13402 to @samp{(2,3)}.  Other commands (like @code{calc-sin}) will @emph{not}
13403 interpret the formula @samp{2 + 3 * i} as a complex number.
13404 @xref{Variables}, under ``special constants.''@refill
13406 @node Fraction Formats, HMS Formats, Complex Formats, Display Modes
13407 @subsection Fraction Formats
13409 @noindent
13410 @kindex d o
13411 @pindex calc-over-notation
13412 Display of fractional numbers is controlled by the @kbd{d o}
13413 (@code{calc-over-notation}) command.  By default, a number like
13414 eight thirds is displayed in the form @samp{8:3}.  The @kbd{d o} command
13415 prompts for a one- or two-character format.  If you give one character,
13416 that character is used as the fraction separator.  Common separators are
13417 @samp{:} and @samp{/}.  (During input of numbers, the @kbd{:} key must be
13418 used regardless of the display format; in particular, the @kbd{/} is used
13419 for RPN-style division, @emph{not} for entering fractions.)
13421 If you give two characters, fractions use ``integer-plus-fractional-part''
13422 notation.  For example, the format @samp{+/} would display eight thirds
13423 as @samp{2+2/3}.  If two colons are present in a number being entered,
13424 the number is interpreted in this form (so that the entries @kbd{2:2:3}
13425 and @kbd{8:3} are equivalent).
13427 It is also possible to follow the one- or two-character format with
13428 a number.  For example:  @samp{:10} or @samp{+/3}.  In this case,
13429 Calc adjusts all fractions that are displayed to have the specified
13430 denominator, if possible.  Otherwise it adjusts the denominator to
13431 be a multiple of the specified value.  For example, in @samp{:6} mode
13432 the fraction @cite{1:6} will be unaffected, but @cite{2:3} will be
13433 displayed as @cite{4:6}, @cite{1:2} will be displayed as @cite{3:6},
13434 and @cite{1:8} will be displayed as @cite{3:24}.  Integers are also
13435 affected by this mode:  3 is displayed as @cite{18:6}.  Note that the
13436 format @samp{:1} writes fractions the same as @samp{:}, but it writes
13437 integers as @cite{n:1}.
13439 The fraction format does not affect the way fractions or integers are
13440 stored, only the way they appear on the screen.  The fraction format
13441 never affects floats.
13443 @node HMS Formats, Date Formats, Fraction Formats, Display Modes
13444 @subsection HMS Formats
13446 @noindent
13447 @kindex d h
13448 @pindex calc-hms-notation
13449 The @kbd{d h} (@code{calc-hms-notation}) command controls the display of
13450 HMS (hours-minutes-seconds) forms.  It prompts for a string which
13451 consists basically of an ``hours'' marker, optional punctuation, a
13452 ``minutes'' marker, more optional punctuation, and a ``seconds'' marker.
13453 Punctuation is zero or more spaces, commas, or semicolons.  The hours
13454 marker is one or more non-punctuation characters.  The minutes and
13455 seconds markers must be single non-punctuation characters.
13457 The default HMS format is @samp{@@ ' "}, producing HMS values of the form
13458 @samp{23@@ 30' 15.75"}.  The format @samp{deg, ms} would display this same
13459 value as @samp{23deg, 30m15.75s}.  During numeric entry, the @kbd{h} or @kbd{o}
13460 keys are recognized as synonyms for @kbd{@@} regardless of display format.
13461 The @kbd{m} and @kbd{s} keys are recognized as synonyms for @kbd{'} and
13462 @kbd{"}, respectively, but only if an @kbd{@@} (or @kbd{h} or @kbd{o}) has
13463 already been typed; otherwise, they have their usual meanings
13464 (@kbd{m-} prefix and @kbd{s-} prefix).  Thus, @kbd{5 "}, @kbd{0 @@ 5 "}, and
13465 @kbd{0 h 5 s} are some of the ways to enter the quantity ``five seconds.''
13466 The @kbd{'} key is recognized as ``minutes'' only if @kbd{@@} (or @kbd{h} or
13467 @kbd{o}) has already been pressed; otherwise it means to switch to algebraic
13468 entry.
13470 @node Date Formats, Truncating the Stack, HMS Formats, Display Modes
13471 @subsection Date Formats
13473 @noindent
13474 @kindex d d
13475 @pindex calc-date-notation
13476 The @kbd{d d} (@code{calc-date-notation}) command controls the display
13477 of date forms (@pxref{Date Forms}).  It prompts for a string which
13478 contains letters that represent the various parts of a date and time.
13479 To show which parts should be omitted when the form represents a pure
13480 date with no time, parts of the string can be enclosed in @samp{< >}
13481 marks.  If you don't include @samp{< >} markers in the format, Calc
13482 guesses at which parts, if any, should be omitted when formatting
13483 pure dates.
13485 The default format is:  @samp{<H:mm:SSpp >Www Mmm D, YYYY}.
13486 An example string in this format is @samp{3:32pm Wed Jan 9, 1991}.
13487 If you enter a blank format string, this default format is
13488 reestablished.
13490 Calc uses @samp{< >} notation for nameless functions as well as for
13491 dates.  @xref{Specifying Operators}.  To avoid confusion with nameless
13492 functions, your date formats should avoid using the @samp{#} character.
13494 @menu
13495 * Date Formatting Codes::
13496 * Free-Form Dates::
13497 * Standard Date Formats::
13498 @end menu
13500 @node Date Formatting Codes, Free-Form Dates, Date Formats, Date Formats
13501 @subsubsection Date Formatting Codes
13503 @noindent
13504 When displaying a date, the current date format is used.  All
13505 characters except for letters and @samp{<} and @samp{>} are
13506 copied literally when dates are formatted.  The portion between
13507 @samp{< >} markers is omitted for pure dates, or included for
13508 date/time forms.  Letters are interpreted according to the table
13509 below.
13511 When dates are read in during algebraic entry, Calc first tries to
13512 match the input string to the current format either with or without
13513 the time part.  The punctuation characters (including spaces) must
13514 match exactly; letter fields must correspond to suitable text in
13515 the input.  If this doesn't work, Calc checks if the input is a
13516 simple number; if so, the number is interpreted as a number of days
13517 since Jan 1, 1 AD.  Otherwise, Calc tries a much more relaxed and
13518 flexible algorithm which is described in the next section.
13520 Weekday names are ignored during reading.
13522 Two-digit year numbers are interpreted as lying in the range
13523 from 1941 to 2039.  Years outside that range are always
13524 entered and displayed in full.  Year numbers with a leading
13525 @samp{+} sign are always interpreted exactly, allowing the
13526 entry and display of the years 1 through 99 AD.
13528 Here is a complete list of the formatting codes for dates:
13530 @table @asis
13531 @item Y
13532 Year:  ``91'' for 1991, ``7'' for 2007, ``+23'' for 23 AD.
13533 @item YY
13534 Year:  ``91'' for 1991, ``07'' for 2007, ``+23'' for 23 AD.
13535 @item BY
13536 Year:  ``91'' for 1991, `` 7'' for 2007, ``+23'' for 23 AD.
13537 @item YYY
13538 Year:  ``1991'' for 1991, ``23'' for 23 AD.
13539 @item YYYY
13540 Year:  ``1991'' for 1991, ``+23'' for 23 AD.
13541 @item aa
13542 Year:  ``ad'' or blank.
13543 @item AA
13544 Year:  ``AD'' or blank.
13545 @item aaa
13546 Year:  ``ad '' or blank.  (Note trailing space.)
13547 @item AAA
13548 Year:  ``AD '' or blank.
13549 @item aaaa
13550 Year:  ``a.d.'' or blank.
13551 @item AAAA
13552 Year:  ``A.D.'' or blank.
13553 @item bb
13554 Year:  ``bc'' or blank.
13555 @item BB
13556 Year:  ``BC'' or blank.
13557 @item bbb
13558 Year:  `` bc'' or blank.  (Note leading space.)
13559 @item BBB
13560 Year:  `` BC'' or blank.
13561 @item bbbb
13562 Year:  ``b.c.'' or blank.
13563 @item BBBB
13564 Year:  ``B.C.'' or blank.
13565 @item M
13566 Month:  ``8'' for August.
13567 @item MM
13568 Month:  ``08'' for August.
13569 @item BM
13570 Month:  `` 8'' for August.
13571 @item MMM
13572 Month:  ``AUG'' for August.
13573 @item Mmm
13574 Month:  ``Aug'' for August.
13575 @item mmm
13576 Month:  ``aug'' for August.
13577 @item MMMM
13578 Month:  ``AUGUST'' for August.
13579 @item Mmmm
13580 Month:  ``August'' for August.
13581 @item D
13582 Day:  ``7'' for 7th day of month.
13583 @item DD
13584 Day:  ``07'' for 7th day of month.
13585 @item BD
13586 Day:  `` 7'' for 7th day of month.
13587 @item W
13588 Weekday:  ``0'' for Sunday, ``6'' for Saturday.
13589 @item WWW
13590 Weekday:  ``SUN'' for Sunday.
13591 @item Www
13592 Weekday:  ``Sun'' for Sunday.
13593 @item www
13594 Weekday:  ``sun'' for Sunday.
13595 @item WWWW
13596 Weekday:  ``SUNDAY'' for Sunday.
13597 @item Wwww
13598 Weekday:  ``Sunday'' for Sunday.
13599 @item d
13600 Day of year:  ``34'' for Feb. 3.
13601 @item ddd
13602 Day of year:  ``034'' for Feb. 3.
13603 @item bdd
13604 Day of year:  `` 34'' for Feb. 3.
13605 @item h
13606 Hour:  ``5'' for 5 AM; ``17'' for 5 PM.
13607 @item hh
13608 Hour:  ``05'' for 5 AM; ``17'' for 5 PM.
13609 @item bh
13610 Hour:  `` 5'' for 5 AM; ``17'' for 5 PM.
13611 @item H
13612 Hour:  ``5'' for 5 AM and 5 PM.
13613 @item HH
13614 Hour:  ``05'' for 5 AM and 5 PM.
13615 @item BH
13616 Hour:  `` 5'' for 5 AM and 5 PM.
13617 @item p
13618 AM/PM:  ``a'' or ``p''.
13619 @item P
13620 AM/PM:  ``A'' or ``P''.
13621 @item pp
13622 AM/PM:  ``am'' or ``pm''.
13623 @item PP
13624 AM/PM:  ``AM'' or ``PM''.
13625 @item pppp
13626 AM/PM:  ``a.m.'' or ``p.m.''.
13627 @item PPPP
13628 AM/PM:  ``A.M.'' or ``P.M.''.
13629 @item m
13630 Minutes:  ``7'' for 7.
13631 @item mm
13632 Minutes:  ``07'' for 7.
13633 @item bm
13634 Minutes:  `` 7'' for 7.
13635 @item s
13636 Seconds:  ``7'' for 7;  ``7.23'' for 7.23.
13637 @item ss
13638 Seconds:  ``07'' for 7;  ``07.23'' for 7.23.
13639 @item bs
13640 Seconds:  `` 7'' for 7;  `` 7.23'' for 7.23.
13641 @item SS
13642 Optional seconds:  ``07'' for 7;  blank for 0.
13643 @item BS
13644 Optional seconds:  `` 7'' for 7;  blank for 0.
13645 @item N
13646 Numeric date/time:  ``726842.25'' for 6:00am Wed Jan 9, 1991.
13647 @item n
13648 Numeric date:  ``726842'' for any time on Wed Jan 9, 1991.
13649 @item J
13650 Julian date/time:  ``2448265.75'' for 6:00am Wed Jan 9, 1991.
13651 @item j
13652 Julian date:  ``2448266'' for any time on Wed Jan 9, 1991.
13653 @item U
13654 Unix time:  ``663400800'' for 6:00am Wed Jan 9, 1991.
13655 @item X
13656 Brackets suppression.  An ``X'' at the front of the format
13657 causes the surrounding @w{@samp{< >}} delimiters to be omitted
13658 when formatting dates.  Note that the brackets are still
13659 required for algebraic entry.
13660 @end table
13662 If ``SS'' or ``BS'' (optional seconds) is preceded by a colon, the
13663 colon is also omitted if the seconds part is zero.
13665 If ``bb,'' ``bbb'' or ``bbbb'' or their upper-case equivalents
13666 appear in the format, then negative year numbers are displayed
13667 without a minus sign.  Note that ``aa'' and ``bb'' are mutually
13668 exclusive.  Some typical usages would be @samp{YYYY AABB};
13669 @samp{AAAYYYYBBB}; @samp{YYYYBBB}.
13671 The formats ``YY,'' ``YYYY,'' ``MM,'' ``DD,'' ``ddd,'' ``hh,'' ``HH,''
13672 ``mm,'' ``ss,'' and ``SS'' actually match any number of digits during
13673 reading unless several of these codes are strung together with no
13674 punctuation in between, in which case the input must have exactly as
13675 many digits as there are letters in the format.
13677 The ``j,'' ``J,'' and ``U'' formats do not make any time zone
13678 adjustment.  They effectively use @samp{julian(x,0)} and
13679 @samp{unixtime(x,0)} to make the conversion; @pxref{Date Arithmetic}.
13681 @node Free-Form Dates, Standard Date Formats, Date Formatting Codes, Date Formats
13682 @subsubsection Free-Form Dates
13684 @noindent
13685 When reading a date form during algebraic entry, Calc falls back
13686 on the algorithm described here if the input does not exactly
13687 match the current date format.  This algorithm generally
13688 ``does the right thing'' and you don't have to worry about it,
13689 but it is described here in full detail for the curious.
13691 Calc does not distinguish between upper- and lower-case letters
13692 while interpreting dates.
13694 First, the time portion, if present, is located somewhere in the
13695 text and then removed.  The remaining text is then interpreted as
13696 the date.
13698 A time is of the form @samp{hh:mm:ss}, possibly with the seconds
13699 part omitted and possibly with an AM/PM indicator added to indicate
13700 12-hour time.  If the AM/PM is present, the minutes may also be
13701 omitted.  The AM/PM part may be any of the words @samp{am},
13702 @samp{pm}, @samp{noon}, or @samp{midnight}; each of these may be
13703 abbreviated to one letter, and the alternate forms @samp{a.m.},
13704 @samp{p.m.}, and @samp{mid} are also understood.  Obviously
13705 @samp{noon} and @samp{midnight} are allowed only on 12:00:00.
13706 The words @samp{noon}, @samp{mid}, and @samp{midnight} are also
13707 recognized with no number attached.
13709 If there is no AM/PM indicator, the time is interpreted in 24-hour
13710 format.
13712 To read the date portion, all words and numbers are isolated
13713 from the string; other characters are ignored.  All words must
13714 be either month names or day-of-week names (the latter of which
13715 are ignored).  Names can be written in full or as three-letter
13716 abbreviations.
13718 Large numbers, or numbers with @samp{+} or @samp{-} signs,
13719 are interpreted as years.  If one of the other numbers is
13720 greater than 12, then that must be the day and the remaining
13721 number in the input is therefore the month.  Otherwise, Calc
13722 assumes the month, day and year are in the same order that they
13723 appear in the current date format.  If the year is omitted, the
13724 current year is taken from the system clock.
13726 If there are too many or too few numbers, or any unrecognizable
13727 words, then the input is rejected.
13729 If there are any large numbers (of five digits or more) other than
13730 the year, they are ignored on the assumption that they are something
13731 like Julian dates that were included along with the traditional
13732 date components when the date was formatted.
13734 One of the words @samp{ad}, @samp{a.d.}, @samp{bc}, or @samp{b.c.}
13735 may optionally be used; the latter two are equivalent to a
13736 minus sign on the year value.
13738 If you always enter a four-digit year, and use a name instead
13739 of a number for the month, there is no danger of ambiguity.
13741 @node Standard Date Formats, , Free-Form Dates, Date Formats
13742 @subsubsection Standard Date Formats
13744 @noindent
13745 There are actually ten standard date formats, numbered 0 through 9.
13746 Entering a blank line at the @kbd{d d} command's prompt gives
13747 you format number 1, Calc's usual format.  You can enter any digit
13748 to select the other formats.
13750 To create your own standard date formats, give a numeric prefix
13751 argument from 0 to 9 to the @w{@kbd{d d}} command.  The format you
13752 enter will be recorded as the new standard format of that
13753 number, as well as becoming the new current date format.
13754 You can save your formats permanently with the @w{@kbd{m m}}
13755 command (@pxref{Mode Settings}).
13757 @table @asis
13758 @item 0
13759 @samp{N}  (Numerical format)
13760 @item 1
13761 @samp{<H:mm:SSpp >Www Mmm D, YYYY}  (American format)
13762 @item 2
13763 @samp{D Mmm YYYY<, h:mm:SS>}  (European format)
13764 @item 3
13765 @samp{Www Mmm BD< hh:mm:ss> YYYY}  (Unix written date format)
13766 @item 4
13767 @samp{M/D/Y< H:mm:SSpp>}  (American slashed format)
13768 @item 5
13769 @samp{D.M.Y< h:mm:SS>}  (European dotted format)
13770 @item 6
13771 @samp{M-D-Y< H:mm:SSpp>}  (American dashed format)
13772 @item 7
13773 @samp{D-M-Y< h:mm:SS>}  (European dashed format)
13774 @item 8
13775 @samp{j<, h:mm:ss>}  (Julian day plus time)
13776 @item 9
13777 @samp{YYddd< hh:mm:ss>}  (Year-day format)
13778 @end table
13780 @node Truncating the Stack, Justification, Date Formats, Display Modes
13781 @subsection Truncating the Stack
13783 @noindent
13784 @kindex d t
13785 @pindex calc-truncate-stack
13786 @cindex Truncating the stack
13787 @cindex Narrowing the stack
13788 The @kbd{d t} (@code{calc-truncate-stack}) command moves the @samp{.}@:
13789 line that marks the top-of-stack up or down in the Calculator buffer.
13790 The number right above that line is considered to the be at the top of
13791 the stack.  Any numbers below that line are ``hidden'' from all stack
13792 operations.  This is similar to the Emacs ``narrowing'' feature, except
13793 that the values below the @samp{.} are @emph{visible}, just temporarily
13794 frozen.  This feature allows you to keep several independent calculations
13795 running at once in different parts of the stack, or to apply a certain
13796 command to an element buried deep in the stack.@refill
13798 Pressing @kbd{d t} by itself moves the @samp{.} to the line the cursor
13799 is on.  Thus, this line and all those below it become hidden.  To un-hide
13800 these lines, move down to the end of the buffer and press @w{@kbd{d t}}.
13801 With a positive numeric prefix argument @cite{n}, @kbd{d t} hides the
13802 bottom @cite{n} values in the buffer.  With a negative argument, it hides
13803 all but the top @cite{n} values.  With an argument of zero, it hides zero
13804 values, i.e., moves the @samp{.} all the way down to the bottom.@refill
13806 @kindex d [
13807 @pindex calc-truncate-up
13808 @kindex d ]
13809 @pindex calc-truncate-down
13810 The @kbd{d [} (@code{calc-truncate-up}) and @kbd{d ]}
13811 (@code{calc-truncate-down}) commands move the @samp{.} up or down one
13812 line at a time (or several lines with a prefix argument).@refill
13814 @node Justification, Labels, Truncating the Stack, Display Modes
13815 @subsection Justification
13817 @noindent
13818 @kindex d <
13819 @pindex calc-left-justify
13820 @kindex d =
13821 @pindex calc-center-justify
13822 @kindex d >
13823 @pindex calc-right-justify
13824 Values on the stack are normally left-justified in the window.  You can
13825 control this arrangement by typing @kbd{d <} (@code{calc-left-justify}),
13826 @kbd{d >} (@code{calc-right-justify}), or @kbd{d =}
13827 (@code{calc-center-justify}).  For example, in right-justification mode,
13828 stack entries are displayed flush-right against the right edge of the
13829 window.@refill
13831 If you change the width of the Calculator window you may have to type
13832 @kbd{d SPC} (@code{calc-refresh}) to re-align right-justified or centered
13833 text.
13835 Right-justification is especially useful together with fixed-point
13836 notation (see @code{d f}; @code{calc-fix-notation}).  With these modes
13837 together, the decimal points on numbers will always line up.
13839 With a numeric prefix argument, the justification commands give you
13840 a little extra control over the display.  The argument specifies the
13841 horizontal ``origin'' of a display line.  It is also possible to
13842 specify a maximum line width using the @kbd{d b} command (@pxref{Normal
13843 Language Modes}).  For reference, the precise rules for formatting and
13844 breaking lines are given below.  Notice that the interaction between
13845 origin and line width is slightly different in each justification
13846 mode.
13848 In left-justified mode, the line is indented by a number of spaces
13849 given by the origin (default zero).  If the result is longer than the
13850 maximum line width, if given, or too wide to fit in the Calc window
13851 otherwise, then it is broken into lines which will fit; each broken
13852 line is indented to the origin.
13854 In right-justified mode, lines are shifted right so that the rightmost
13855 character is just before the origin, or just before the current
13856 window width if no origin was specified.  If the line is too long
13857 for this, then it is broken; the current line width is used, if
13858 specified, or else the origin is used as a width if that is
13859 specified, or else the line is broken to fit in the window.
13861 In centering mode, the origin is the column number of the center of
13862 each stack entry.  If a line width is specified, lines will not be
13863 allowed to go past that width; Calc will either indent less or
13864 break the lines if necessary.  If no origin is specified, half the
13865 line width or Calc window width is used.
13867 Note that, in each case, if line numbering is enabled the display
13868 is indented an additional four spaces to make room for the line
13869 number.  The width of the line number is taken into account when
13870 positioning according to the current Calc window width, but not
13871 when positioning by explicit origins and widths.  In the latter
13872 case, the display is formatted as specified, and then uniformly
13873 shifted over four spaces to fit the line numbers.
13875 @node Labels, , Justification, Display Modes
13876 @subsection Labels
13878 @noindent
13879 @kindex d @{
13880 @pindex calc-left-label
13881 The @kbd{d @{} (@code{calc-left-label}) command prompts for a string,
13882 then displays that string to the left of every stack entry.  If the
13883 entries are left-justified (@pxref{Justification}), then they will
13884 appear immediately after the label (unless you specified an origin
13885 greater than the length of the label).  If the entries are centered
13886 or right-justified, the label appears on the far left and does not
13887 affect the horizontal position of the stack entry.
13889 Give a blank string (with @kbd{d @{ @key{RET}}) to turn the label off.
13891 @kindex d @}
13892 @pindex calc-right-label
13893 The @kbd{d @}} (@code{calc-right-label}) command similarly adds a
13894 label on the righthand side.  It does not affect positioning of
13895 the stack entries unless they are right-justified.  Also, if both
13896 a line width and an origin are given in right-justified mode, the
13897 stack entry is justified to the origin and the righthand label is
13898 justified to the line width.
13900 One application of labels would be to add equation numbers to
13901 formulas you are manipulating in Calc and then copying into a
13902 document (possibly using Embedded Mode).  The equations would
13903 typically be centered, and the equation numbers would be on the
13904 left or right as you prefer.
13906 @node Language Modes, Modes Variable, Display Modes, Mode Settings
13907 @section Language Modes
13909 @noindent
13910 The commands in this section change Calc to use a different notation for
13911 entry and display of formulas, corresponding to the conventions of some
13912 other common language such as Pascal or @TeX{}.  Objects displayed on the
13913 stack or yanked from the Calculator to an editing buffer will be formatted
13914 in the current language; objects entered in algebraic entry or yanked from
13915 another buffer will be interpreted according to the current language.
13917 The current language has no effect on things written to or read from the
13918 trail buffer, nor does it affect numeric entry.  Only algebraic entry is
13919 affected.  You can make even algebraic entry ignore the current language
13920 and use the standard notation by giving a numeric prefix, e.g., @kbd{C-u '}.
13922 For example, suppose the formula @samp{2*a[1] + atan(a[2])} occurs in a C
13923 program; elsewhere in the program you need the derivatives of this formula
13924 with respect to @samp{a[1]} and @samp{a[2]}.  First, type @kbd{d C}
13925 to switch to C notation.  Now use @code{C-u M-# g} to grab the formula
13926 into the Calculator, @kbd{a d a[1] @key{RET}} to differentiate with respect
13927 to the first variable, and @kbd{M-# y} to yank the formula for the derivative
13928 back into your C program.  Press @kbd{U} to undo the differentiation and
13929 repeat with @kbd{a d a[2] @key{RET}} for the other derivative.
13931 Without being switched into C mode first, Calc would have misinterpreted
13932 the brackets in @samp{a[1]} and @samp{a[2]}, would not have known that
13933 @code{atan} was equivalent to Calc's built-in @code{arctan} function,
13934 and would have written the formula back with notations (like implicit
13935 multiplication) which would not have been legal for a C program.
13937 As another example, suppose you are maintaining a C program and a @TeX{}
13938 document, each of which needs a copy of the same formula.  You can grab the
13939 formula from the program in C mode, switch to @TeX{} mode, and yank the
13940 formula into the document in @TeX{} math-mode format.
13942 Language modes are selected by typing the letter @kbd{d} followed by a
13943 shifted letter key.
13945 @menu
13946 * Normal Language Modes::
13947 * C FORTRAN Pascal::
13948 * TeX Language Mode::
13949 * Eqn Language Mode::
13950 * Mathematica Language Mode::
13951 * Maple Language Mode::
13952 * Compositions::
13953 * Syntax Tables::
13954 @end menu
13956 @node Normal Language Modes, C FORTRAN Pascal, Language Modes, Language Modes
13957 @subsection Normal Language Modes
13959 @noindent
13960 @kindex d N
13961 @pindex calc-normal-language
13962 The @kbd{d N} (@code{calc-normal-language}) command selects the usual
13963 notation for Calc formulas, as described in the rest of this manual.
13964 Matrices are displayed in a multi-line tabular format, but all other
13965 objects are written in linear form, as they would be typed from the
13966 keyboard.
13968 @kindex d O
13969 @pindex calc-flat-language
13970 @cindex Matrix display
13971 The @kbd{d O} (@code{calc-flat-language}) command selects a language
13972 identical with the normal one, except that matrices are written in
13973 one-line form along with everything else.  In some applications this
13974 form may be more suitable for yanking data into other buffers.
13976 @kindex d b
13977 @pindex calc-line-breaking
13978 @cindex Line breaking
13979 @cindex Breaking up long lines
13980 Even in one-line mode, long formulas or vectors will still be split
13981 across multiple lines if they exceed the width of the Calculator window.
13982 The @kbd{d b} (@code{calc-line-breaking}) command turns this line-breaking
13983 feature on and off.  (It works independently of the current language.)
13984 If you give a numeric prefix argument of five or greater to the @kbd{d b}
13985 command, that argument will specify the line width used when breaking
13986 long lines.
13988 @kindex d B
13989 @pindex calc-big-language
13990 The @kbd{d B} (@code{calc-big-language}) command selects a language
13991 which uses textual approximations to various mathematical notations,
13992 such as powers, quotients, and square roots:
13994 @example
13995   ____________
13996  | a + 1    2
13997  | ----- + c
13998 \|   b
13999 @end example
14001 @noindent
14002 in place of @samp{sqrt((a+1)/b + c^2)}.
14004 Subscripts like @samp{a_i} are displayed as actual subscripts in ``big''
14005 mode.  Double subscripts, @samp{a_i_j} (@samp{subscr(subscr(a, i), j)})
14006 are displayed as @samp{a} with subscripts separated by commas:
14007 @samp{i, j}.  They must still be entered in the usual underscore
14008 notation.
14010 One slight ambiguity of Big notation is that
14012 @example
14013   3
14014 - -
14015   4
14016 @end example
14018 @noindent
14019 can represent either the negative rational number @cite{-3:4}, or the
14020 actual expression @samp{-(3/4)}; but the latter formula would normally
14021 never be displayed because it would immediately be evaluated to
14022 @cite{-3:4} or @cite{-0.75}, so this ambiguity is not a problem in
14023 typical use.
14025 Non-decimal numbers are displayed with subscripts.  Thus there is no
14026 way to tell the difference between @samp{16#C2} and @samp{C2_16},
14027 though generally you will know which interpretation is correct.
14028 Logarithms @samp{log(x,b)} and @samp{log10(x)} also use subscripts
14029 in Big mode.
14031 In Big mode, stack entries often take up several lines.  To aid
14032 readability, stack entries are separated by a blank line in this mode.
14033 You may find it useful to expand the Calc window's height using
14034 @kbd{C-x ^} (@code{enlarge-window}) or to make the Calc window the only
14035 one on the screen with @kbd{C-x 1} (@code{delete-other-windows}).
14037 Long lines are currently not rearranged to fit the window width in
14038 Big mode, so you may need to use the @kbd{<} and @kbd{>} keys
14039 to scroll across a wide formula.  For really big formulas, you may
14040 even need to use @kbd{@{} and @kbd{@}} to scroll up and down.
14042 @kindex d U
14043 @pindex calc-unformatted-language
14044 The @kbd{d U} (@code{calc-unformatted-language}) command altogether disables
14045 the use of operator notation in formulas.  In this mode, the formula
14046 shown above would be displayed:
14048 @example
14049 sqrt(add(div(add(a, 1), b), pow(c, 2)))
14050 @end example
14052 These four modes differ only in display format, not in the format
14053 expected for algebraic entry.  The standard Calc operators work in
14054 all four modes, and unformatted notation works in any language mode
14055 (except that Mathematica mode expects square brackets instead of
14056 parentheses).
14058 @node C FORTRAN Pascal, TeX Language Mode, Normal Language Modes, Language Modes
14059 @subsection C, FORTRAN, and Pascal Modes
14061 @noindent
14062 @kindex d C
14063 @pindex calc-c-language
14064 @cindex C language
14065 The @kbd{d C} (@code{calc-c-language}) command selects the conventions
14066 of the C language for display and entry of formulas.  This differs from
14067 the normal language mode in a variety of (mostly minor) ways.  In
14068 particular, C language operators and operator precedences are used in
14069 place of Calc's usual ones.  For example, @samp{a^b} means @samp{xor(a,b)}
14070 in C mode; a value raised to a power is written as a function call,
14071 @samp{pow(a,b)}.
14073 In C mode, vectors and matrices use curly braces instead of brackets.
14074 Octal and hexadecimal values are written with leading @samp{0} or @samp{0x}
14075 rather than using the @samp{#} symbol.  Array subscripting is
14076 translated into @code{subscr} calls, so that @samp{a[i]} in C
14077 mode is the same as @samp{a_i} in normal mode.  Assignments
14078 turn into the @code{assign} function, which Calc normally displays
14079 using the @samp{:=} symbol.
14081 The variables @code{var-pi} and @code{var-e} would be displayed @samp{pi}
14082 and @samp{e} in normal mode, but in C mode they are displayed as
14083 @samp{M_PI} and @samp{M_E}, corresponding to the names of constants
14084 typically provided in the @file{<math.h>} header.  Functions whose
14085 names are different in C are translated automatically for entry and
14086 display purposes.  For example, entering @samp{asin(x)} will push the
14087 formula @samp{arcsin(x)} onto the stack; this formula will be displayed
14088 as @samp{asin(x)} as long as C mode is in effect.
14090 @kindex d P
14091 @pindex calc-pascal-language
14092 @cindex Pascal language
14093 The @kbd{d P} (@code{calc-pascal-language}) command selects Pascal
14094 conventions.  Like C mode, Pascal mode interprets array brackets and uses
14095 a different table of operators.  Hexadecimal numbers are entered and
14096 displayed with a preceding dollar sign.  (Thus the regular meaning of
14097 @kbd{$2} during algebraic entry does not work in Pascal mode, though
14098 @kbd{$} (and @kbd{$$}, etc.) not followed by digits works the same as
14099 always.)  No special provisions are made for other non-decimal numbers,
14100 vectors, and so on, since there is no universally accepted standard way
14101 of handling these in Pascal.
14103 @kindex d F
14104 @pindex calc-fortran-language
14105 @cindex FORTRAN language
14106 The @kbd{d F} (@code{calc-fortran-language}) command selects FORTRAN
14107 conventions.  Various function names are transformed into FORTRAN
14108 equivalents.  Vectors are written as @samp{/1, 2, 3/}, and may be
14109 entered this way or using square brackets.  Since FORTRAN uses round
14110 parentheses for both function calls and array subscripts, Calc displays
14111 both in the same way; @samp{a(i)} is interpreted as a function call
14112 upon reading, and subscripts must be entered as @samp{subscr(a, i)}.
14113 Also, if the variable @code{a} has been declared to have type
14114 @code{vector} or @code{matrix} then @samp{a(i)} will be parsed as a
14115 subscript.  (@xref{Declarations}.)  Usually it doesn't matter, though;
14116 if you enter the subscript expression @samp{a(i)} and Calc interprets
14117 it as a function call, you'll never know the difference unless you
14118 switch to another language mode or replace @code{a} with an actual
14119 vector (or unless @code{a} happens to be the name of a built-in
14120 function!).
14122 Underscores are allowed in variable and function names in all of these
14123 language modes.  The underscore here is equivalent to the @samp{#} in
14124 normal mode, or to hyphens in the underlying Emacs Lisp variable names.
14126 FORTRAN and Pascal modes normally do not adjust the case of letters in
14127 formulas.  Most built-in Calc names use lower-case letters.  If you use a
14128 positive numeric prefix argument with @kbd{d P} or @kbd{d F}, these
14129 modes will use upper-case letters exclusively for display, and will
14130 convert to lower-case on input.  With a negative prefix, these modes
14131 convert to lower-case for display and input.
14133 @node TeX Language Mode, Eqn Language Mode, C FORTRAN Pascal, Language Modes
14134 @subsection @TeX{} Language Mode
14136 @noindent
14137 @kindex d T
14138 @pindex calc-tex-language
14139 @cindex TeX language
14140 The @kbd{d T} (@code{calc-tex-language}) command selects the conventions
14141 of ``math mode'' in the @TeX{} typesetting language, by Donald Knuth.
14142 Formulas are entered
14143 and displayed in @TeX{} notation, as in @samp{\sin\left( a \over b \right)}.
14144 Math formulas are usually enclosed by @samp{$ $} signs in @TeX{}; these
14145 should be omitted when interfacing with Calc.  To Calc, the @samp{$} sign
14146 has the same meaning it always does in algebraic formulas (a reference to
14147 an existing entry on the stack).@refill
14149 Complex numbers are displayed as in @samp{3 + 4i}.  Fractions and
14150 quotients are written using @code{\over};
14151 binomial coefficients are written with @code{\choose}.
14152 Interval forms are written with @code{\ldots}, and
14153 error forms are written with @code{\pm}.
14154 Absolute values are written as in @samp{|x + 1|}, and the floor and
14155 ceiling functions are written with @code{\lfloor}, @code{\rfloor}, etc.
14156 The words @code{\left} and @code{\right} are ignored when reading
14157 formulas in @TeX{} mode.  Both @code{inf} and @code{uinf} are written
14158 as @code{\infty}; when read, @code{\infty} always translates to
14159 @code{inf}.@refill
14161 Function calls are written the usual way, with the function name followed
14162 by the arguments in parentheses.  However, functions for which @TeX{} has
14163 special names (like @code{\sin}) will use curly braces instead of
14164 parentheses for very simple arguments.  During input, curly braces and
14165 parentheses work equally well for grouping, but when the document is
14166 formatted the curly braces will be invisible.  Thus the printed result is
14167 @c{$\sin{2 x}$}
14168 @cite{sin 2x} but @c{$\sin(2 + x)$}
14169 @cite{sin(2 + x)}.
14171 Function and variable names not treated specially by @TeX{} are simply
14172 written out as-is, which will cause them to come out in italic letters
14173 in the printed document.  If you invoke @kbd{d T} with a positive numeric
14174 prefix argument, names of more than one character will instead be written
14175 @samp{\hbox@{@var{name}@}}.  The @samp{\hbox@{ @}} notation is ignored
14176 during reading.  If you use a negative prefix argument, such function
14177 names are written @samp{\@var{name}}, and function names that begin
14178 with @code{\} during reading have the @code{\} removed.  (Note that
14179 in this mode, long variable names are still written with @code{\hbox}.
14180 However, you can always make an actual variable name like @code{\bar}
14181 in any @TeX{} mode.)
14183 During reading, text of the form @samp{\matrix@{ ...@: @}} is replaced
14184 by @samp{[ ...@: ]}.  The same also applies to @code{\pmatrix} and
14185 @code{\bmatrix}.  The symbol @samp{&} is interpreted as a comma,
14186 and the symbols @samp{\cr} and @samp{\\} are interpreted as semicolons.
14187 During output, matrices are displayed in @samp{\matrix@{ a & b \\ c & d@}}
14188 format; you may need to edit this afterwards to change @code{\matrix}
14189 to @code{\pmatrix} or @code{\\} to @code{\cr}.
14191 Accents like @code{\tilde} and @code{\bar} translate into function
14192 calls internally (@samp{tilde(x)}, @samp{bar(x)}).  The @code{\underline}
14193 sequence is treated as an accent.  The @code{\vec} accent corresponds
14194 to the function name @code{Vec}, because @code{vec} is the name of
14195 a built-in Calc function.  The following table shows the accents
14196 in Calc, @TeX{}, and @dfn{eqn} (described in the next section):
14198 @iftex
14199 @begingroup
14200 @let@calcindexershow=@calcindexernoshow  @c Suppress marginal notes
14201 @let@calcindexersh=@calcindexernoshow
14202 @end iftex
14203 @c @starindex
14204 @tindex acute
14205 @c @starindex
14206 @tindex bar
14207 @c @starindex
14208 @tindex breve
14209 @c @starindex
14210 @tindex check
14211 @c @starindex
14212 @tindex dot
14213 @c @starindex
14214 @tindex dotdot
14215 @c @starindex
14216 @tindex dyad
14217 @c @starindex
14218 @tindex grave
14219 @c @starindex
14220 @tindex hat
14221 @c @starindex
14222 @tindex Prime
14223 @c @starindex
14224 @tindex tilde
14225 @c @starindex
14226 @tindex under
14227 @c @starindex
14228 @tindex Vec
14229 @iftex
14230 @endgroup
14231 @end iftex
14232 @example
14233 Calc      TeX           eqn
14234 ----      ---           ---
14235 acute     \acute
14236 bar       \bar          bar
14237 breve     \breve        
14238 check     \check
14239 dot       \dot          dot
14240 dotdot    \ddot         dotdot
14241 dyad                    dyad
14242 grave     \grave
14243 hat       \hat          hat
14244 Prime                   prime
14245 tilde     \tilde        tilde
14246 under     \underline    under
14247 Vec       \vec          vec
14248 @end example
14250 The @samp{=>} (evaluates-to) operator appears as a @code{\to} symbol:
14251 @samp{@{@var{a} \to @var{b}@}}.  @TeX{} defines @code{\to} as an
14252 alias for @code{\rightarrow}.  However, if the @samp{=>} is the
14253 top-level expression being formatted, a slightly different notation
14254 is used:  @samp{\evalto @var{a} \to @var{b}}.  The @code{\evalto}
14255 word is ignored by Calc's input routines, and is undefined in @TeX{}.
14256 You will typically want to include one of the following definitions
14257 at the top of a @TeX{} file that uses @code{\evalto}:
14259 @example
14260 \def\evalto@{@}
14261 \def\evalto#1\to@{@}
14262 @end example
14264 The first definition formats evaluates-to operators in the usual
14265 way.  The second causes only the @var{b} part to appear in the
14266 printed document; the @var{a} part and the arrow are hidden.
14267 Another definition you may wish to use is @samp{\let\to=\Rightarrow}
14268 which causes @code{\to} to appear more like Calc's @samp{=>} symbol.
14269 @xref{Evaluates-To Operator}, for a discussion of @code{evalto}.
14271 The complete set of @TeX{} control sequences that are ignored during
14272 reading is:
14274 @example
14275 \hbox  \mbox  \text  \left  \right
14276 \,  \>  \:  \;  \!  \quad  \qquad  \hfil  \hfill
14277 \displaystyle  \textstyle  \dsize  \tsize
14278 \scriptstyle  \scriptscriptstyle  \ssize  \ssize
14279 \rm  \bf  \it  \sl  \roman  \bold  \italic  \slanted
14280 \cal  \mit  \Cal  \Bbb  \frak  \goth
14281 \evalto
14282 @end example
14284 Note that, because these symbols are ignored, reading a @TeX{} formula
14285 into Calc and writing it back out may lose spacing and font information.
14287 Also, the ``discretionary multiplication sign'' @samp{\*} is read
14288 the same as @samp{*}.
14290 @ifinfo
14291 The @TeX{} version of this manual includes some printed examples at the
14292 end of this section.
14293 @end ifinfo
14294 @iftex
14295 Here are some examples of how various Calc formulas are formatted in @TeX{}:
14297 @group
14298 @example
14299 sin(a^2 / b_i)
14300 \sin\left( {a^2 \over b_i} \right)
14301 @end example
14302 @tex
14303 \let\rm\goodrm
14304 $$ \sin\left( a^2 \over b_i \right) $$
14305 @end tex
14306 @sp 1
14307 @end group
14309 @group
14310 @example
14311 [(3, 4), 3:4, 3 +/- 4, [3 .. inf)]
14312 [3 + 4i, @{3 \over 4@}, 3 \pm 4, [3 \ldots \infty)]
14313 @end example
14314 @tex
14315 \turnoffactive
14316 $$ [3 + 4i, {3 \over 4}, 3 \pm 4, [ 3 \ldots \infty)] $$
14317 @end tex
14318 @sp 1
14319 @end group
14321 @group
14322 @example
14323 [abs(a), abs(a / b), floor(a), ceil(a / b)]
14324 [|a|, \left| a \over b \right|,
14325  \lfloor a \rfloor, \left\lceil a \over b \right\rceil]
14326 @end example
14327 @tex
14328 $$ [|a|, \left| a \over b \right|,
14329     \lfloor a \rfloor, \left\lceil a \over b \right\rceil] $$
14330 @end tex
14331 @sp 1
14332 @end group
14334 @group
14335 @example
14336 [sin(a), sin(2 a), sin(2 + a), sin(a / b)]
14337 [\sin@{a@}, \sin@{2 a@}, \sin(2 + a),
14338  \sin\left( @{a \over b@} \right)]
14339 @end example
14340 @tex
14341 \turnoffactive\let\rm\goodrm
14342 $$ [\sin{a}, \sin{2 a}, \sin(2 + a), \sin\left( {a \over b} \right)] $$
14343 @end tex
14344 @sp 2
14345 @end group
14347 @group
14348 First with plain @kbd{d T}, then with @kbd{C-u d T}, then finally with
14349 @kbd{C-u - d T} (using the example definition
14350 @samp{\def\foo#1@{\tilde F(#1)@}}:
14352 @example
14354 [f(a), foo(bar), sin(pi)]
14355 [f(a), foo(bar), \sin{\pi}]
14356 [f(a), \hbox@{foo@}(\hbox@{bar@}), \sin@{\pi@}]
14357 [f(a), \foo@{\hbox@{bar@}@}, \sin@{\pi@}]
14358 @end example
14359 @tex
14360 \let\rm\goodrm
14361 $$ [f(a), foo(bar), \sin{\pi}] $$
14362 $$ [f(a), \hbox{foo}(\hbox{bar}), \sin{\pi}] $$
14363 $$ [f(a), \tilde F(\hbox{bar}), \sin{\pi}] $$
14364 @end tex
14365 @sp 2
14366 @end group
14368 @group
14369 First with @samp{\def\evalto@{@}}, then with @samp{\def\evalto#1\to@{@}}:
14371 @example
14373 2 + 3 => 5
14374 \evalto 2 + 3 \to 5
14375 @end example
14376 @tex
14377 \turnoffactive
14378 $$ 2 + 3 \to 5 $$
14379 $$ 5 $$
14380 @end tex
14381 @sp 2
14382 @end group
14384 @group
14385 First with standard @code{\to}, then with @samp{\let\to\Rightarrow}:
14387 @example
14389 [2 + 3 => 5, a / 2 => (b + c) / 2]
14390 [@{2 + 3 \to 5@}, @{@{a \over 2@} \to @{b + c \over 2@}@}]
14391 @end example
14392 @tex
14393 \turnoffactive
14394 $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$
14395 {\let\to\Rightarrow
14396 $$ [{2 + 3 \to 5}, {{a \over 2} \to {b + c \over 2}}] $$}
14397 @end tex
14398 @sp 2
14399 @end group
14401 @group
14402 Matrices normally, then changing @code{\matrix} to @code{\pmatrix}:
14404 @example
14406 [ [ a / b, 0 ], [ 0, 2^(x + 1) ] ]
14407 \matrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14408 \pmatrix@{ @{a \over b@} & 0 \\ 0 & 2^@{(x + 1)@} @}
14409 @end example
14410 @tex
14411 \turnoffactive
14412 $$ \matrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14413 $$ \pmatrix{ {a \over b} & 0 \cr 0 & 2^{(x + 1)} } $$
14414 @end tex
14415 @sp 2
14416 @end group
14417 @end iftex
14419 @node Eqn Language Mode, Mathematica Language Mode, TeX Language Mode, Language Modes
14420 @subsection Eqn Language Mode
14422 @noindent
14423 @kindex d E
14424 @pindex calc-eqn-language
14425 @dfn{Eqn} is another popular formatter for math formulas.  It is
14426 designed for use with the TROFF text formatter, and comes standard
14427 with many versions of Unix.  The @kbd{d E} (@code{calc-eqn-language})
14428 command selects @dfn{eqn} notation.
14430 The @dfn{eqn} language's main idiosyncrasy is that whitespace plays
14431 a significant part in the parsing of the language.  For example,
14432 @samp{sqrt x+1 + y} treats @samp{x+1} as the argument of the
14433 @code{sqrt} operator.  @dfn{Eqn} also understands more conventional
14434 grouping using curly braces:  @samp{sqrt@{x+1@} + y}.  Braces are
14435 required only when the argument contains spaces.
14437 In Calc's @dfn{eqn} mode, however, curly braces are required to
14438 delimit arguments of operators like @code{sqrt}.  The first of the
14439 above examples would treat only the @samp{x} as the argument of
14440 @code{sqrt}, and in fact @samp{sin x+1} would be interpreted as
14441 @samp{sin * x + 1}, because @code{sin} is not a special operator
14442 in the @dfn{eqn} language.  If you always surround the argument
14443 with curly braces, Calc will never misunderstand.
14445 Calc also understands parentheses as grouping characters.  Another
14446 peculiarity of @dfn{eqn}'s syntax makes it advisable to separate
14447 words with spaces from any surrounding characters that aren't curly
14448 braces, so Calc writes @samp{sin ( x + y )} in @dfn{eqn} mode.
14449 (The spaces around @code{sin} are important to make @dfn{eqn}
14450 recognize that @code{sin} should be typeset in a roman font, and
14451 the spaces around @code{x} and @code{y} are a good idea just in
14452 case the @dfn{eqn} document has defined special meanings for these
14453 names, too.)
14455 Powers and subscripts are written with the @code{sub} and @code{sup}
14456 operators, respectively.  Note that the caret symbol @samp{^} is
14457 treated the same as a space in @dfn{eqn} mode, as is the @samp{~}
14458 symbol (these are used to introduce spaces of various widths into
14459 the typeset output of @dfn{eqn}).
14461 As in @TeX{} mode, Calc's formatter omits parentheses around the
14462 arguments of functions like @code{ln} and @code{sin} if they are
14463 ``simple-looking''; in this case Calc surrounds the argument with
14464 braces, separated by a @samp{~} from the function name: @samp{sin~@{x@}}.
14466 Font change codes (like @samp{roman @var{x}}) and positioning codes
14467 (like @samp{~} and @samp{down @var{n} @var{x}}) are ignored by the
14468 @dfn{eqn} reader.  Also ignored are the words @code{left}, @code{right},
14469 @code{mark}, and @code{lineup}.  Quotation marks in @dfn{eqn} mode input
14470 are treated the same as curly braces: @samp{sqrt "1+x"} is equivalent to
14471 @samp{sqrt @{1+x@}}; this is only an approximation to the true meaning
14472 of quotes in @dfn{eqn}, but it is good enough for most uses.
14474 Accent codes (@samp{@var{x} dot}) are handled by treating them as
14475 function calls (@samp{dot(@var{x})}) internally.  @xref{TeX Language
14476 Mode}, for a table of these accent functions.  The @code{prime} accent
14477 is treated specially if it occurs on a variable or function name:
14478 @samp{f prime prime @w{( x prime )}} is stored internally as
14479 @samp{f'@w{'}(x')}.  For example, taking the derivative of @samp{f(2 x)}
14480 with @kbd{a d x} will produce @samp{2 f'(2 x)}, which @dfn{eqn} mode
14481 will display as @samp{2 f prime ( 2 x )}.
14483 Assignments are written with the @samp{<-} (left-arrow) symbol,
14484 and @code{evalto} operators are written with @samp{->} or
14485 @samp{evalto ... ->} (@pxref{TeX Language Mode}, for a discussion
14486 of this).  The regular Calc symbols @samp{:=} and @samp{=>} are also
14487 recognized for these operators during reading.
14489 Vectors in @dfn{eqn} mode use regular Calc square brackets, but
14490 matrices are formatted as @samp{matrix @{ ccol @{ a above b @} ... @}}.
14491 The words @code{lcol} and @code{rcol} are recognized as synonyms
14492 for @code{ccol} during input, and are generated instead of @code{ccol}
14493 if the matrix justification mode so specifies.
14495 @node Mathematica Language Mode, Maple Language Mode, Eqn Language Mode, Language Modes
14496 @subsection Mathematica Language Mode
14498 @noindent
14499 @kindex d M
14500 @pindex calc-mathematica-language
14501 @cindex Mathematica language
14502 The @kbd{d M} (@code{calc-mathematica-language}) command selects the
14503 conventions of Mathematica, a powerful and popular mathematical tool
14504 from Wolfram Research, Inc.  Notable differences in Mathematica mode
14505 are that the names of built-in functions are capitalized, and function
14506 calls use square brackets instead of parentheses.  Thus the Calc
14507 formula @samp{sin(2 x)} is entered and displayed @w{@samp{Sin[2 x]}} in
14508 Mathematica mode.
14510 Vectors and matrices use curly braces in Mathematica.  Complex numbers
14511 are written @samp{3 + 4 I}.  The standard special constants in Calc are
14512 written @code{Pi}, @code{E}, @code{I}, @code{GoldenRatio}, @code{EulerGamma},
14513 @code{Infinity}, @code{ComplexInfinity}, and @code{Indeterminate} in
14514 Mathematica mode.
14515 Non-decimal numbers are written, e.g., @samp{16^^7fff}.  Floating-point
14516 numbers in scientific notation are written @samp{1.23*10.^3}.
14517 Subscripts use double square brackets: @samp{a[[i]]}.@refill
14519 @node Maple Language Mode, Compositions, Mathematica Language Mode, Language Modes
14520 @subsection Maple Language Mode
14522 @noindent
14523 @kindex d W
14524 @pindex calc-maple-language
14525 @cindex Maple language
14526 The @kbd{d W} (@code{calc-maple-language}) command selects the
14527 conventions of Maple, another mathematical tool from the University
14528 of Waterloo.  
14530 Maple's language is much like C.  Underscores are allowed in symbol
14531 names; square brackets are used for subscripts; explicit @samp{*}s for
14532 multiplications are required.  Use either @samp{^} or @samp{**} to
14533 denote powers.
14535 Maple uses square brackets for lists and curly braces for sets.  Calc
14536 interprets both notations as vectors, and displays vectors with square
14537 brackets.  This means Maple sets will be converted to lists when they
14538 pass through Calc.  As a special case, matrices are written as calls
14539 to the function @code{matrix}, given a list of lists as the argument,
14540 and can be read in this form or with all-capitals @code{MATRIX}.
14542 The Maple interval notation @samp{2 .. 3} has no surrounding brackets;
14543 Calc reads @samp{2 .. 3} as the closed interval @samp{[2 .. 3]}, and
14544 writes any kind of interval as @samp{2 .. 3}.  This means you cannot
14545 see the difference between an open and a closed interval while in
14546 Maple display mode.
14548 Maple writes complex numbers as @samp{3 + 4*I}.  Its special constants
14549 are @code{Pi}, @code{E}, @code{I}, and @code{infinity} (all three of
14550 @code{inf}, @code{uinf}, and @code{nan} display as @code{infinity}).
14551 Floating-point numbers are written @samp{1.23*10.^3}.
14553 Among things not currently handled by Calc's Maple mode are the
14554 various quote symbols, procedures and functional operators, and
14555 inert (@samp{&}) operators.
14557 @node Compositions, Syntax Tables, Maple Language Mode, Language Modes
14558 @subsection Compositions
14560 @noindent
14561 @cindex Compositions
14562 There are several @dfn{composition functions} which allow you to get
14563 displays in a variety of formats similar to those in Big language
14564 mode.  Most of these functions do not evaluate to anything; they are
14565 placeholders which are left in symbolic form by Calc's evaluator but
14566 are recognized by Calc's display formatting routines.
14568 Two of these, @code{string} and @code{bstring}, are described elsewhere.
14569 @xref{Strings}.  For example, @samp{string("ABC")} is displayed as
14570 @samp{ABC}.  When viewed on the stack it will be indistinguishable from
14571 the variable @code{ABC}, but internally it will be stored as
14572 @samp{string([65, 66, 67])} and can still be manipulated this way; for
14573 example, the selection and vector commands @kbd{j 1 v v j u} would
14574 select the vector portion of this object and reverse the elements, then
14575 deselect to reveal a string whose characters had been reversed.
14577 The composition functions do the same thing in all language modes
14578 (although their components will of course be formatted in the current
14579 language mode).  The one exception is Unformatted mode (@kbd{d U}),
14580 which does not give the composition functions any special treatment.
14581 The functions are discussed here because of their relationship to
14582 the language modes.
14584 @menu
14585 * Composition Basics::
14586 * Horizontal Compositions::
14587 * Vertical Compositions::
14588 * Other Compositions::
14589 * Information about Compositions::
14590 * User-Defined Compositions::
14591 @end menu
14593 @node Composition Basics, Horizontal Compositions, Compositions, Compositions
14594 @subsubsection Composition Basics
14596 @noindent
14597 Compositions are generally formed by stacking formulas together
14598 horizontally or vertically in various ways.  Those formulas are
14599 themselves compositions.  @TeX{} users will find this analogous
14600 to @TeX{}'s ``boxes.''  Each multi-line composition has a
14601 @dfn{baseline}; horizontal compositions use the baselines to
14602 decide how formulas should be positioned relative to one another.
14603 For example, in the Big mode formula
14605 @group
14606 @example
14607           2
14608      a + b
14609 17 + ------
14610        c
14611 @end example
14612 @end group
14614 @noindent
14615 the second term of the sum is four lines tall and has line three as
14616 its baseline.  Thus when the term is combined with 17, line three
14617 is placed on the same level as the baseline of 17.
14619 @tex
14620 \bigskip
14621 @end tex
14623 Another important composition concept is @dfn{precedence}.  This is
14624 an integer that represents the binding strength of various operators.
14625 For example, @samp{*} has higher precedence (195) than @samp{+} (180),
14626 which means that @samp{(a * b) + c} will be formatted without the
14627 parentheses, but @samp{a * (b + c)} will keep the parentheses.
14629 The operator table used by normal and Big language modes has the
14630 following precedences:
14632 @example
14633 _     1200   @r{(subscripts)}
14634 %     1100   @r{(as in n}%@r{)}
14635 -     1000   @r{(as in }-@r{n)}
14636 !     1000   @r{(as in }!@r{n)}
14637 mod    400
14638 +/-    300
14639 !!     210    @r{(as in n}!!@r{)}
14640 !      210    @r{(as in n}!@r{)}
14641 ^      200
14642 *      195    @r{(or implicit multiplication)}
14643 / % \  190
14644 + -    180    @r{(as in a}+@r{b)}
14645 |      170
14646 < =    160    @r{(and other relations)}
14647 &&     110
14648 ||     100
14649 ? :     90
14650 !!!     85
14651 &&&     80
14652 |||     75
14653 :=      50
14654 ::      45
14655 =>      40
14656 @end example
14658 The general rule is that if an operator with precedence @cite{n}
14659 occurs as an argument to an operator with precedence @cite{m}, then
14660 the argument is enclosed in parentheses if @cite{n < m}.  Top-level
14661 expressions and expressions which are function arguments, vector
14662 components, etc., are formatted with precedence zero (so that they
14663 normally never get additional parentheses).
14665 For binary left-associative operators like @samp{+}, the righthand
14666 argument is actually formatted with one-higher precedence than shown
14667 in the table.  This makes sure @samp{(a + b) + c} omits the parentheses,
14668 but the unnatural form @samp{a + (b + c)} keeps its parentheses.
14669 Right-associative operators like @samp{^} format the lefthand argument
14670 with one-higher precedence.
14672 @c @starindex
14673 @tindex cprec
14674 The @code{cprec} function formats an expression with an arbitrary
14675 precedence.  For example, @samp{cprec(abc, 185)} will combine into
14676 sums and products as follows:  @samp{7 + abc}, @samp{7 (abc)} (because
14677 this @code{cprec} form has higher precedence than addition, but lower
14678 precedence than multiplication).
14680 @tex
14681 \bigskip
14682 @end tex
14684 A final composition issue is @dfn{line breaking}.  Calc uses two
14685 different strategies for ``flat'' and ``non-flat'' compositions.
14686 A non-flat composition is anything that appears on multiple lines
14687 (not counting line breaking).  Examples would be matrices and Big
14688 mode powers and quotients.  Non-flat compositions are displayed
14689 exactly as specified.  If they come out wider than the current
14690 window, you must use horizontal scrolling (@kbd{<} and @kbd{>}) to
14691 view them.
14693 Flat compositions, on the other hand, will be broken across several
14694 lines if they are too wide to fit the window.  Certain points in a
14695 composition are noted internally as @dfn{break points}.  Calc's
14696 general strategy is to fill each line as much as possible, then to
14697 move down to the next line starting at the first break point that
14698 didn't fit.  However, the line breaker understands the hierarchical
14699 structure of formulas.  It will not break an ``inner'' formula if
14700 it can use an earlier break point from an ``outer'' formula instead.
14701 For example, a vector of sums might be formatted as:
14703 @group
14704 @example
14705 [ a + b + c, d + e + f,
14706   g + h + i, j + k + l, m ]
14707 @end example
14708 @end group
14710 @noindent
14711 If the @samp{m} can fit, then so, it seems, could the @samp{g}.
14712 But Calc prefers to break at the comma since the comma is part
14713 of a ``more outer'' formula.  Calc would break at a plus sign
14714 only if it had to, say, if the very first sum in the vector had
14715 itself been too large to fit.
14717 Of the composition functions described below, only @code{choriz}
14718 generates break points.  The @code{bstring} function (@pxref{Strings})
14719 also generates breakable items:  A break point is added after every
14720 space (or group of spaces) except for spaces at the very beginning or
14721 end of the string.
14723 Composition functions themselves count as levels in the formula
14724 hierarchy, so a @code{choriz} that is a component of a larger
14725 @code{choriz} will be less likely to be broken.  As a special case,
14726 if a @code{bstring} occurs as a component of a @code{choriz} or
14727 @code{choriz}-like object (such as a vector or a list of arguments
14728 in a function call), then the break points in that @code{bstring}
14729 will be on the same level as the break points of the surrounding
14730 object.
14732 @node Horizontal Compositions, Vertical Compositions, Composition Basics, Compositions
14733 @subsubsection Horizontal Compositions
14735 @noindent
14736 @c @starindex
14737 @tindex choriz
14738 The @code{choriz} function takes a vector of objects and composes
14739 them horizontally.  For example, @samp{choriz([17, a b/c, d])} formats
14740 as @w{@samp{17a b / cd}} in normal language mode, or as
14742 @group
14743 @example
14744   a b
14745 17---d
14746    c
14747 @end example
14748 @end group
14750 @noindent
14751 in Big language mode.  This is actually one case of the general
14752 function @samp{choriz(@var{vec}, @var{sep}, @var{prec})}, where
14753 either or both of @var{sep} and @var{prec} may be omitted.
14754 @var{Prec} gives the @dfn{precedence} to use when formatting
14755 each of the components of @var{vec}.  The default precedence is
14756 the precedence from the surrounding environment.
14758 @var{Sep} is a string (i.e., a vector of character codes as might
14759 be entered with @code{" "} notation) which should separate components
14760 of the composition.  Also, if @var{sep} is given, the line breaker
14761 will allow lines to be broken after each occurrence of @var{sep}.
14762 If @var{sep} is omitted, the composition will not be breakable
14763 (unless any of its component compositions are breakable).
14765 For example, @samp{2 choriz([a, b c, d = e], " + ", 180)} is
14766 formatted as @samp{2 a + b c + (d = e)}.  To get the @code{choriz}
14767 to have precedence 180 ``outwards'' as well as ``inwards,''
14768 enclose it in a @code{cprec} form:  @samp{2 cprec(choriz(...), 180)}
14769 formats as @samp{2 (a + b c + (d = e))}.
14771 The baseline of a horizontal composition is the same as the
14772 baselines of the component compositions, which are all aligned.
14774 @node Vertical Compositions, Other Compositions, Horizontal Compositions, Compositions
14775 @subsubsection Vertical Compositions
14777 @noindent
14778 @c @starindex
14779 @tindex cvert
14780 The @code{cvert} function makes a vertical composition.  Each
14781 component of the vector is centered in a column.  The baseline of
14782 the result is by default the top line of the resulting composition.
14783 For example, @samp{f(cvert([a, bb, ccc]), cvert([a^2 + 1, b^2]))}
14784 formats in Big mode as
14786 @group
14787 @example
14788 f( a ,  2    )
14789   bb   a  + 1
14790   ccc     2
14791          b
14792 @end example
14793 @end group
14795 @c @starindex
14796 @tindex cbase
14797 There are several special composition functions that work only as
14798 components of a vertical composition.  The @code{cbase} function
14799 controls the baseline of the vertical composition; the baseline
14800 will be the same as the baseline of whatever component is enclosed
14801 in @code{cbase}.  Thus @samp{f(cvert([a, cbase(bb), ccc]),
14802 cvert([a^2 + 1, cbase(b^2)]))} displays as
14804 @group
14805 @example
14806         2
14807        a  + 1
14808    a      2
14809 f(bb ,   b   )
14810   ccc
14811 @end example
14812 @end group
14814 @c @starindex
14815 @tindex ctbase
14816 @c @starindex
14817 @tindex cbbase
14818 There are also @code{ctbase} and @code{cbbase} functions which
14819 make the baseline of the vertical composition equal to the top
14820 or bottom line (rather than the baseline) of that component.
14821 Thus @samp{cvert([cbase(a / b)]) + cvert([ctbase(a / b)]) +
14822 cvert([cbbase(a / b)])} gives
14824 @group
14825 @example
14826         a
14827 a       -
14828 - + a + b
14829 b   -
14830     b
14831 @end example
14832 @end group
14834 There should be only one @code{cbase}, @code{ctbase}, or @code{cbbase}
14835 function in a given vertical composition.  These functions can also
14836 be written with no arguments:  @samp{ctbase()} is a zero-height object
14837 which means the baseline is the top line of the following item, and
14838 @samp{cbbase()} means the baseline is the bottom line of the preceding
14839 item.
14841 @c @starindex
14842 @tindex crule
14843 The @code{crule} function builds a ``rule,'' or horizontal line,
14844 across a vertical composition.  By itself @samp{crule()} uses @samp{-}
14845 characters to build the rule.  You can specify any other character,
14846 e.g., @samp{crule("=")}.  The argument must be a character code or
14847 vector of exactly one character code.  It is repeated to match the
14848 width of the widest item in the stack.  For example, a quotient
14849 with a thick line is @samp{cvert([a + 1, cbase(crule("=")), b^2])}:
14851 @group
14852 @example
14853 a + 1
14854 =====
14855   2
14857 @end example
14858 @end group
14860 @c @starindex
14861 @tindex clvert
14862 @c @starindex
14863 @tindex crvert
14864 Finally, the functions @code{clvert} and @code{crvert} act exactly
14865 like @code{cvert} except that the items are left- or right-justified
14866 in the stack.  Thus @samp{clvert([a, bb, ccc]) + crvert([a, bb, ccc])}
14867 gives:
14869 @group
14870 @example
14871 a   +   a
14872 bb     bb
14873 ccc   ccc
14874 @end example
14875 @end group
14877 Like @code{choriz}, the vertical compositions accept a second argument
14878 which gives the precedence to use when formatting the components.
14879 Vertical compositions do not support separator strings.
14881 @node Other Compositions, Information about Compositions, Vertical Compositions, Compositions
14882 @subsubsection Other Compositions
14884 @noindent
14885 @c @starindex
14886 @tindex csup
14887 The @code{csup} function builds a superscripted expression.  For
14888 example, @samp{csup(a, b)} looks the same as @samp{a^b} does in Big
14889 language mode.  This is essentially a horizontal composition of
14890 @samp{a} and @samp{b}, where @samp{b} is shifted up so that its
14891 bottom line is one above the baseline.
14893 @c @starindex
14894 @tindex csub
14895 Likewise, the @code{csub} function builds a subscripted expression.
14896 This shifts @samp{b} down so that its top line is one below the
14897 bottom line of @samp{a} (note that this is not quite analogous to
14898 @code{csup}).  Other arrangements can be obtained by using
14899 @code{choriz} and @code{cvert} directly.
14901 @c @starindex
14902 @tindex cflat
14903 The @code{cflat} function formats its argument in ``flat'' mode,
14904 as obtained by @samp{d O}, if the current language mode is normal
14905 or Big.  It has no effect in other language modes.  For example,
14906 @samp{a^(b/c)} is formatted by Big mode like @samp{csup(a, cflat(b/c))}
14907 to improve its readability.
14909 @c @starindex
14910 @tindex cspace
14911 The @code{cspace} function creates horizontal space.  For example,
14912 @samp{cspace(4)} is effectively the same as @samp{string("    ")}.
14913 A second string (i.e., vector of characters) argument is repeated
14914 instead of the space character.  For example, @samp{cspace(4, "ab")}
14915 looks like @samp{abababab}.  If the second argument is not a string,
14916 it is formatted in the normal way and then several copies of that
14917 are composed together:  @samp{cspace(4, a^2)} yields
14919 @group
14920 @example
14921  2 2 2 2
14922 a a a a
14923 @end example
14924 @end group
14926 @noindent
14927 If the number argument is zero, this is a zero-width object.
14929 @c @starindex
14930 @tindex cvspace
14931 The @code{cvspace} function creates vertical space, or a vertical
14932 stack of copies of a certain string or formatted object.  The
14933 baseline is the center line of the resulting stack.  A numerical
14934 argument of zero will produce an object which contributes zero
14935 height if used in a vertical composition.
14937 @c @starindex
14938 @tindex ctspace
14939 @c @starindex
14940 @tindex cbspace
14941 There are also @code{ctspace} and @code{cbspace} functions which
14942 create vertical space with the baseline the same as the baseline
14943 of the top or bottom copy, respectively, of the second argument.
14944 Thus @samp{cvspace(2, a/b) + ctspace(2, a/b) + cbspace(2, a/b)}
14945 displays as:
14947 @group
14948 @example
14949         a
14950         -
14951 a       b
14952 -   a   a
14953 b + - + -
14954 a   b   b
14955 -   a
14956 b   -
14957     b
14958 @end example
14959 @end group
14961 @node Information about Compositions, User-Defined Compositions, Other Compositions, Compositions
14962 @subsubsection Information about Compositions
14964 @noindent
14965 The functions in this section are actual functions; they compose their
14966 arguments according to the current language and other display modes,
14967 then return a certain measurement of the composition as an integer.
14969 @c @starindex
14970 @tindex cwidth
14971 The @code{cwidth} function measures the width, in characters, of a
14972 composition.  For example, @samp{cwidth(a + b)} is 5, and
14973 @samp{cwidth(a / b)} is 5 in normal mode, 1 in Big mode, and 11 in
14974 @TeX{} mode (for @samp{@{a \over b@}}).  The argument may involve
14975 the composition functions described in this section.
14977 @c @starindex
14978 @tindex cheight
14979 The @code{cheight} function measures the height of a composition.
14980 This is the total number of lines in the argument's printed form.
14982 @c @starindex
14983 @tindex cascent
14984 @c @starindex
14985 @tindex cdescent
14986 The functions @code{cascent} and @code{cdescent} measure the amount
14987 of the height that is above (and including) the baseline, or below
14988 the baseline, respectively.  Thus @samp{cascent(@var{x}) + cdescent(@var{x})}
14989 always equals @samp{cheight(@var{x})}.  For a one-line formula like
14990 @samp{a + b}, @code{cascent} returns 1 and @code{cdescent} returns 0.
14991 For @samp{a / b} in Big mode, @code{cascent} returns 2 and @code{cdescent}
14992 returns 1.  The only formula for which @code{cascent} will return zero
14993 is @samp{cvspace(0)} or equivalents.
14995 @node User-Defined Compositions, , Information about Compositions, Compositions
14996 @subsubsection User-Defined Compositions
14998 @noindent
14999 @kindex Z C
15000 @pindex calc-user-define-composition
15001 The @kbd{Z C} (@code{calc-user-define-composition}) command lets you
15002 define the display format for any algebraic function.  You provide a
15003 formula containing a certain number of argument variables on the stack.
15004 Any time Calc formats a call to the specified function in the current
15005 language mode and with that number of arguments, Calc effectively
15006 replaces the function call with that formula with the arguments
15007 replaced.
15009 Calc builds the default argument list by sorting all the variable names
15010 that appear in the formula into alphabetical order.  You can edit this
15011 argument list before pressing @key{RET} if you wish.  Any variables in
15012 the formula that do not appear in the argument list will be displayed
15013 literally; any arguments that do not appear in the formula will not
15014 affect the display at all.
15016 You can define formats for built-in functions, for functions you have
15017 defined with @kbd{Z F} (@pxref{Algebraic Definitions}), or for functions
15018 which have no definitions but are being used as purely syntactic objects.
15019 You can define different formats for each language mode, and for each
15020 number of arguments, using a succession of @kbd{Z C} commands.  When
15021 Calc formats a function call, it first searches for a format defined
15022 for the current language mode (and number of arguments); if there is
15023 none, it uses the format defined for the Normal language mode.  If
15024 neither format exists, Calc uses its built-in standard format for that
15025 function (usually just @samp{@var{func}(@var{args})}).
15027 If you execute @kbd{Z C} with the number 0 on the stack instead of a
15028 formula, any defined formats for the function in the current language
15029 mode will be removed.  The function will revert to its standard format.
15031 For example, the default format for the binomial coefficient function
15032 @samp{choose(n, m)} in the Big language mode is
15034 @group
15035 @example
15037 ( )
15039 @end example
15040 @end group
15042 @noindent
15043 You might prefer the notation,
15045 @group
15046 @example
15048 n m
15049 @end example
15050 @end group
15052 @noindent
15053 To define this notation, first make sure you are in Big mode,
15054 then put the formula
15056 @smallexample
15057 choriz([cvert([cvspace(1), n]), C, cvert([cvspace(1), m])])
15058 @end smallexample
15060 @noindent
15061 on the stack and type @kbd{Z C}.  Answer the first prompt with
15062 @code{choose}.  The second prompt will be the default argument list
15063 of @samp{(C m n)}.  Edit this list to be @samp{(n m)} and press
15064 @key{RET}.  Now, try it out:  For example, turn simplification
15065 off with @kbd{m O} and enter @samp{choose(a,b) + choose(7,3)}
15066 as an algebraic entry.
15068 @group
15069 @example
15070  C  +  C 
15071 a b   7 3
15072 @end example
15073 @end group
15075 As another example, let's define the usual notation for Stirling
15076 numbers of the first kind, @samp{stir1(n, m)}.  This is just like
15077 the regular format for binomial coefficients but with square brackets
15078 instead of parentheses.
15080 @smallexample
15081 choriz([string("["), cvert([n, cbase(cvspace(1)), m]), string("]")])
15082 @end smallexample
15084 Now type @kbd{Z C stir1 @key{RET}}, edit the argument list to
15085 @samp{(n m)}, and type @key{RET}.
15087 The formula provided to @kbd{Z C} usually will involve composition
15088 functions, but it doesn't have to.  Putting the formula @samp{a + b + c}
15089 onto the stack and typing @kbd{Z C foo @key{RET} @key{RET}} would define
15090 the function @samp{foo(x,y,z)} to display like @samp{x + y + z}.
15091 This ``sum'' will act exactly like a real sum for all formatting
15092 purposes (it will be parenthesized the same, and so on).  However
15093 it will be computationally unrelated to a sum.  For example, the
15094 formula @samp{2 * foo(1, 2, 3)} will display as @samp{2 (1 + 2 + 3)}.
15095 Operator precedences have caused the ``sum'' to be written in
15096 parentheses, but the arguments have not actually been summed.
15097 (Generally a display format like this would be undesirable, since
15098 it can easily be confused with a real sum.)
15100 The special function @code{eval} can be used inside a @kbd{Z C}
15101 composition formula to cause all or part of the formula to be
15102 evaluated at display time.  For example, if the formula is
15103 @samp{a + eval(b + c)}, then @samp{foo(1, 2, 3)} will be displayed
15104 as @samp{1 + 5}.  Evaluation will use the default simplifications,
15105 regardless of the current simplification mode.  There are also
15106 @code{evalsimp} and @code{evalextsimp} which simplify as if by
15107 @kbd{a s} and @kbd{a e} (respectively).  Note that these ``functions''
15108 operate only in the context of composition formulas (and also in
15109 rewrite rules, where they serve a similar purpose; @pxref{Rewrite
15110 Rules}).  On the stack, a call to @code{eval} will be left in
15111 symbolic form.
15113 It is not a good idea to use @code{eval} except as a last resort.
15114 It can cause the display of formulas to be extremely slow.  For
15115 example, while @samp{eval(a + b)} might seem quite fast and simple,
15116 there are several situations where it could be slow.  For example,
15117 @samp{a} and/or @samp{b} could be polar complex numbers, in which
15118 case doing the sum requires trigonometry.  Or, @samp{a} could be
15119 the factorial @samp{fact(100)} which is unevaluated because you
15120 have typed @kbd{m O}; @code{eval} will evaluate it anyway to
15121 produce a large, unwieldy integer.
15123 You can save your display formats permanently using the @kbd{Z P}
15124 command (@pxref{Creating User Keys}).
15126 @node Syntax Tables, , Compositions, Language Modes
15127 @subsection Syntax Tables
15129 @noindent
15130 @cindex Syntax tables
15131 @cindex Parsing formulas, customized
15132 Syntax tables do for input what compositions do for output:  They
15133 allow you to teach custom notations to Calc's formula parser.
15134 Calc keeps a separate syntax table for each language mode.
15136 (Note that the Calc ``syntax tables'' discussed here are completely
15137 unrelated to the syntax tables described in the Emacs manual.)
15139 @kindex Z S
15140 @pindex calc-edit-user-syntax
15141 The @kbd{Z S} (@code{calc-edit-user-syntax}) command edits the
15142 syntax table for the current language mode.  If you want your
15143 syntax to work in any language, define it in the normal language
15144 mode.  Type @kbd{M-# M-#} to finish editing the syntax table, or
15145 @kbd{M-# x} to cancel the edit.  The @kbd{m m} command saves all
15146 the syntax tables along with the other mode settings;
15147 @pxref{General Mode Commands}.
15149 @menu
15150 * Syntax Table Basics::
15151 * Precedence in Syntax Tables::
15152 * Advanced Syntax Patterns::
15153 * Conditional Syntax Rules::
15154 @end menu
15156 @node Syntax Table Basics, Precedence in Syntax Tables, Syntax Tables, Syntax Tables
15157 @subsubsection Syntax Table Basics
15159 @noindent
15160 @dfn{Parsing} is the process of converting a raw string of characters,
15161 such as you would type in during algebraic entry, into a Calc formula.
15162 Calc's parser works in two stages.  First, the input is broken down
15163 into @dfn{tokens}, such as words, numbers, and punctuation symbols
15164 like @samp{+}, @samp{:=}, and @samp{+/-}.  Space between tokens is
15165 ignored (except when it serves to separate adjacent words).  Next,
15166 the parser matches this string of tokens against various built-in
15167 syntactic patterns, such as ``an expression followed by @samp{+}
15168 followed by another expression'' or ``a name followed by @samp{(},
15169 zero or more expressions separated by commas, and @samp{)}.''
15171 A @dfn{syntax table} is a list of user-defined @dfn{syntax rules},
15172 which allow you to specify new patterns to define your own
15173 favorite input notations.  Calc's parser always checks the syntax
15174 table for the current language mode, then the table for the normal
15175 language mode, before it uses its built-in rules to parse an
15176 algebraic formula you have entered.  Each syntax rule should go on
15177 its own line; it consists of a @dfn{pattern}, a @samp{:=} symbol,
15178 and a Calc formula with an optional @dfn{condition}.  (Syntax rules
15179 resemble algebraic rewrite rules, but the notation for patterns is
15180 completely different.)
15182 A syntax pattern is a list of tokens, separated by spaces.
15183 Except for a few special symbols, tokens in syntax patterns are
15184 matched literally, from left to right.  For example, the rule,
15186 @example
15187 foo ( ) := 2+3
15188 @end example
15190 @noindent
15191 would cause Calc to parse the formula @samp{4+foo()*5} as if it
15192 were @samp{4+(2+3)*5}.  Notice that the parentheses were written
15193 as two separate tokens in the rule.  As a result, the rule works
15194 for both @samp{foo()} and @w{@samp{foo (  )}}.  If we had written
15195 the rule as @samp{foo () := 2+3}, then Calc would treat @samp{()}
15196 as a single, indivisible token, so that @w{@samp{foo( )}} would
15197 not be recognized by the rule.  (It would be parsed as a regular
15198 zero-argument function call instead.)  In fact, this rule would
15199 also make trouble for the rest of Calc's parser:  An unrelated
15200 formula like @samp{bar()} would now be tokenized into @samp{bar ()}
15201 instead of @samp{bar ( )}, so that the standard parser for function
15202 calls would no longer recognize it!
15204 While it is possible to make a token with a mixture of letters
15205 and punctuation symbols, this is not recommended.  It is better to
15206 break it into several tokens, as we did with @samp{foo()} above.
15208 The symbol @samp{#} in a syntax pattern matches any Calc expression.
15209 On the righthand side, the things that matched the @samp{#}s can
15210 be referred to as @samp{#1}, @samp{#2}, and so on (where @samp{#1}
15211 matches the leftmost @samp{#} in the pattern).  For example, these
15212 rules match a user-defined function, prefix operator, infix operator,
15213 and postfix operator, respectively:
15215 @example
15216 foo ( # ) := myfunc(#1)
15217 foo # := myprefix(#1)
15218 # foo # := myinfix(#1,#2)
15219 # foo := mypostfix(#1)
15220 @end example
15222 Thus @samp{foo(3)} will parse as @samp{myfunc(3)}, and @samp{2+3 foo}
15223 will parse as @samp{mypostfix(2+3)}.
15225 It is important to write the first two rules in the order shown,
15226 because Calc tries rules in order from first to last.  If the
15227 pattern @samp{foo #} came first, it would match anything that could
15228 match the @samp{foo ( # )} rule, since an expression in parentheses
15229 is itself a valid expression.  Thus the @w{@samp{foo ( # )}} rule would
15230 never get to match anything.  Likewise, the last two rules must be
15231 written in the order shown or else @samp{3 foo 4} will be parsed as
15232 @samp{mypostfix(3) * 4}.  (Of course, the best way to avoid these
15233 ambiguities is not to use the same symbol in more than one way at
15234 the same time!  In case you're not convinced, try the following
15235 exercise:  How will the above rules parse the input @samp{foo(3,4)},
15236 if at all?  Work it out for yourself, then try it in Calc and see.)
15238 Calc is quite flexible about what sorts of patterns are allowed.
15239 The only rule is that every pattern must begin with a literal
15240 token (like @samp{foo} in the first two patterns above), or with
15241 a @samp{#} followed by a literal token (as in the last two
15242 patterns).  After that, any mixture is allowed, although putting
15243 two @samp{#}s in a row will not be very useful since two
15244 expressions with nothing between them will be parsed as one
15245 expression that uses implicit multiplication.
15247 As a more practical example, Maple uses the notation
15248 @samp{sum(a(i), i=1..10)} for sums, which Calc's Maple mode doesn't
15249 recognize at present.  To handle this syntax, we simply add the
15250 rule,
15252 @example
15253 sum ( # , # = # .. # ) := sum(#1,#2,#3,#4)
15254 @end example
15256 @noindent
15257 to the Maple mode syntax table.  As another example, C mode can't
15258 read assignment operators like @samp{++} and @samp{*=}.  We can
15259 define these operators quite easily:
15261 @example
15262 # *= # := muleq(#1,#2)
15263 # ++ := postinc(#1)
15264 ++ # := preinc(#1)
15265 @end example
15267 @noindent
15268 To complete the job, we would use corresponding composition functions
15269 and @kbd{Z C} to cause these functions to display in their respective
15270 Maple and C notations.  (Note that the C example ignores issues of
15271 operator precedence, which are discussed in the next section.)
15273 You can enclose any token in quotes to prevent its usual
15274 interpretation in syntax patterns:
15276 @example
15277 # ":=" # := becomes(#1,#2)
15278 @end example
15280 Quotes also allow you to include spaces in a token, although once
15281 again it is generally better to use two tokens than one token with
15282 an embedded space.  To include an actual quotation mark in a quoted
15283 token, precede it with a backslash.  (This also works to include
15284 backslashes in tokens.)
15286 @example
15287 # "bad token" # "/\"\\" # := silly(#1,#2,#3)
15288 @end example
15290 @noindent
15291 This will parse @samp{3 bad token 4 /"\ 5} to @samp{silly(3,4,5)}.
15293 The token @kbd{#} has a predefined meaning in Calc's formula parser;
15294 it is not legal to use @samp{"#"} in a syntax rule.  However, longer
15295 tokens that include the @samp{#} character are allowed.  Also, while
15296 @samp{"$"} and @samp{"\""} are allowed as tokens, their presence in
15297 the syntax table will prevent those characters from working in their
15298 usual ways (referring to stack entries and quoting strings,
15299 respectively).
15301 Finally, the notation @samp{%%} anywhere in a syntax table causes
15302 the rest of the line to be ignored as a comment.
15304 @node Precedence in Syntax Tables, Advanced Syntax Patterns, Syntax Table Basics, Syntax Tables
15305 @subsubsection Precedence
15307 @noindent
15308 Different operators are generally assigned different @dfn{precedences}.
15309 By default, an operator defined by a rule like
15311 @example
15312 # foo # := foo(#1,#2)
15313 @end example
15315 @noindent
15316 will have an extremely low precedence, so that @samp{2*3+4 foo 5 == 6}
15317 will be parsed as @samp{(2*3+4) foo (5 == 6)}.  To change the
15318 precedence of an operator, use the notation @samp{#/@var{p}} in
15319 place of @samp{#}, where @var{p} is an integer precedence level.
15320 For example, 185 lies between the precedences for @samp{+} and
15321 @samp{*}, so if we change this rule to
15323 @example
15324 #/185 foo #/186 := foo(#1,#2)
15325 @end example
15327 @noindent
15328 then @samp{2+3 foo 4*5} will be parsed as @samp{2+(3 foo (4*5))}.
15329 Also, because we've given the righthand expression slightly higher
15330 precedence, our new operator will be left-associative:
15331 @samp{1 foo 2 foo 3} will be parsed as @samp{(1 foo 2) foo 3}.
15332 By raising the precedence of the lefthand expression instead, we
15333 can create a right-associative operator.
15335 @xref{Composition Basics}, for a table of precedences of the
15336 standard Calc operators.  For the precedences of operators in other
15337 language modes, look in the Calc source file @file{calc-lang.el}.
15339 @node Advanced Syntax Patterns, Conditional Syntax Rules, Precedence in Syntax Tables, Syntax Tables
15340 @subsubsection Advanced Syntax Patterns
15342 @noindent
15343 To match a function with a variable number of arguments, you could
15344 write
15346 @example
15347 foo ( # ) := myfunc(#1)
15348 foo ( # , # ) := myfunc(#1,#2)
15349 foo ( # , # , # ) := myfunc(#1,#2,#3)
15350 @end example
15352 @noindent
15353 but this isn't very elegant.  To match variable numbers of items,
15354 Calc uses some notations inspired regular expressions and the
15355 ``extended BNF'' style used by some language designers.
15357 @example
15358 foo ( @{ # @}*, ) := apply(myfunc,#1)
15359 @end example
15361 The token @samp{@{} introduces a repeated or optional portion.
15362 One of the three tokens @samp{@}*}, @samp{@}+}, or @samp{@}?}
15363 ends the portion.  These will match zero or more, one or more,
15364 or zero or one copies of the enclosed pattern, respectively.
15365 In addition, @samp{@}*} and @samp{@}+} can be followed by a
15366 separator token (with no space in between, as shown above).
15367 Thus @samp{@{ # @}*,} matches nothing, or one expression, or
15368 several expressions separated by commas.
15370 A complete @samp{@{ ... @}} item matches as a vector of the
15371 items that matched inside it.  For example, the above rule will
15372 match @samp{foo(1,2,3)} to get @samp{apply(myfunc,[1,2,3])}.
15373 The Calc @code{apply} function takes a function name and a vector
15374 of arguments and builds a call to the function with those
15375 arguments, so the net result is the formula @samp{myfunc(1,2,3)}.
15377 If the body of a @samp{@{ ... @}} contains several @samp{#}s
15378 (or nested @samp{@{ ... @}} constructs), then the items will be
15379 strung together into the resulting vector.  If the body
15380 does not contain anything but literal tokens, the result will
15381 always be an empty vector.
15383 @example
15384 foo ( @{ # , # @}+, ) := bar(#1)
15385 foo ( @{ @{ # @}*, @}*; ) := matrix(#1)
15386 @end example
15388 @noindent
15389 will parse @samp{foo(1,2,3,4)} as @samp{bar([1,2,3,4])}, and
15390 @samp{foo(1,2;3,4)} as @samp{matrix([[1,2],[3,4]])}.  Also, after
15391 some thought it's easy to see how this pair of rules will parse
15392 @samp{foo(1,2,3)} as @samp{matrix([[1,2,3]])}, since the first
15393 rule will only match an even number of arguments.  The rule
15395 @example
15396 foo ( # @{ , # , # @}? ) := bar(#1,#2)
15397 @end example
15399 @noindent
15400 will parse @samp{foo(2,3,4)} as @samp{bar(2,[3,4])}, and
15401 @samp{foo(2)} as @samp{bar(2,[])}.
15403 The notation @samp{@{ ... @}?.} (note the trailing period) works
15404 just the same as regular @samp{@{ ... @}?}, except that it does not
15405 count as an argument; the following two rules are equivalent:
15407 @example
15408 foo ( # , @{ also @}? # ) := bar(#1,#3)
15409 foo ( # , @{ also @}?. # ) := bar(#1,#2)
15410 @end example
15412 @noindent
15413 Note that in the first case the optional text counts as @samp{#2},
15414 which will always be an empty vector, but in the second case no
15415 empty vector is produced.
15417 Another variant is @samp{@{ ... @}?$}, which means the body is
15418 optional only at the end of the input formula.  All built-in syntax
15419 rules in Calc use this for closing delimiters, so that during
15420 algebraic entry you can type @kbd{[sqrt(2), sqrt(3 RET}, omitting
15421 the closing parenthesis and bracket.  Calc does this automatically
15422 for trailing @samp{)}, @samp{]}, and @samp{>} tokens in syntax
15423 rules, but you can use @samp{@{ ... @}?$} explicitly to get
15424 this effect with any token (such as @samp{"@}"} or @samp{end}).
15425 Like @samp{@{ ... @}?.}, this notation does not count as an
15426 argument.  Conversely, you can use quotes, as in @samp{")"}, to
15427 prevent a closing-delimiter token from being automatically treated
15428 as optional.
15430 Calc's parser does not have full backtracking, which means some
15431 patterns will not work as you might expect:
15433 @example
15434 foo ( @{ # , @}? # , # ) := bar(#1,#2,#3)
15435 @end example
15437 @noindent
15438 Here we are trying to make the first argument optional, so that
15439 @samp{foo(2,3)} parses as @samp{bar([],2,3)}.  Unfortunately, Calc
15440 first tries to match @samp{2,} against the optional part of the
15441 pattern, finds a match, and so goes ahead to match the rest of the
15442 pattern.  Later on it will fail to match the second comma, but it
15443 doesn't know how to go back and try the other alternative at that
15444 point.  One way to get around this would be to use two rules:
15446 @example
15447 foo ( # , # , # ) := bar([#1],#2,#3)
15448 foo ( # , # ) := bar([],#1,#2)
15449 @end example
15451 More precisely, when Calc wants to match an optional or repeated
15452 part of a pattern, it scans forward attempting to match that part.
15453 If it reaches the end of the optional part without failing, it
15454 ``finalizes'' its choice and proceeds.  If it fails, though, it
15455 backs up and tries the other alternative.  Thus Calc has ``partial''
15456 backtracking.  A fully backtracking parser would go on to make sure
15457 the rest of the pattern matched before finalizing the choice.
15459 @node Conditional Syntax Rules, , Advanced Syntax Patterns, Syntax Tables
15460 @subsubsection Conditional Syntax Rules
15462 @noindent
15463 It is possible to attach a @dfn{condition} to a syntax rule.  For
15464 example, the rules
15466 @example
15467 foo ( # ) := ifoo(#1) :: integer(#1)
15468 foo ( # ) := gfoo(#1)
15469 @end example
15471 @noindent
15472 will parse @samp{foo(3)} as @samp{ifoo(3)}, but will parse
15473 @samp{foo(3.5)} and @samp{foo(x)} as calls to @code{gfoo}.  Any
15474 number of conditions may be attached; all must be true for the
15475 rule to succeed.  A condition is ``true'' if it evaluates to a
15476 nonzero number.  @xref{Logical Operations}, for a list of Calc
15477 functions like @code{integer} that perform logical tests.
15479 The exact sequence of events is as follows:  When Calc tries a
15480 rule, it first matches the pattern as usual.  It then substitutes
15481 @samp{#1}, @samp{#2}, etc., in the conditions, if any.  Next, the
15482 conditions are simplified and evaluated in order from left to right,
15483 as if by the @w{@kbd{a s}} algebra command (@pxref{Simplifying Formulas}).
15484 Each result is true if it is a nonzero number, or an expression
15485 that can be proven to be nonzero (@pxref{Declarations}).  If the
15486 results of all conditions are true, the expression (such as
15487 @samp{ifoo(#1)}) has its @samp{#}s substituted, and that is the
15488 result of the parse.  If the result of any condition is false, Calc
15489 goes on to try the next rule in the syntax table.
15491 Syntax rules also support @code{let} conditions, which operate in
15492 exactly the same way as they do in algebraic rewrite rules.
15493 @xref{Other Features of Rewrite Rules}, for details.  A @code{let}
15494 condition is always true, but as a side effect it defines a
15495 variable which can be used in later conditions, and also in the
15496 expression after the @samp{:=} sign:
15498 @example
15499 foo ( # ) := hifoo(x) :: let(x := #1 + 0.5) :: dnumint(x)
15500 @end example
15502 @noindent
15503 The @code{dnumint} function tests if a value is numerically an
15504 integer, i.e., either a true integer or an integer-valued float.
15505 This rule will parse @code{foo} with a half-integer argument,
15506 like @samp{foo(3.5)}, to a call like @samp{hifoo(4.)}.
15508 The lefthand side of a syntax rule @code{let} must be a simple
15509 variable, not the arbitrary pattern that is allowed in rewrite
15510 rules.
15512 The @code{matches} function is also treated specially in syntax
15513 rule conditions (again, in the same way as in rewrite rules).
15514 @xref{Matching Commands}.  If the matching pattern contains
15515 meta-variables, then those meta-variables may be used in later
15516 conditions and in the result expression.  The arguments to
15517 @code{matches} are not evaluated in this situation.
15519 @example
15520 sum ( # , # ) := sum(#1,a,b,c) :: matches(#2, a=[b..c])
15521 @end example
15523 @noindent
15524 This is another way to implement the Maple mode @code{sum} notation.
15525 In this approach, we allow @samp{#2} to equal the whole expression
15526 @samp{i=1..10}.  Then, we use @code{matches} to break it apart into
15527 its components.  If the expression turns out not to match the pattern,
15528 the syntax rule will fail.  Note that @kbd{Z S} always uses Calc's
15529 normal language mode for editing expressions in syntax rules, so we
15530 must use regular Calc notation for the interval @samp{[b..c]} that
15531 will correspond to the Maple mode interval @samp{1..10}.
15533 @node Modes Variable, Calc Mode Line, Language Modes, Mode Settings
15534 @section The @code{Modes} Variable
15536 @noindent
15537 @kindex m g
15538 @pindex calc-get-modes
15539 The @kbd{m g} (@code{calc-get-modes}) command pushes onto the stack
15540 a vector of numbers that describes the various mode settings that
15541 are in effect.  With a numeric prefix argument, it pushes only the
15542 @var{n}th mode, i.e., the @var{n}th element of this vector.  Keyboard
15543 macros can use the @kbd{m g} command to modify their behavior based
15544 on the current mode settings.
15546 @cindex @code{Modes} variable
15547 @vindex Modes
15548 The modes vector is also available in the special variable
15549 @code{Modes}.  In other words, @kbd{m g} is like @kbd{s r Modes RET}.
15550 It will not work to store into this variable; in fact, if you do,
15551 @code{Modes} will cease to track the current modes.  (The @kbd{m g}
15552 command will continue to work, however.)
15554 In general, each number in this vector is suitable as a numeric
15555 prefix argument to the associated mode-setting command.  (Recall
15556 that the @kbd{~} key takes a number from the stack and gives it as
15557 a numeric prefix to the next command.)
15559 The elements of the modes vector are as follows:
15561 @enumerate
15562 @item
15563 Current precision.  Default is 12; associated command is @kbd{p}.
15565 @item
15566 Binary word size.  Default is 32; associated command is @kbd{b w}.
15568 @item
15569 Stack size (not counting the value about to be pushed by @kbd{m g}).
15570 This is zero if @kbd{m g} is executed with an empty stack.
15572 @item
15573 Number radix.  Default is 10; command is @kbd{d r}.
15575 @item
15576 Floating-point format.  This is the number of digits, plus the
15577 constant 0 for normal notation, 10000 for scientific notation,
15578 20000 for engineering notation, or 30000 for fixed-point notation.
15579 These codes are acceptable as prefix arguments to the @kbd{d n}
15580 command, but note that this may lose information:  For example,
15581 @kbd{d s} and @kbd{C-u 12 d s} have similar (but not quite
15582 identical) effects if the current precision is 12, but they both
15583 produce a code of 10012, which will be treated by @kbd{d n} as
15584 @kbd{C-u 12 d s}.  If the precision then changes, the float format
15585 will still be frozen at 12 significant figures.
15587 @item
15588 Angular mode.  Default is 1 (degrees).  Other values are 2 (radians)
15589 and 3 (HMS).  The @kbd{m d} command accepts these prefixes.
15591 @item
15592 Symbolic mode.  Value is 0 or 1; default is 0.  Command is @kbd{m s}.
15594 @item 
15595 Fraction mode.  Value is 0 or 1; default is 0.  Command is @kbd{m f}.
15597 @item
15598 Polar mode.  Value is 0 (rectangular) or 1 (polar); default is 0.
15599 Command is @kbd{m p}.
15601 @item
15602 Matrix/scalar mode.  Default value is @i{-1}.  Value is 0 for scalar
15603 mode, @i{-2} for matrix mode, or @i{N} for @c{$N\times N$}
15604 @i{NxN} matrix mode.  Command is @kbd{m v}.
15606 @item
15607 Simplification mode.  Default is 1.  Value is @i{-1} for off (@kbd{m O}),
15608 0 for @kbd{m N}, 2 for @kbd{m B}, 3 for @kbd{m A}, 4 for @kbd{m E},
15609 or 5 for @w{@kbd{m U}}.  The @kbd{m D} command accepts these prefixes.
15611 @item
15612 Infinite mode.  Default is @i{-1} (off).  Value is 1 if the mode is on,
15613 or 0 if the mode is on with positive zeros.  Command is @kbd{m i}.
15614 @end enumerate
15616 For example, the sequence @kbd{M-1 m g RET 2 + ~ p} increases the
15617 precision by two, leaving a copy of the old precision on the stack.
15618 Later, @kbd{~ p} will restore the original precision using that
15619 stack value.  (This sequence might be especially useful inside a
15620 keyboard macro.)
15622 As another example, @kbd{M-3 m g 1 - ~ DEL} deletes all but the
15623 oldest (bottommost) stack entry.
15625 Yet another example:  The HP-48 ``round'' command rounds a number
15626 to the current displayed precision.  You could roughly emulate this
15627 in Calc with the sequence @kbd{M-5 m g 10000 % ~ c c}.  (This
15628 would not work for fixed-point mode, but it wouldn't be hard to
15629 do a full emulation with the help of the @kbd{Z [} and @kbd{Z ]}
15630 programming commands.  @xref{Conditionals in Macros}.)
15632 @node Calc Mode Line, , Modes Variable, Mode Settings
15633 @section The Calc Mode Line
15635 @noindent
15636 @cindex Mode line indicators
15637 This section is a summary of all symbols that can appear on the
15638 Calc mode line, the highlighted bar that appears under the Calc
15639 stack window (or under an editing window in Embedded Mode).
15641 The basic mode line format is:
15643 @example
15644 --%%-Calc: 12 Deg @var{other modes}       (Calculator)
15645 @end example
15647 The @samp{%%} is the Emacs symbol for ``read-only''; it shows that
15648 regular Emacs commands are not allowed to edit the stack buffer
15649 as if it were text.
15651 The word @samp{Calc:} changes to @samp{CalcEmbed:} if Embedded Mode
15652 is enabled.  The words after this describe the various Calc modes
15653 that are in effect.
15655 The first mode is always the current precision, an integer.
15656 The second mode is always the angular mode, either @code{Deg},
15657 @code{Rad}, or @code{Hms}.
15659 Here is a complete list of the remaining symbols that can appear
15660 on the mode line:
15662 @table @code
15663 @item Alg
15664 Algebraic mode (@kbd{m a}; @pxref{Algebraic Entry}).
15666 @item Alg[(
15667 Incomplete algebraic mode (@kbd{C-u m a}).
15669 @item Alg*
15670 Total algebraic mode (@kbd{m t}).
15672 @item Symb
15673 Symbolic mode (@kbd{m s}; @pxref{Symbolic Mode}).
15675 @item Matrix
15676 Matrix mode (@kbd{m v}; @pxref{Matrix Mode}).
15678 @item Matrix@var{n}
15679 Dimensioned matrix mode (@kbd{C-u @var{n} m v}).
15681 @item Scalar
15682 Scalar mode (@kbd{m v}; @pxref{Matrix Mode}).
15684 @item Polar
15685 Polar complex mode (@kbd{m p}; @pxref{Polar Mode}).
15687 @item Frac
15688 Fraction mode (@kbd{m f}; @pxref{Fraction Mode}).
15690 @item Inf
15691 Infinite mode (@kbd{m i}; @pxref{Infinite Mode}).
15693 @item +Inf
15694 Positive infinite mode (@kbd{C-u 0 m i}).
15696 @item NoSimp
15697 Default simplifications off (@kbd{m O}; @pxref{Simplification Modes}).
15699 @item NumSimp
15700 Default simplifications for numeric arguments only (@kbd{m N}).
15702 @item BinSimp@var{w}
15703 Binary-integer simplification mode; word size @var{w} (@kbd{m B}, @kbd{b w}).
15705 @item AlgSimp
15706 Algebraic simplification mode (@kbd{m A}).
15708 @item ExtSimp
15709 Extended algebraic simplification mode (@kbd{m E}).
15711 @item UnitSimp
15712 Units simplification mode (@kbd{m U}).
15714 @item Bin
15715 Current radix is 2 (@kbd{d 2}; @pxref{Radix Modes}).
15717 @item Oct
15718 Current radix is 8 (@kbd{d 8}).
15720 @item Hex
15721 Current radix is 16 (@kbd{d 6}).
15723 @item Radix@var{n}
15724 Current radix is @var{n} (@kbd{d r}).
15726 @item Zero
15727 Leading zeros (@kbd{d z}; @pxref{Radix Modes}).
15729 @item Big
15730 Big language mode (@kbd{d B}; @pxref{Normal Language Modes}).
15732 @item Flat
15733 One-line normal language mode (@kbd{d O}).
15735 @item Unform
15736 Unformatted language mode (@kbd{d U}).
15738 @item C
15739 C language mode (@kbd{d C}; @pxref{C FORTRAN Pascal}).
15741 @item Pascal
15742 Pascal language mode (@kbd{d P}).
15744 @item Fortran
15745 FORTRAN language mode (@kbd{d F}).
15747 @item TeX
15748 @TeX{} language mode (@kbd{d T}; @pxref{TeX Language Mode}).
15750 @item Eqn
15751 @dfn{Eqn} language mode (@kbd{d E}; @pxref{Eqn Language Mode}).
15753 @item Math
15754 Mathematica language mode (@kbd{d M}; @pxref{Mathematica Language Mode}).
15756 @item Maple
15757 Maple language mode (@kbd{d W}; @pxref{Maple Language Mode}).
15759 @item Norm@var{n}
15760 Normal float mode with @var{n} digits (@kbd{d n}; @pxref{Float Formats}).
15762 @item Fix@var{n}
15763 Fixed point mode with @var{n} digits after the point (@kbd{d f}).
15765 @item Sci
15766 Scientific notation mode (@kbd{d s}).
15768 @item Sci@var{n}
15769 Scientific notation with @var{n} digits (@kbd{d s}).
15771 @item Eng
15772 Engineering notation mode (@kbd{d e}).
15774 @item Eng@var{n}
15775 Engineering notation with @var{n} digits (@kbd{d e}).
15777 @item Left@var{n}
15778 Left-justified display indented by @var{n} (@kbd{d <}; @pxref{Justification}).
15780 @item Right
15781 Right-justified display (@kbd{d >}).
15783 @item Right@var{n}
15784 Right-justified display with width @var{n} (@kbd{d >}).
15786 @item Center
15787 Centered display (@kbd{d =}).
15789 @item Center@var{n}
15790 Centered display with center column @var{n} (@kbd{d =}).
15792 @item Wid@var{n}
15793 Line breaking with width @var{n} (@kbd{d b}; @pxref{Normal Language Modes}).
15795 @item Wide
15796 No line breaking (@kbd{d b}).
15798 @item Break
15799 Selections show deep structure (@kbd{j b}; @pxref{Making Selections}).
15801 @item Save
15802 Record modes in @file{~/.emacs} (@kbd{m R}; @pxref{General Mode Commands}).
15804 @item Local
15805 Record modes in Embedded buffer (@kbd{m R}).
15807 @item LocEdit
15808 Record modes as editing-only in Embedded buffer (@kbd{m R}).
15810 @item LocPerm
15811 Record modes as permanent-only in Embedded buffer (@kbd{m R}).
15813 @item Global
15814 Record modes as global in Embedded buffer (@kbd{m R}).
15816 @item Manual
15817 Automatic recomputation turned off (@kbd{m C}; @pxref{Automatic
15818 Recomputation}).
15820 @item Graph
15821 GNUPLOT process is alive in background (@pxref{Graphics}).
15823 @item Sel
15824 Top-of-stack has a selection (Embedded only; @pxref{Making Selections}).
15826 @item Dirty
15827 The stack display may not be up-to-date (@pxref{Display Modes}).
15829 @item Inv
15830 ``Inverse'' prefix was pressed (@kbd{I}; @pxref{Inverse and Hyperbolic}).
15832 @item Hyp
15833 ``Hyperbolic'' prefix was pressed (@kbd{H}).
15835 @item Keep
15836 ``Keep-arguments'' prefix was pressed (@kbd{K}).
15838 @item Narrow
15839 Stack is truncated (@kbd{d t}; @pxref{Truncating the Stack}).
15840 @end table
15842 In addition, the symbols @code{Active} and @code{~Active} can appear
15843 as minor modes on an Embedded buffer's mode line.  @xref{Embedded Mode}.
15845 @node Arithmetic, Scientific Functions, Mode Settings, Top
15846 @chapter Arithmetic Functions
15848 @noindent
15849 This chapter describes the Calc commands for doing simple calculations
15850 on numbers, such as addition, absolute value, and square roots.  These
15851 commands work by removing the top one or two values from the stack,
15852 performing the desired operation, and pushing the result back onto the
15853 stack.  If the operation cannot be performed, the result pushed is a
15854 formula instead of a number, such as @samp{2/0} (because division by zero
15855 is illegal) or @samp{sqrt(x)} (because the argument @samp{x} is a formula).
15857 Most of the commands described here can be invoked by a single keystroke.
15858 Some of the more obscure ones are two-letter sequences beginning with
15859 the @kbd{f} (``functions'') prefix key.
15861 @xref{Prefix Arguments}, for a discussion of the effect of numeric
15862 prefix arguments on commands in this chapter which do not otherwise
15863 interpret a prefix argument.
15865 @menu
15866 * Basic Arithmetic::
15867 * Integer Truncation::
15868 * Complex Number Functions::
15869 * Conversions::
15870 * Date Arithmetic::
15871 * Financial Functions::
15872 * Binary Functions::
15873 @end menu
15875 @node Basic Arithmetic, Integer Truncation, Arithmetic, Arithmetic
15876 @section Basic Arithmetic
15878 @noindent
15879 @kindex +
15880 @pindex calc-plus
15881 @c @mindex @null
15882 @tindex +
15883 The @kbd{+} (@code{calc-plus}) command adds two numbers.  The numbers may
15884 be any of the standard Calc data types.  The resulting sum is pushed back
15885 onto the stack.
15887 If both arguments of @kbd{+} are vectors or matrices (of matching dimensions),
15888 the result is a vector or matrix sum.  If one argument is a vector and the
15889 other a scalar (i.e., a non-vector), the scalar is added to each of the
15890 elements of the vector to form a new vector.  If the scalar is not a
15891 number, the operation is left in symbolic form:  Suppose you added @samp{x}
15892 to the vector @samp{[1,2]}.  You may want the result @samp{[1+x,2+x]}, or
15893 you may plan to substitute a 2-vector for @samp{x} in the future.  Since
15894 the Calculator can't tell which interpretation you want, it makes the
15895 safest assumption.  @xref{Reducing and Mapping}, for a way to add @samp{x}
15896 to every element of a vector.
15898 If either argument of @kbd{+} is a complex number, the result will in general
15899 be complex.  If one argument is in rectangular form and the other polar,
15900 the current Polar Mode determines the form of the result.  If Symbolic
15901 Mode is enabled, the sum may be left as a formula if the necessary
15902 conversions for polar addition are non-trivial.
15904 If both arguments of @kbd{+} are HMS forms, the forms are added according to
15905 the usual conventions of hours-minutes-seconds notation.  If one argument
15906 is an HMS form and the other is a number, that number is converted from
15907 degrees or radians (depending on the current Angular Mode) to HMS format
15908 and then the two HMS forms are added.
15910 If one argument of @kbd{+} is a date form, the other can be either a
15911 real number, which advances the date by a certain number of days, or
15912 an HMS form, which advances the date by a certain amount of time.
15913 Subtracting two date forms yields the number of days between them.
15914 Adding two date forms is meaningless, but Calc interprets it as the
15915 subtraction of one date form and the negative of the other.  (The
15916 negative of a date form can be understood by remembering that dates
15917 are stored as the number of days before or after Jan 1, 1 AD.)
15919 If both arguments of @kbd{+} are error forms, the result is an error form
15920 with an appropriately computed standard deviation.  If one argument is an
15921 error form and the other is a number, the number is taken to have zero error.
15922 Error forms may have symbolic formulas as their mean and/or error parts;
15923 adding these will produce a symbolic error form result.  However, adding an
15924 error form to a plain symbolic formula (as in @samp{(a +/- b) + c}) will not
15925 work, for the same reasons just mentioned for vectors.  Instead you must
15926 write @samp{(a +/- b) + (c +/- 0)}.
15928 If both arguments of @kbd{+} are modulo forms with equal values of @cite{M},
15929 or if one argument is a modulo form and the other a plain number, the
15930 result is a modulo form which represents the sum, modulo @cite{M}, of
15931 the two values.
15933 If both arguments of @kbd{+} are intervals, the result is an interval
15934 which describes all possible sums of the possible input values.  If
15935 one argument is a plain number, it is treated as the interval
15936 @w{@samp{[x ..@: x]}}.
15938 If one argument of @kbd{+} is an infinity and the other is not, the
15939 result is that same infinity.  If both arguments are infinite and in
15940 the same direction, the result is the same infinity, but if they are
15941 infinite in different directions the result is @code{nan}.
15943 @kindex -
15944 @pindex calc-minus
15945 @c @mindex @null
15946 @tindex -
15947 The @kbd{-} (@code{calc-minus}) command subtracts two values.  The top
15948 number on the stack is subtracted from the one behind it, so that the
15949 computation @kbd{5 @key{RET} 2 -} produces 3, not @i{-3}.  All options
15950 available for @kbd{+} are available for @kbd{-} as well.
15952 @kindex *
15953 @pindex calc-times
15954 @c @mindex @null
15955 @tindex *
15956 The @kbd{*} (@code{calc-times}) command multiplies two numbers.  If one
15957 argument is a vector and the other a scalar, the scalar is multiplied by
15958 the elements of the vector to produce a new vector.  If both arguments
15959 are vectors, the interpretation depends on the dimensions of the
15960 vectors:  If both arguments are matrices, a matrix multiplication is
15961 done.  If one argument is a matrix and the other a plain vector, the
15962 vector is interpreted as a row vector or column vector, whichever is
15963 dimensionally correct.  If both arguments are plain vectors, the result
15964 is a single scalar number which is the dot product of the two vectors.
15966 If one argument of @kbd{*} is an HMS form and the other a number, the
15967 HMS form is multiplied by that amount.  It is an error to multiply two
15968 HMS forms together, or to attempt any multiplication involving date
15969 forms.  Error forms, modulo forms, and intervals can be multiplied;
15970 see the comments for addition of those forms.  When two error forms
15971 or intervals are multiplied they are considered to be statistically
15972 independent; thus, @samp{[-2 ..@: 3] * [-2 ..@: 3]} is @samp{[-6 ..@: 9]},
15973 whereas @w{@samp{[-2 ..@: 3] ^ 2}} is @samp{[0 ..@: 9]}.
15975 @kindex /
15976 @pindex calc-divide
15977 @c @mindex @null
15978 @tindex /
15979 The @kbd{/} (@code{calc-divide}) command divides two numbers.  When
15980 dividing a scalar @cite{B} by a square matrix @cite{A}, the computation
15981 performed is @cite{B} times the inverse of @cite{A}.  This also occurs
15982 if @cite{B} is itself a vector or matrix, in which case the effect is
15983 to solve the set of linear equations represented by @cite{B}.  If @cite{B}
15984 is a matrix with the same number of rows as @cite{A}, or a plain vector
15985 (which is interpreted here as a column vector), then the equation
15986 @cite{A X = B} is solved for the vector or matrix @cite{X}.  Otherwise,
15987 if @cite{B} is a non-square matrix with the same number of @emph{columns}
15988 as @cite{A}, the equation @cite{X A = B} is solved.  If you wish a vector
15989 @cite{B} to be interpreted as a row vector to be solved as @cite{X A = B},
15990 make it into a one-row matrix with @kbd{C-u 1 v p} first.  To force a
15991 left-handed solution with a square matrix @cite{B}, transpose @cite{A} and
15992 @cite{B} before dividing, then transpose the result.
15994 HMS forms can be divided by real numbers or by other HMS forms.  Error
15995 forms can be divided in any combination of ways.  Modulo forms where both
15996 values and the modulo are integers can be divided to get an integer modulo
15997 form result.  Intervals can be divided; dividing by an interval that
15998 encompasses zero or has zero as a limit will result in an infinite
15999 interval.
16001 @kindex ^
16002 @pindex calc-power
16003 @c @mindex @null
16004 @tindex ^
16005 The @kbd{^} (@code{calc-power}) command raises a number to a power.  If
16006 the power is an integer, an exact result is computed using repeated
16007 multiplications.  For non-integer powers, Calc uses Newton's method or
16008 logarithms and exponentials.  Square matrices can be raised to integer
16009 powers.  If either argument is an error (or interval or modulo) form,
16010 the result is also an error (or interval or modulo) form.
16012 @kindex I ^
16013 @tindex nroot
16014 If you press the @kbd{I} (inverse) key first, the @kbd{I ^} command
16015 computes an Nth root:  @kbd{125 RET 3 I ^} computes the number 5.
16016 (This is entirely equivalent to @kbd{125 RET 1:3 ^}.)
16018 @kindex \
16019 @pindex calc-idiv
16020 @tindex idiv
16021 @c @mindex @null
16022 @tindex \
16023 The @kbd{\} (@code{calc-idiv}) command divides two numbers on the stack
16024 to produce an integer result.  It is equivalent to dividing with
16025 @key{/}, then rounding down with @kbd{F} (@code{calc-floor}), only a bit
16026 more convenient and efficient.  Also, since it is an all-integer
16027 operation when the arguments are integers, it avoids problems that
16028 @kbd{/ F} would have with floating-point roundoff.
16030 @kindex %
16031 @pindex calc-mod
16032 @c @mindex @null
16033 @tindex %
16034 The @kbd{%} (@code{calc-mod}) command performs a ``modulo'' (or ``remainder'')
16035 operation.  Mathematically, @samp{a%b = a - (a\b)*b}, and is defined
16036 for all real numbers @cite{a} and @cite{b} (except @cite{b=0}).  For
16037 positive @cite{b}, the result will always be between 0 (inclusive) and
16038 @cite{b} (exclusive).  Modulo does not work for HMS forms and error forms.
16039 If @cite{a} is a modulo form, its modulo is changed to @cite{b}, which
16040 must be positive real number.
16042 @kindex :
16043 @pindex calc-fdiv
16044 @tindex fdiv
16045 The @kbd{:} (@code{calc-fdiv}) command [@code{fdiv} function in a formula]
16046 divides the two integers on the top of the stack to produce a fractional
16047 result.  This is a convenient shorthand for enabling Fraction Mode (with
16048 @kbd{m f}) temporarily and using @samp{/}.  Note that during numeric entry
16049 the @kbd{:} key is interpreted as a fraction separator, so to divide 8 by 6
16050 you would have to type @kbd{8 @key{RET} 6 @key{RET} :}.  (Of course, in
16051 this case, it would be much easier simply to enter the fraction directly
16052 as @kbd{8:6 @key{RET}}!)
16054 @kindex n
16055 @pindex calc-change-sign
16056 The @kbd{n} (@code{calc-change-sign}) command negates the number on the top
16057 of the stack.  It works on numbers, vectors and matrices, HMS forms, date
16058 forms, error forms, intervals, and modulo forms.
16060 @kindex A
16061 @pindex calc-abs
16062 @tindex abs
16063 The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the absolute
16064 value of a number.  The result of @code{abs} is always a nonnegative
16065 real number:  With a complex argument, it computes the complex magnitude.
16066 With a vector or matrix argument, it computes the Frobenius norm, i.e.,
16067 the square root of the sum of the squares of the absolute values of the
16068 elements.  The absolute value of an error form is defined by replacing
16069 the mean part with its absolute value and leaving the error part the same.
16070 The absolute value of a modulo form is undefined.  The absolute value of
16071 an interval is defined in the obvious way.
16073 @kindex f A
16074 @pindex calc-abssqr
16075 @tindex abssqr
16076 The @kbd{f A} (@code{calc-abssqr}) [@code{abssqr}] command computes the
16077 absolute value squared of a number, vector or matrix, or error form.
16079 @kindex f s
16080 @pindex calc-sign
16081 @tindex sign
16082 The @kbd{f s} (@code{calc-sign}) [@code{sign}] command returns 1 if its
16083 argument is positive, @i{-1} if its argument is negative, or 0 if its
16084 argument is zero.  In algebraic form, you can also write @samp{sign(a,x)}
16085 which evaluates to @samp{x * sign(a)}, i.e., either @samp{x}, @samp{-x}, or
16086 zero depending on the sign of @samp{a}.
16088 @kindex &
16089 @pindex calc-inv
16090 @tindex inv
16091 @cindex Reciprocal
16092 The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
16093 reciprocal of a number, i.e., @cite{1 / x}.  Operating on a square
16094 matrix, it computes the inverse of that matrix.
16096 @kindex Q
16097 @pindex calc-sqrt
16098 @tindex sqrt
16099 The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] command computes the square
16100 root of a number.  For a negative real argument, the result will be a
16101 complex number whose form is determined by the current Polar Mode.
16103 @kindex f h
16104 @pindex calc-hypot
16105 @tindex hypot
16106 The @kbd{f h} (@code{calc-hypot}) [@code{hypot}] command computes the square
16107 root of the sum of the squares of two numbers.  That is, @samp{hypot(a,b)}
16108 is the length of the hypotenuse of a right triangle with sides @cite{a}
16109 and @cite{b}.  If the arguments are complex numbers, their squared
16110 magnitudes are used.
16112 @kindex f Q
16113 @pindex calc-isqrt
16114 @tindex isqrt
16115 The @kbd{f Q} (@code{calc-isqrt}) [@code{isqrt}] command computes the
16116 integer square root of an integer.  This is the true square root of the
16117 number, rounded down to an integer.  For example, @samp{isqrt(10)}
16118 produces 3.  Note that, like @kbd{\} [@code{idiv}], this uses exact
16119 integer arithmetic throughout to avoid roundoff problems.  If the input
16120 is a floating-point number or other non-integer value, this is exactly
16121 the same as @samp{floor(sqrt(x))}.
16123 @kindex f n
16124 @kindex f x
16125 @pindex calc-min
16126 @tindex min
16127 @pindex calc-max
16128 @tindex max
16129 The @kbd{f n} (@code{calc-min}) [@code{min}] and @kbd{f x} (@code{calc-max})
16130 [@code{max}] commands take the minimum or maximum of two real numbers,
16131 respectively.  These commands also work on HMS forms, date forms,
16132 intervals, and infinities.  (In algebraic expressions, these functions
16133 take any number of arguments and return the maximum or minimum among
16134 all the arguments.)@refill
16136 @kindex f M
16137 @kindex f X
16138 @pindex calc-mant-part
16139 @tindex mant
16140 @pindex calc-xpon-part
16141 @tindex xpon
16142 The @kbd{f M} (@code{calc-mant-part}) [@code{mant}] function extracts
16143 the ``mantissa'' part @cite{m} of its floating-point argument; @kbd{f X}
16144 (@code{calc-xpon-part}) [@code{xpon}] extracts the ``exponent'' part
16145 @cite{e}.  The original number is equal to @c{$m \times 10^e$}
16146 @cite{m * 10^e},
16147 where @cite{m} is in the interval @samp{[1.0 ..@: 10.0)} except that
16148 @cite{m=e=0} if the original number is zero.  For integers
16149 and fractions, @code{mant} returns the number unchanged and @code{xpon}
16150 returns zero.  The @kbd{v u} (@code{calc-unpack}) command can also be
16151 used to ``unpack'' a floating-point number; this produces an integer
16152 mantissa and exponent, with the constraint that the mantissa is not
16153 a multiple of ten (again except for the @cite{m=e=0} case).@refill
16155 @kindex f S
16156 @pindex calc-scale-float
16157 @tindex scf
16158 The @kbd{f S} (@code{calc-scale-float}) [@code{scf}] function scales a number
16159 by a given power of ten.  Thus, @samp{scf(mant(x), xpon(x)) = x} for any
16160 real @samp{x}.  The second argument must be an integer, but the first
16161 may actually be any numeric value.  For example, @samp{scf(5,-2) = 0.05}
16162 or @samp{1:20} depending on the current Fraction Mode.@refill
16164 @kindex f [
16165 @kindex f ]
16166 @pindex calc-decrement
16167 @pindex calc-increment
16168 @tindex decr
16169 @tindex incr
16170 The @kbd{f [} (@code{calc-decrement}) [@code{decr}] and @kbd{f ]}
16171 (@code{calc-increment}) [@code{incr}] functions decrease or increase
16172 a number by one unit.  For integers, the effect is obvious.  For
16173 floating-point numbers, the change is by one unit in the last place.
16174 For example, incrementing @samp{12.3456} when the current precision
16175 is 6 digits yields @samp{12.3457}.  If the current precision had been
16176 8 digits, the result would have been @samp{12.345601}.  Incrementing
16177 @samp{0.0} produces @c{$10^{-p}$}
16178 @cite{10^-p}, where @cite{p} is the current
16179 precision.  These operations are defined only on integers and floats.
16180 With numeric prefix arguments, they change the number by @cite{n} units.
16182 Note that incrementing followed by decrementing, or vice-versa, will
16183 almost but not quite always cancel out.  Suppose the precision is
16184 6 digits and the number @samp{9.99999} is on the stack.  Incrementing
16185 will produce @samp{10.0000}; decrementing will produce @samp{9.9999}.
16186 One digit has been dropped.  This is an unavoidable consequence of the
16187 way floating-point numbers work.
16189 Incrementing a date/time form adjusts it by a certain number of seconds.
16190 Incrementing a pure date form adjusts it by a certain number of days.
16192 @node Integer Truncation, Complex Number Functions, Basic Arithmetic, Arithmetic
16193 @section Integer Truncation
16195 @noindent
16196 There are four commands for truncating a real number to an integer,
16197 differing mainly in their treatment of negative numbers.  All of these
16198 commands have the property that if the argument is an integer, the result
16199 is the same integer.  An integer-valued floating-point argument is converted
16200 to integer form.
16202 If you press @kbd{H} (@code{calc-hyperbolic}) first, the result will be
16203 expressed as an integer-valued floating-point number.
16205 @cindex Integer part of a number
16206 @kindex F
16207 @pindex calc-floor
16208 @tindex floor
16209 @tindex ffloor
16210 @c @mindex @null
16211 @kindex H F
16212 The @kbd{F} (@code{calc-floor}) [@code{floor} or @code{ffloor}] command
16213 truncates a real number to the next lower integer, i.e., toward minus
16214 infinity.  Thus @kbd{3.6 F} produces 3, but @kbd{_3.6 F} produces
16215 @i{-4}.@refill
16217 @kindex I F
16218 @pindex calc-ceiling
16219 @tindex ceil
16220 @tindex fceil
16221 @c @mindex @null
16222 @kindex H I F
16223 The @kbd{I F} (@code{calc-ceiling}) [@code{ceil} or @code{fceil}]
16224 command truncates toward positive infinity.  Thus @kbd{3.6 I F} produces
16225 4, and @kbd{_3.6 I F} produces @i{-3}.@refill
16227 @kindex R
16228 @pindex calc-round
16229 @tindex round
16230 @tindex fround
16231 @c @mindex @null
16232 @kindex H R
16233 The @kbd{R} (@code{calc-round}) [@code{round} or @code{fround}] command
16234 rounds to the nearest integer.  When the fractional part is .5 exactly,
16235 this command rounds away from zero.  (All other rounding in the
16236 Calculator uses this convention as well.)  Thus @kbd{3.5 R} produces 4
16237 but @kbd{3.4 R} produces 3; @kbd{_3.5 R} produces @i{-4}.@refill
16239 @kindex I R
16240 @pindex calc-trunc
16241 @tindex trunc
16242 @tindex ftrunc
16243 @c @mindex @null
16244 @kindex H I R
16245 The @kbd{I R} (@code{calc-trunc}) [@code{trunc} or @code{ftrunc}]
16246 command truncates toward zero.  In other words, it ``chops off''
16247 everything after the decimal point.  Thus @kbd{3.6 I R} produces 3 and
16248 @kbd{_3.6 I R} produces @i{-3}.@refill
16250 These functions may not be applied meaningfully to error forms, but they
16251 do work for intervals.  As a convenience, applying @code{floor} to a
16252 modulo form floors the value part of the form.  Applied to a vector,
16253 these functions operate on all elements of the vector one by one.
16254 Applied to a date form, they operate on the internal numerical
16255 representation of dates, converting a date/time form into a pure date.
16257 @c @starindex
16258 @tindex rounde
16259 @c @starindex
16260 @tindex roundu
16261 @c @starindex
16262 @tindex frounde
16263 @c @starindex
16264 @tindex froundu
16265 There are two more rounding functions which can only be entered in
16266 algebraic notation.  The @code{roundu} function is like @code{round}
16267 except that it rounds up, toward plus infinity, when the fractional
16268 part is .5.  This distinction matters only for negative arguments.
16269 Also, @code{rounde} rounds to an even number in the case of a tie,
16270 rounding up or down as necessary.  For example, @samp{rounde(3.5)} and
16271 @samp{rounde(4.5)} both return 4, but @samp{rounde(5.5)} returns 6.
16272 The advantage of round-to-even is that the net error due to rounding
16273 after a long calculation tends to cancel out to zero.  An important
16274 subtle point here is that the number being fed to @code{rounde} will
16275 already have been rounded to the current precision before @code{rounde}
16276 begins.  For example, @samp{rounde(2.500001)} with a current precision
16277 of 6 will incorrectly, or at least surprisingly, yield 2 because the
16278 argument will first have been rounded down to @cite{2.5} (which
16279 @code{rounde} sees as an exact tie between 2 and 3).
16281 Each of these functions, when written in algebraic formulas, allows
16282 a second argument which specifies the number of digits after the
16283 decimal point to keep.  For example, @samp{round(123.4567, 2)} will
16284 produce the answer 123.46, and @samp{round(123.4567, -1)} will
16285 produce 120 (i.e., the cutoff is one digit to the @emph{left} of
16286 the decimal point).  A second argument of zero is equivalent to
16287 no second argument at all.
16289 @cindex Fractional part of a number
16290 To compute the fractional part of a number (i.e., the amount which, when
16291 added to `@t{floor(}@i{N}@t{)}', will produce @cite{N}) just take @cite{N}
16292 modulo 1 using the @code{%} command.@refill
16294 Note also the @kbd{\} (integer quotient), @kbd{f I} (integer logarithm),
16295 and @kbd{f Q} (integer square root) commands, which are analogous to
16296 @kbd{/}, @kbd{B}, and @kbd{Q}, respectively, except that they take integer
16297 arguments and return the result rounded down to an integer.
16299 @node Complex Number Functions, Conversions, Integer Truncation, Arithmetic
16300 @section Complex Number Functions
16302 @noindent
16303 @kindex J
16304 @pindex calc-conj
16305 @tindex conj
16306 The @kbd{J} (@code{calc-conj}) [@code{conj}] command computes the
16307 complex conjugate of a number.  For complex number @cite{a+bi}, the
16308 complex conjugate is @cite{a-bi}.  If the argument is a real number,
16309 this command leaves it the same.  If the argument is a vector or matrix,
16310 this command replaces each element by its complex conjugate.
16312 @kindex G
16313 @pindex calc-argument
16314 @tindex arg
16315 The @kbd{G} (@code{calc-argument}) [@code{arg}] command computes the
16316 ``argument'' or polar angle of a complex number.  For a number in polar
16317 notation, this is simply the second component of the pair
16318 `@t{(}@i{r}@t{;}@c{$\theta$}
16319 @i{theta}@t{)}'.
16320 The result is expressed according to the current angular mode and will
16321 be in the range @i{-180} degrees (exclusive) to @i{+180} degrees
16322 (inclusive), or the equivalent range in radians.@refill
16324 @pindex calc-imaginary
16325 The @code{calc-imaginary} command multiplies the number on the
16326 top of the stack by the imaginary number @cite{i = (0,1)}.  This
16327 command is not normally bound to a key in Calc, but it is available
16328 on the @key{IMAG} button in Keypad Mode.
16330 @kindex f r
16331 @pindex calc-re
16332 @tindex re
16333 The @kbd{f r} (@code{calc-re}) [@code{re}] command replaces a complex number
16334 by its real part.  This command has no effect on real numbers.  (As an
16335 added convenience, @code{re} applied to a modulo form extracts
16336 the value part.)@refill
16338 @kindex f i
16339 @pindex calc-im
16340 @tindex im
16341 The @kbd{f i} (@code{calc-im}) [@code{im}] command replaces a complex number
16342 by its imaginary part; real numbers are converted to zero.  With a vector
16343 or matrix argument, these functions operate element-wise.@refill
16345 @c @mindex v p
16346 @kindex v p (complex)
16347 @pindex calc-pack
16348 The @kbd{v p} (@code{calc-pack}) command can pack the top two numbers on
16349 the the stack into a composite object such as a complex number.  With
16350 a prefix argument of @i{-1}, it produces a rectangular complex number;
16351 with an argument of @i{-2}, it produces a polar complex number.
16352 (Also, @pxref{Building Vectors}.)
16354 @c @mindex v u
16355 @kindex v u (complex)
16356 @pindex calc-unpack
16357 The @kbd{v u} (@code{calc-unpack}) command takes the complex number
16358 (or other composite object) on the top of the stack and unpacks it
16359 into its separate components.
16361 @node Conversions, Date Arithmetic, Complex Number Functions, Arithmetic
16362 @section Conversions
16364 @noindent
16365 The commands described in this section convert numbers from one form
16366 to another; they are two-key sequences beginning with the letter @kbd{c}.
16368 @kindex c f
16369 @pindex calc-float
16370 @tindex pfloat
16371 The @kbd{c f} (@code{calc-float}) [@code{pfloat}] command converts the
16372 number on the top of the stack to floating-point form.  For example,
16373 @cite{23} is converted to @cite{23.0}, @cite{3:2} is converted to
16374 @cite{1.5}, and @cite{2.3} is left the same.  If the value is a composite
16375 object such as a complex number or vector, each of the components is
16376 converted to floating-point.  If the value is a formula, all numbers
16377 in the formula are converted to floating-point.  Note that depending
16378 on the current floating-point precision, conversion to floating-point
16379 format may lose information.@refill
16381 As a special exception, integers which appear as powers or subscripts
16382 are not floated by @kbd{c f}.  If you really want to float a power,
16383 you can use a @kbd{j s} command to select the power followed by @kbd{c f}.
16384 Because @kbd{c f} cannot examine the formula outside of the selection,
16385 it does not notice that the thing being floated is a power.
16386 @xref{Selecting Subformulas}.
16388 The normal @kbd{c f} command is ``pervasive'' in the sense that it
16389 applies to all numbers throughout the formula.  The @code{pfloat}
16390 algebraic function never stays around in a formula; @samp{pfloat(a + 1)}
16391 changes to @samp{a + 1.0} as soon as it is evaluated.
16393 @kindex H c f
16394 @tindex float
16395 With the Hyperbolic flag, @kbd{H c f} [@code{float}] operates
16396 only on the number or vector of numbers at the top level of its
16397 argument.  Thus, @samp{float(1)} is 1.0, but @samp{float(a + 1)}
16398 is left unevaluated because its argument is not a number.
16400 You should use @kbd{H c f} if you wish to guarantee that the final
16401 value, once all the variables have been assigned, is a float; you
16402 would use @kbd{c f} if you wish to do the conversion on the numbers
16403 that appear right now.
16405 @kindex c F
16406 @pindex calc-fraction
16407 @tindex pfrac
16408 The @kbd{c F} (@code{calc-fraction}) [@code{pfrac}] command converts a
16409 floating-point number into a fractional approximation.  By default, it
16410 produces a fraction whose decimal representation is the same as the
16411 input number, to within the current precision.  You can also give a
16412 numeric prefix argument to specify a tolerance, either directly, or,
16413 if the prefix argument is zero, by using the number on top of the stack
16414 as the tolerance.  If the tolerance is a positive integer, the fraction
16415 is correct to within that many significant figures.  If the tolerance is
16416 a non-positive integer, it specifies how many digits fewer than the current
16417 precision to use.  If the tolerance is a floating-point number, the
16418 fraction is correct to within that absolute amount.
16420 @kindex H c F
16421 @tindex frac
16422 The @code{pfrac} function is pervasive, like @code{pfloat}.
16423 There is also a non-pervasive version, @kbd{H c F} [@code{frac}],
16424 which is analogous to @kbd{H c f} discussed above.
16426 @kindex c d
16427 @pindex calc-to-degrees
16428 @tindex deg
16429 The @kbd{c d} (@code{calc-to-degrees}) [@code{deg}] command converts a
16430 number into degrees form.  The value on the top of the stack may be an
16431 HMS form (interpreted as degrees-minutes-seconds), or a real number which
16432 will be interpreted in radians regardless of the current angular mode.@refill
16434 @kindex c r
16435 @pindex calc-to-radians
16436 @tindex rad
16437 The @kbd{c r} (@code{calc-to-radians}) [@code{rad}] command converts an
16438 HMS form or angle in degrees into an angle in radians.
16440 @kindex c h
16441 @pindex calc-to-hms
16442 @tindex hms
16443 The @kbd{c h} (@code{calc-to-hms}) [@code{hms}] command converts a real
16444 number, interpreted according to the current angular mode, to an HMS
16445 form describing the same angle.  In algebraic notation, the @code{hms}
16446 function also accepts three arguments: @samp{hms(@var{h}, @var{m}, @var{s})}.
16447 (The three-argument version is independent of the current angular mode.)
16449 @pindex calc-from-hms
16450 The @code{calc-from-hms} command converts the HMS form on the top of the
16451 stack into a real number according to the current angular mode.
16453 @kindex c p
16454 @kindex I c p
16455 @pindex calc-polar
16456 @tindex polar
16457 @tindex rect
16458 The @kbd{c p} (@code{calc-polar}) command converts the complex number on
16459 the top of the stack from polar to rectangular form, or from rectangular
16460 to polar form, whichever is appropriate.  Real numbers are left the same.
16461 This command is equivalent to the @code{rect} or @code{polar}
16462 functions in algebraic formulas, depending on the direction of
16463 conversion.  (It uses @code{polar}, except that if the argument is
16464 already a polar complex number, it uses @code{rect} instead.  The
16465 @kbd{I c p} command always uses @code{rect}.)@refill
16467 @kindex c c
16468 @pindex calc-clean
16469 @tindex pclean
16470 The @kbd{c c} (@code{calc-clean}) [@code{pclean}] command ``cleans'' the
16471 number on the top of the stack.  Floating point numbers are re-rounded
16472 according to the current precision.  Polar numbers whose angular
16473 components have strayed from the @i{-180} to @i{+180} degree range
16474 are normalized.  (Note that results will be undesirable if the current
16475 angular mode is different from the one under which the number was
16476 produced!)  Integers and fractions are generally unaffected by this
16477 operation.  Vectors and formulas are cleaned by cleaning each component
16478 number (i.e., pervasively).@refill
16480 If the simplification mode is set below the default level, it is raised
16481 to the default level for the purposes of this command.  Thus, @kbd{c c}
16482 applies the default simplifications even if their automatic application
16483 is disabled.  @xref{Simplification Modes}.
16485 @cindex Roundoff errors, correcting
16486 A numeric prefix argument to @kbd{c c} sets the floating-point precision
16487 to that value for the duration of the command.  A positive prefix (of at
16488 least 3) sets the precision to the specified value; a negative or zero
16489 prefix decreases the precision by the specified amount.
16491 @kindex c 0-9
16492 @pindex calc-clean-num
16493 The keystroke sequences @kbd{c 0} through @kbd{c 9} are equivalent
16494 to @kbd{c c} with the corresponding negative prefix argument.  If roundoff
16495 errors have changed 2.0 into 1.999999, typing @kbd{c 1} to clip off one
16496 decimal place often conveniently does the trick.
16498 The @kbd{c c} command with a numeric prefix argument, and the @kbd{c 0}
16499 through @kbd{c 9} commands, also ``clip'' very small floating-point
16500 numbers to zero.  If the exponent is less than or equal to the negative
16501 of the specified precision, the number is changed to 0.0.  For example,
16502 if the current precision is 12, then @kbd{c 2} changes the vector
16503 @samp{[1e-8, 1e-9, 1e-10, 1e-11]} to @samp{[1e-8, 1e-9, 0, 0]}.
16504 Numbers this small generally arise from roundoff noise.
16506 If the numbers you are using really are legitimately this small,
16507 you should avoid using the @kbd{c 0} through @kbd{c 9} commands.
16508 (The plain @kbd{c c} command rounds to the current precision but
16509 does not clip small numbers.)
16511 One more property of @kbd{c 0} through @kbd{c 9}, and of @kbd{c c} with
16512 a prefix argument, is that integer-valued floats are converted to
16513 plain integers, so that @kbd{c 1} on @samp{[1., 1.5, 2., 2.5, 3.]}
16514 produces @samp{[1, 1.5, 2, 2.5, 3]}.  This is not done for huge
16515 numbers (@samp{1e100} is technically an integer-valued float, but
16516 you wouldn't want it automatically converted to a 100-digit integer).
16518 @kindex H c 0-9
16519 @kindex H c c
16520 @tindex clean
16521 With the Hyperbolic flag, @kbd{H c c} and @kbd{H c 0} through @kbd{H c 9}
16522 operate non-pervasively [@code{clean}].
16524 @node Date Arithmetic, Financial Functions, Conversions, Arithmetic
16525 @section Date Arithmetic
16527 @noindent
16528 @cindex Date arithmetic, additional functions
16529 The commands described in this section perform various conversions
16530 and calculations involving date forms (@pxref{Date Forms}).  They
16531 use the @kbd{t} (for time/date) prefix key followed by shifted
16532 letters.
16534 The simplest date arithmetic is done using the regular @kbd{+} and @kbd{-}
16535 commands.  In particular, adding a number to a date form advances the
16536 date form by a certain number of days; adding an HMS form to a date
16537 form advances the date by a certain amount of time; and subtracting two
16538 date forms produces a difference measured in days.  The commands
16539 described here provide additional, more specialized operations on dates.
16541 Many of these commands accept a numeric prefix argument; if you give
16542 plain @kbd{C-u} as the prefix, these commands will instead take the
16543 additional argument from the top of the stack.
16545 @menu
16546 * Date Conversions::
16547 * Date Functions::
16548 * Time Zones::
16549 * Business Days::
16550 @end menu
16552 @node Date Conversions, Date Functions, Date Arithmetic, Date Arithmetic
16553 @subsection Date Conversions
16555 @noindent
16556 @kindex t D
16557 @pindex calc-date
16558 @tindex date
16559 The @kbd{t D} (@code{calc-date}) [@code{date}] command converts a
16560 date form into a number, measured in days since Jan 1, 1 AD.  The
16561 result will be an integer if @var{date} is a pure date form, or a
16562 fraction or float if @var{date} is a date/time form.  Or, if its
16563 argument is a number, it converts this number into a date form.
16565 With a numeric prefix argument, @kbd{t D} takes that many objects
16566 (up to six) from the top of the stack and interprets them in one
16567 of the following ways:
16569 The @samp{date(@var{year}, @var{month}, @var{day})} function
16570 builds a pure date form out of the specified year, month, and
16571 day, which must all be integers.  @var{Year} is a year number,
16572 such as 1991 (@emph{not} the same as 91!).  @var{Month} must be
16573 an integer in the range 1 to 12; @var{day} must be in the range
16574 1 to 31.  If the specified month has fewer than 31 days and
16575 @var{day} is too large, the equivalent day in the following
16576 month will be used.
16578 The @samp{date(@var{month}, @var{day})} function builds a
16579 pure date form using the current year, as determined by the
16580 real-time clock.
16582 The @samp{date(@var{year}, @var{month}, @var{day}, @var{hms})}
16583 function builds a date/time form using an @var{hms} form.
16585 The @samp{date(@var{year}, @var{month}, @var{day}, @var{hour},
16586 @var{minute}, @var{second})} function builds a date/time form.
16587 @var{hour} should be an integer in the range 0 to 23;
16588 @var{minute} should be an integer in the range 0 to 59;
16589 @var{second} should be any real number in the range @samp{[0 .. 60)}.
16590 The last two arguments default to zero if omitted.
16592 @kindex t J
16593 @pindex calc-julian
16594 @tindex julian
16595 @cindex Julian day counts, conversions
16596 The @kbd{t J} (@code{calc-julian}) [@code{julian}] command converts
16597 a date form into a Julian day count, which is the number of days
16598 since noon on Jan 1, 4713 BC.  A pure date is converted to an integer
16599 Julian count representing noon of that day.  A date/time form is
16600 converted to an exact floating-point Julian count, adjusted to
16601 interpret the date form in the current time zone but the Julian
16602 day count in Greenwich Mean Time.  A numeric prefix argument allows
16603 you to specify the time zone; @pxref{Time Zones}.  Use a prefix of
16604 zero to suppress the time zone adjustment.  Note that pure date forms
16605 are never time-zone adjusted.
16607 This command can also do the opposite conversion, from a Julian day
16608 count (either an integer day, or a floating-point day and time in
16609 the GMT zone), into a pure date form or a date/time form in the
16610 current or specified time zone.
16612 @kindex t U
16613 @pindex calc-unix-time
16614 @tindex unixtime
16615 @cindex Unix time format, conversions
16616 The @kbd{t U} (@code{calc-unix-time}) [@code{unixtime}] command
16617 converts a date form into a Unix time value, which is the number of
16618 seconds since midnight on Jan 1, 1970, or vice-versa.  The numeric result
16619 will be an integer if the current precision is 12 or less; for higher
16620 precisions, the result may be a float with (@var{precision}@i{-}12)
16621 digits after the decimal.  Just as for @kbd{t J}, the numeric time
16622 is interpreted in the GMT time zone and the date form is interpreted
16623 in the current or specified zone.  Some systems use Unix-like
16624 numbering but with the local time zone; give a prefix of zero to
16625 suppress the adjustment if so.
16627 @kindex t C
16628 @pindex calc-convert-time-zones
16629 @tindex tzconv
16630 @cindex Time Zones, converting between
16631 The @kbd{t C} (@code{calc-convert-time-zones}) [@code{tzconv}]
16632 command converts a date form from one time zone to another.  You
16633 are prompted for each time zone name in turn; you can answer with
16634 any suitable Calc time zone expression (@pxref{Time Zones}).
16635 If you answer either prompt with a blank line, the local time
16636 zone is used for that prompt.  You can also answer the first
16637 prompt with @kbd{$} to take the two time zone names from the
16638 stack (and the date to be converted from the third stack level).
16640 @node Date Functions, Business Days, Date Conversions, Date Arithmetic
16641 @subsection Date Functions
16643 @noindent
16644 @kindex t N
16645 @pindex calc-now
16646 @tindex now
16647 The @kbd{t N} (@code{calc-now}) [@code{now}] command pushes the
16648 current date and time on the stack as a date form.  The time is
16649 reported in terms of the specified time zone; with no numeric prefix
16650 argument, @kbd{t N} reports for the current time zone.
16652 @kindex t P
16653 @pindex calc-date-part
16654 The @kbd{t P} (@code{calc-date-part}) command extracts one part
16655 of a date form.  The prefix argument specifies the part; with no
16656 argument, this command prompts for a part code from 1 to 9.
16657 The various part codes are described in the following paragraphs.
16659 @tindex year
16660 The @kbd{M-1 t P} [@code{year}] function extracts the year number
16661 from a date form as an integer, e.g., 1991.  This and the
16662 following functions will also accept a real number for an
16663 argument, which is interpreted as a standard Calc day number.
16664 Note that this function will never return zero, since the year
16665 1 BC immediately precedes the year 1 AD.
16667 @tindex month
16668 The @kbd{M-2 t P} [@code{month}] function extracts the month number
16669 from a date form as an integer in the range 1 to 12.
16671 @tindex day
16672 The @kbd{M-3 t P} [@code{day}] function extracts the day number
16673 from a date form as an integer in the range 1 to 31.
16675 @tindex hour
16676 The @kbd{M-4 t P} [@code{hour}] function extracts the hour from
16677 a date form as an integer in the range 0 (midnight) to 23.  Note
16678 that 24-hour time is always used.  This returns zero for a pure
16679 date form.  This function (and the following two) also accept
16680 HMS forms as input.
16682 @tindex minute
16683 The @kbd{M-5 t P} [@code{minute}] function extracts the minute
16684 from a date form as an integer in the range 0 to 59.
16686 @tindex second
16687 The @kbd{M-6 t P} [@code{second}] function extracts the second
16688 from a date form.  If the current precision is 12 or less,
16689 the result is an integer in the range 0 to 59.  For higher
16690 precisions, the result may instead be a floating-point number.
16692 @tindex weekday
16693 The @kbd{M-7 t P} [@code{weekday}] function extracts the weekday
16694 number from a date form as an integer in the range 0 (Sunday)
16695 to 6 (Saturday).
16697 @tindex yearday
16698 The @kbd{M-8 t P} [@code{yearday}] function extracts the day-of-year
16699 number from a date form as an integer in the range 1 (January 1)
16700 to 366 (December 31 of a leap year).
16702 @tindex time
16703 The @kbd{M-9 t P} [@code{time}] function extracts the time portion
16704 of a date form as an HMS form.  This returns @samp{0@@ 0' 0"}
16705 for a pure date form.
16707 @kindex t M
16708 @pindex calc-new-month
16709 @tindex newmonth
16710 The @kbd{t M} (@code{calc-new-month}) [@code{newmonth}] command
16711 computes a new date form that represents the first day of the month
16712 specified by the input date.  The result is always a pure date
16713 form; only the year and month numbers of the input are retained.
16714 With a numeric prefix argument @var{n} in the range from 1 to 31,
16715 @kbd{t M} computes the @var{n}th day of the month.  (If @var{n}
16716 is greater than the actual number of days in the month, or if
16717 @var{n} is zero, the last day of the month is used.)
16719 @kindex t Y
16720 @pindex calc-new-year
16721 @tindex newyear
16722 The @kbd{t Y} (@code{calc-new-year}) [@code{newyear}] command
16723 computes a new pure date form that represents the first day of
16724 the year specified by the input.  The month, day, and time
16725 of the input date form are lost.  With a numeric prefix argument
16726 @var{n} in the range from 1 to 366, @kbd{t Y} computes the
16727 @var{n}th day of the year (366 is treated as 365 in non-leap
16728 years).  A prefix argument of 0 computes the last day of the
16729 year (December 31).  A negative prefix argument from @i{-1} to
16730 @i{-12} computes the first day of the @var{n}th month of the year.
16732 @kindex t W
16733 @pindex calc-new-week
16734 @tindex newweek
16735 The @kbd{t W} (@code{calc-new-week}) [@code{newweek}] command
16736 computes a new pure date form that represents the Sunday on or before
16737 the input date.  With a numeric prefix argument, it can be made to
16738 use any day of the week as the starting day; the argument must be in
16739 the range from 0 (Sunday) to 6 (Saturday).  This function always
16740 subtracts between 0 and 6 days from the input date.
16742 Here's an example use of @code{newweek}:  Find the date of the next
16743 Wednesday after a given date.  Using @kbd{M-3 t W} or @samp{newweek(d, 3)}
16744 will give you the @emph{preceding} Wednesday, so @samp{newweek(d+7, 3)}
16745 will give you the following Wednesday.  A further look at the definition
16746 of @code{newweek} shows that if the input date is itself a Wednesday,
16747 this formula will return the Wednesday one week in the future.  An
16748 exercise for the reader is to modify this formula to yield the same day
16749 if the input is already a Wednesday.  Another interesting exercise is
16750 to preserve the time-of-day portion of the input (@code{newweek} resets
16751 the time to midnight; hint:@: how can @code{newweek} be defined in terms
16752 of the @code{weekday} function?).
16754 @c @starindex
16755 @tindex pwday
16756 The @samp{pwday(@var{date})} function (not on any key) computes the
16757 day-of-month number of the Sunday on or before @var{date}.  With
16758 two arguments, @samp{pwday(@var{date}, @var{day})} computes the day
16759 number of the Sunday on or before day number @var{day} of the month
16760 specified by @var{date}.  The @var{day} must be in the range from
16761 7 to 31; if the day number is greater than the actual number of days
16762 in the month, the true number of days is used instead.  Thus
16763 @samp{pwday(@var{date}, 7)} finds the first Sunday of the month, and
16764 @samp{pwday(@var{date}, 31)} finds the last Sunday of the month.
16765 With a third @var{weekday} argument, @code{pwday} can be made to look
16766 for any day of the week instead of Sunday.
16768 @kindex t I
16769 @pindex calc-inc-month
16770 @tindex incmonth
16771 The @kbd{t I} (@code{calc-inc-month}) [@code{incmonth}] command
16772 increases a date form by one month, or by an arbitrary number of
16773 months specified by a numeric prefix argument.  The time portion,
16774 if any, of the date form stays the same.  The day also stays the
16775 same, except that if the new month has fewer days the day
16776 number may be reduced to lie in the valid range.  For example,
16777 @samp{incmonth(<Jan 31, 1991>)} produces @samp{<Feb 28, 1991>}.
16778 Because of this, @kbd{t I t I} and @kbd{M-2 t I} do not always give
16779 the same results (@samp{<Mar 28, 1991>} versus @samp{<Mar 31, 1991>}
16780 in this case).
16782 @c @starindex
16783 @tindex incyear
16784 The @samp{incyear(@var{date}, @var{step})} function increases
16785 a date form by the specified number of years, which may be
16786 any positive or negative integer.  Note that @samp{incyear(d, n)}
16787 is equivalent to @w{@samp{incmonth(d, 12*n)}}, but these do not have
16788 simple equivalents in terms of day arithmetic because
16789 months and years have varying lengths.  If the @var{step}
16790 argument is omitted, 1 year is assumed.  There is no keyboard
16791 command for this function; use @kbd{C-u 12 t I} instead.
16793 There is no @code{newday} function at all because @kbd{F} [@code{floor}]
16794 serves this purpose.  Similarly, instead of @code{incday} and
16795 @code{incweek} simply use @cite{d + n} or @cite{d + 7 n}.
16797 @xref{Basic Arithmetic}, for the @kbd{f ]} [@code{incr}] command
16798 which can adjust a date/time form by a certain number of seconds.
16800 @node Business Days, Time Zones, Date Functions, Date Arithmetic
16801 @subsection Business Days
16803 @noindent
16804 Often time is measured in ``business days'' or ``working days,''
16805 where weekends and holidays are skipped.  Calc's normal date
16806 arithmetic functions use calendar days, so that subtracting two
16807 consecutive Mondays will yield a difference of 7 days.  By contrast,
16808 subtracting two consecutive Mondays would yield 5 business days
16809 (assuming two-day weekends and the absence of holidays).
16811 @kindex t +
16812 @kindex t -
16813 @tindex badd
16814 @tindex bsub
16815 @pindex calc-business-days-plus
16816 @pindex calc-business-days-minus
16817 The @kbd{t +} (@code{calc-business-days-plus}) [@code{badd}]
16818 and @kbd{t -} (@code{calc-business-days-minus}) [@code{bsub}]
16819 commands perform arithmetic using business days.  For @kbd{t +},
16820 one argument must be a date form and the other must be a real
16821 number (positive or negative).  If the number is not an integer,
16822 then a certain amount of time is added as well as a number of
16823 days; for example, adding 0.5 business days to a time in Friday
16824 evening will produce a time in Monday morning.  It is also
16825 possible to add an HMS form; adding @samp{12@@ 0' 0"} also adds
16826 half a business day.  For @kbd{t -}, the arguments are either a
16827 date form and a number or HMS form, or two date forms, in which
16828 case the result is the number of business days between the two
16829 dates.
16831 @cindex @code{Holidays} variable
16832 @vindex Holidays
16833 By default, Calc considers any day that is not a Saturday or
16834 Sunday to be a business day.  You can define any number of
16835 additional holidays by editing the variable @code{Holidays}.
16836 (There is an @w{@kbd{s H}} convenience command for editing this
16837 variable.)  Initially, @code{Holidays} contains the vector
16838 @samp{[sat, sun]}.  Entries in the @code{Holidays} vector may
16839 be any of the following kinds of objects:
16841 @itemize @bullet
16842 @item
16843 Date forms (pure dates, not date/time forms).  These specify
16844 particular days which are to be treated as holidays.
16846 @item
16847 Intervals of date forms.  These specify a range of days, all of
16848 which are holidays (e.g., Christmas week).  @xref{Interval Forms}.
16850 @item
16851 Nested vectors of date forms.  Each date form in the vector is
16852 considered to be a holiday.
16854 @item
16855 Any Calc formula which evaluates to one of the above three things.
16856 If the formula involves the variable @cite{y}, it stands for a
16857 yearly repeating holiday; @cite{y} will take on various year
16858 numbers like 1992.  For example, @samp{date(y, 12, 25)} specifies
16859 Christmas day, and @samp{newweek(date(y, 11, 7), 4) + 21} specifies
16860 Thanksgiving (which is held on the fourth Thursday of November).
16861 If the formula involves the variable @cite{m}, that variable
16862 takes on month numbers from 1 to 12:  @samp{date(y, m, 15)} is
16863 a holiday that takes place on the 15th of every month.
16865 @item
16866 A weekday name, such as @code{sat} or @code{sun}.  This is really
16867 a variable whose name is a three-letter, lower-case day name.
16869 @item
16870 An interval of year numbers (integers).  This specifies the span of
16871 years over which this holiday list is to be considered valid.  Any
16872 business-day arithmetic that goes outside this range will result
16873 in an error message.  Use this if you are including an explicit
16874 list of holidays, rather than a formula to generate them, and you
16875 want to make sure you don't accidentally go beyond the last point
16876 where the holidays you entered are complete.  If there is no
16877 limiting interval in the @code{Holidays} vector, the default
16878 @samp{[1 .. 2737]} is used.  (This is the absolute range of years
16879 for which Calc's business-day algorithms will operate.)
16881 @item
16882 An interval of HMS forms.  This specifies the span of hours that
16883 are to be considered one business day.  For example, if this
16884 range is @samp{[9@@ 0' 0" .. 17@@ 0' 0"]} (i.e., 9am to 5pm), then
16885 the business day is only eight hours long, so that @kbd{1.5 t +}
16886 on @samp{<4:00pm Fri Dec 13, 1991>} will add one business day and
16887 four business hours to produce @samp{<12:00pm Tue Dec 17, 1991>}.
16888 Likewise, @kbd{t -} will now express differences in time as
16889 fractions of an eight-hour day.  Times before 9am will be treated
16890 as 9am by business date arithmetic, and times at or after 5pm will
16891 be treated as 4:59:59pm.  If there is no HMS interval in @code{Holidays},
16892 the full 24-hour day @samp{[0@ 0' 0" .. 24@ 0' 0"]} is assumed.
16893 (Regardless of the type of bounds you specify, the interval is
16894 treated as inclusive on the low end and exclusive on the high end,
16895 so that the work day goes from 9am up to, but not including, 5pm.)
16896 @end itemize
16898 If the @code{Holidays} vector is empty, then @kbd{t +} and
16899 @kbd{t -} will act just like @kbd{+} and @kbd{-} because there will
16900 then be no difference between business days and calendar days.
16902 Calc expands the intervals and formulas you give into a complete
16903 list of holidays for internal use.  This is done mainly to make
16904 sure it can detect multiple holidays.  (For example,
16905 @samp{<Jan 1, 1989>} is both New Year's Day and a Sunday, but
16906 Calc's algorithms take care to count it only once when figuring
16907 the number of holidays between two dates.)
16909 Since the complete list of holidays for all the years from 1 to
16910 2737 would be huge, Calc actually computes only the part of the
16911 list between the smallest and largest years that have been involved
16912 in business-day calculations so far.  Normally, you won't have to
16913 worry about this.  Keep in mind, however, that if you do one
16914 calculation for 1992, and another for 1792, even if both involve
16915 only a small range of years, Calc will still work out all the
16916 holidays that fall in that 200-year span.
16918 If you add a (positive) number of days to a date form that falls on a
16919 weekend or holiday, the date form is treated as if it were the most
16920 recent business day.  (Thus adding one business day to a Friday,
16921 Saturday, or Sunday will all yield the following Monday.)  If you
16922 subtract a number of days from a weekend or holiday, the date is
16923 effectively on the following business day.  (So subtracting one business
16924 day from Saturday, Sunday, or Monday yields the preceding Friday.)  The
16925 difference between two dates one or both of which fall on holidays
16926 equals the number of actual business days between them.  These
16927 conventions are consistent in the sense that, if you add @var{n}
16928 business days to any date, the difference between the result and the
16929 original date will come out to @var{n} business days.  (It can't be
16930 completely consistent though; a subtraction followed by an addition
16931 might come out a bit differently, since @kbd{t +} is incapable of
16932 producing a date that falls on a weekend or holiday.)
16934 @c @starindex
16935 @tindex holiday
16936 There is a @code{holiday} function, not on any keys, that takes
16937 any date form and returns 1 if that date falls on a weekend or
16938 holiday, as defined in @code{Holidays}, or 0 if the date is a
16939 business day.
16941 @node Time Zones, , Business Days, Date Arithmetic
16942 @subsection Time Zones
16944 @noindent
16945 @cindex Time zones
16946 @cindex Daylight savings time
16947 Time zones and daylight savings time are a complicated business.
16948 The conversions to and from Julian and Unix-style dates automatically
16949 compute the correct time zone and daylight savings adjustment to use,
16950 provided they can figure out this information.  This section describes
16951 Calc's time zone adjustment algorithm in detail, in case you want to
16952 do conversions in different time zones or in case Calc's algorithms
16953 can't determine the right correction to use.
16955 Adjustments for time zones and daylight savings time are done by
16956 @kbd{t U}, @kbd{t J}, @kbd{t N}, and @kbd{t C}, but not by any other
16957 commands.  In particular, @samp{<may 1 1991> - <apr 1 1991>} evaluates
16958 to exactly 30 days even though there is a daylight-savings
16959 transition in between.  This is also true for Julian pure dates:
16960 @samp{julian(<may 1 1991>) - julian(<apr 1 1991>)}.  But Julian
16961 and Unix date/times will adjust for daylight savings time:
16962 @samp{julian(<12am may 1 1991>) - julian(<12am apr 1 1991>)}
16963 evaluates to @samp{29.95834} (that's 29 days and 23 hours)
16964 because one hour was lost when daylight savings commenced on
16965 April 7, 1991.
16967 In brief, the idiom @samp{julian(@var{date1}) - julian(@var{date2})}
16968 computes the actual number of 24-hour periods between two dates, whereas
16969 @samp{@var{date1} - @var{date2}} computes the number of calendar
16970 days between two dates without taking daylight savings into account.
16972 @pindex calc-time-zone
16973 @c @starindex
16974 @tindex tzone
16975 The @code{calc-time-zone} [@code{tzone}] command converts the time
16976 zone specified by its numeric prefix argument into a number of
16977 seconds difference from Greenwich mean time (GMT).  If the argument
16978 is a number, the result is simply that value multiplied by 3600.
16979 Typical arguments for North America are 5 (Eastern) or 8 (Pacific).  If
16980 Daylight Savings time is in effect, one hour should be subtracted from
16981 the normal difference.
16983 If you give a prefix of plain @kbd{C-u}, @code{calc-time-zone} (like other
16984 date arithmetic commands that include a time zone argument) takes the
16985 zone argument from the top of the stack.  (In the case of @kbd{t J}
16986 and @kbd{t U}, the normal argument is then taken from the second-to-top
16987 stack position.)  This allows you to give a non-integer time zone
16988 adjustment.  The time-zone argument can also be an HMS form, or
16989 it can be a variable which is a time zone name in upper- or lower-case.
16990 For example @samp{tzone(PST) = tzone(8)} and @samp{tzone(pdt) = tzone(7)}
16991 (for Pacific standard and daylight savings times, respectively).
16993 North American and European time zone names are defined as follows;
16994 note that for each time zone there is one name for standard time,
16995 another for daylight savings time, and a third for ``generalized'' time
16996 in which the daylight savings adjustment is computed from context.
16998 @group
16999 @smallexample
17000 YST  PST  MST  CST  EST  AST    NST    GMT   WET     MET    MEZ
17001  9    8    7    6    5    4     3.5     0     -1      -2     -2
17003 YDT  PDT  MDT  CDT  EDT  ADT    NDT    BST  WETDST  METDST  MESZ
17004  8    7    6    5    4    3     2.5     -1    -2      -3     -3
17006 YGT  PGT  MGT  CGT  EGT  AGT    NGT    BGT   WEGT    MEGT   MEGZ
17007 9/8  8/7  7/6  6/5  5/4  4/3  3.5/2.5  0/-1 -1/-2   -2/-3  -2/-3
17008 @end smallexample
17009 @end group
17011 @vindex math-tzone-names
17012 To define time zone names that do not appear in the above table,
17013 you must modify the Lisp variable @code{math-tzone-names}.  This
17014 is a list of lists describing the different time zone names; its
17015 structure is best explained by an example.  The three entries for
17016 Pacific Time look like this:
17018 @group
17019 @smallexample
17020 ( ( "PST" 8 0 )    ; Name as an upper-case string, then standard
17021   ( "PDT" 8 -1 )   ; adjustment, then daylight savings adjustment.
17022   ( "PGT" 8 "PST" "PDT" ) )   ; Generalized time zone.
17023 @end smallexample
17024 @end group
17026 @cindex @code{TimeZone} variable
17027 @vindex TimeZone
17028 With no arguments, @code{calc-time-zone} or @samp{tzone()} obtains an
17029 argument from the Calc variable @code{TimeZone} if a value has been
17030 stored for that variable.  If not, Calc runs the Unix @samp{date}
17031 command and looks for one of the above time zone names in the output;
17032 if this does not succeed, @samp{tzone()} leaves itself unevaluated.
17033 The time zone name in the @samp{date} output may be followed by a signed
17034 adjustment, e.g., @samp{GMT+5} or @samp{GMT+0500} which specifies a
17035 number of hours and minutes to be added to the base time zone.
17036 Calc stores the time zone it finds into @code{TimeZone} to speed
17037 later calls to @samp{tzone()}.
17039 The special time zone name @code{local} is equivalent to no argument,
17040 i.e., it uses the local time zone as obtained from the @code{date}
17041 command.
17043 If the time zone name found is one of the standard or daylight
17044 savings zone names from the above table, and Calc's internal
17045 daylight savings algorithm says that time and zone are consistent
17046 (e.g., @code{PDT} accompanies a date that Calc's algorithm would also
17047 consider to be daylight savings, or @code{PST} accompanies a date
17048 that Calc would consider to be standard time), then Calc substitutes
17049 the corresponding generalized time zone (like @code{PGT}).
17051 If your system does not have a suitable @samp{date} command, you
17052 may wish to put a @samp{(setq var-TimeZone ...)} in your Emacs
17053 initialization file to set the time zone.  The easiest way to do
17054 this is to edit the @code{TimeZone} variable using Calc's @kbd{s T}
17055 command, then use the @kbd{s p} (@code{calc-permanent-variable})
17056 command to save the value of @code{TimeZone} permanently.
17058 The @kbd{t J} and @code{t U} commands with no numeric prefix
17059 arguments do the same thing as @samp{tzone()}.  If the current
17060 time zone is a generalized time zone, e.g., @code{EGT}, Calc
17061 examines the date being converted to tell whether to use standard
17062 or daylight savings time.  But if the current time zone is explicit,
17063 e.g., @code{EST} or @code{EDT}, then that adjustment is used exactly
17064 and Calc's daylight savings algorithm is not consulted.
17066 Some places don't follow the usual rules for daylight savings time.
17067 The state of Arizona, for example, does not observe daylight savings
17068 time.  If you run Calc during the winter season in Arizona, the
17069 Unix @code{date} command will report @code{MST} time zone, which
17070 Calc will change to @code{MGT}.  If you then convert a time that
17071 lies in the summer months, Calc will apply an incorrect daylight
17072 savings time adjustment.  To avoid this, set your @code{TimeZone}
17073 variable explicitly to @code{MST} to force the use of standard,
17074 non-daylight-savings time.
17076 @vindex math-daylight-savings-hook
17077 @findex math-std-daylight-savings
17078 By default Calc always considers daylight savings time to begin at
17079 2 a.m.@: on the first Sunday of April, and to end at 2 a.m.@: on the
17080 last Sunday of October.  This is the rule that has been in effect
17081 in North America since 1987.  If you are in a country that uses
17082 different rules for computing daylight savings time, you have two
17083 choices:  Write your own daylight savings hook, or control time
17084 zones explicitly by setting the @code{TimeZone} variable and/or
17085 always giving a time-zone argument for the conversion functions.
17087 The Lisp variable @code{math-daylight-savings-hook} holds the
17088 name of a function that is used to compute the daylight savings
17089 adjustment for a given date.  The default is
17090 @code{math-std-daylight-savings}, which computes an adjustment
17091 (either 0 or @i{-1}) using the North American rules given above.
17093 The daylight savings hook function is called with four arguments:
17094 The date, as a floating-point number in standard Calc format;
17095 a six-element list of the date decomposed into year, month, day,
17096 hour, minute, and second, respectively; a string which contains
17097 the generalized time zone name in upper-case, e.g., @code{"WEGT"};
17098 and a special adjustment to be applied to the hour value when
17099 converting into a generalized time zone (see below).
17101 @findex math-prev-weekday-in-month
17102 The Lisp function @code{math-prev-weekday-in-month} is useful for
17103 daylight savings computations.  This is an internal version of
17104 the user-level @code{pwday} function described in the previous
17105 section. It takes four arguments:  The floating-point date value,
17106 the corresponding six-element date list, the day-of-month number,
17107 and the weekday number (0-6).
17109 The default daylight savings hook ignores the time zone name, but a
17110 more sophisticated hook could use different algorithms for different
17111 time zones.  It would also be possible to use different algorithms
17112 depending on the year number, but the default hook always uses the
17113 algorithm for 1987 and later.  Here is a listing of the default
17114 daylight savings hook:
17116 @smallexample
17117 (defun math-std-daylight-savings (date dt zone bump)
17118   (cond ((< (nth 1 dt) 4) 0)
17119         ((= (nth 1 dt) 4)
17120          (let ((sunday (math-prev-weekday-in-month date dt 7 0)))
17121            (cond ((< (nth 2 dt) sunday) 0)
17122                  ((= (nth 2 dt) sunday)
17123                   (if (>= (nth 3 dt) (+ 3 bump)) -1 0))
17124                  (t -1))))
17125         ((< (nth 1 dt) 10) -1)
17126         ((= (nth 1 dt) 10)
17127          (let ((sunday (math-prev-weekday-in-month date dt 31 0)))
17128            (cond ((< (nth 2 dt) sunday) -1)
17129                  ((= (nth 2 dt) sunday)
17130                   (if (>= (nth 3 dt) (+ 2 bump)) 0 -1))
17131                  (t 0))))
17132         (t 0))
17134 @end smallexample
17136 @noindent
17137 The @code{bump} parameter is equal to zero when Calc is converting
17138 from a date form in a generalized time zone into a GMT date value.
17139 It is @i{-1} when Calc is converting in the other direction.  The
17140 adjustments shown above ensure that the conversion behaves correctly
17141 and reasonably around the 2 a.m.@: transition in each direction.
17143 There is a ``missing'' hour between 2 a.m.@: and 3 a.m.@: at the
17144 beginning of daylight savings time; converting a date/time form that
17145 falls in this hour results in a time value for the following hour,
17146 from 3 a.m.@: to 4 a.m.  At the end of daylight savings time, the
17147 hour from 1 a.m.@: to 2 a.m.@: repeats itself; converting a date/time
17148 form that falls in in this hour results in a time value for the first
17149 manifestion of that time (@emph{not} the one that occurs one hour later).
17151 If @code{math-daylight-savings-hook} is @code{nil}, then the
17152 daylight savings adjustment is always taken to be zero.
17154 In algebraic formulas, @samp{tzone(@var{zone}, @var{date})}
17155 computes the time zone adjustment for a given zone name at a
17156 given date.  The @var{date} is ignored unless @var{zone} is a
17157 generalized time zone.  If @var{date} is a date form, the
17158 daylight savings computation is applied to it as it appears.
17159 If @var{date} is a numeric date value, it is adjusted for the
17160 daylight-savings version of @var{zone} before being given to
17161 the daylight savings hook.  This odd-sounding rule ensures
17162 that the daylight-savings computation is always done in
17163 local time, not in the GMT time that a numeric @var{date}
17164 is typically represented in.
17166 @c @starindex
17167 @tindex dsadj
17168 The @samp{dsadj(@var{date}, @var{zone})} function computes the
17169 daylight savings adjustment that is appropriate for @var{date} in
17170 time zone @var{zone}.  If @var{zone} is explicitly in or not in
17171 daylight savings time (e.g., @code{PDT} or @code{PST}) the
17172 @var{date} is ignored.  If @var{zone} is a generalized time zone,
17173 the algorithms described above are used.  If @var{zone} is omitted,
17174 the computation is done for the current time zone.
17176 @xref{Reporting Bugs}, for the address of Calc's author, if you
17177 should wish to contribute your improved versions of
17178 @code{math-tzone-names} and @code{math-daylight-savings-hook}
17179 to the Calc distribution.
17181 @node Financial Functions, Binary Functions, Date Arithmetic, Arithmetic
17182 @section Financial Functions
17184 @noindent
17185 Calc's financial or business functions use the @kbd{b} prefix
17186 key followed by a shifted letter.  (The @kbd{b} prefix followed by
17187 a lower-case letter is used for operations on binary numbers.)
17189 Note that the rate and the number of intervals given to these
17190 functions must be on the same time scale, e.g., both months or
17191 both years.  Mixing an annual interest rate with a time expressed
17192 in months will give you very wrong answers!
17194 It is wise to compute these functions to a higher precision than
17195 you really need, just to make sure your answer is correct to the
17196 last penny; also, you may wish to check the definitions at the end
17197 of this section to make sure the functions have the meaning you expect.
17199 @menu
17200 * Percentages::
17201 * Future Value::
17202 * Present Value::
17203 * Related Financial Functions::
17204 * Depreciation Functions::
17205 * Definitions of Financial Functions::
17206 @end menu
17208 @node Percentages, Future Value, Financial Functions, Financial Functions
17209 @subsection Percentages
17211 @kindex M-%
17212 @pindex calc-percent
17213 @tindex %
17214 @tindex percent
17215 The @kbd{M-%} (@code{calc-percent}) command takes a percentage value,
17216 say 5.4, and converts it to an equivalent actual number.  For example,
17217 @kbd{5.4 M-%} enters 0.054 on the stack.  (That's the @key{META} or
17218 @key{ESC} key combined with @kbd{%}.)
17220 Actually, @kbd{M-%} creates a formula of the form @samp{5.4%}.
17221 You can enter @samp{5.4%} yourself during algebraic entry.  The
17222 @samp{%} operator simply means, ``the preceding value divided by
17223 100.''  The @samp{%} operator has very high precedence, so that
17224 @samp{1+8%} is interpreted as @samp{1+(8%)}, not as @samp{(1+8)%}.
17225 (The @samp{%} operator is just a postfix notation for the
17226 @code{percent} function, just like @samp{20!} is the notation for
17227 @samp{fact(20)}, or twenty-factorial.)
17229 The formula @samp{5.4%} would normally evaluate immediately to
17230 0.054, but the @kbd{M-%} command suppresses evaluation as it puts
17231 the formula onto the stack.  However, the next Calc command that
17232 uses the formula @samp{5.4%} will evaluate it as its first step.
17233 The net effect is that you get to look at @samp{5.4%} on the stack,
17234 but Calc commands see it as @samp{0.054}, which is what they expect.
17236 In particular, @samp{5.4%} and @samp{0.054} are suitable values
17237 for the @var{rate} arguments of the various financial functions,
17238 but the number @samp{5.4} is probably @emph{not} suitable---it
17239 represents a rate of 540 percent!
17241 The key sequence @kbd{M-% *} effectively means ``percent-of.''
17242 For example, @kbd{68 RET 25 M-% *} computes 17, which is 25% of
17243 68 (and also 68% of 25, which comes out to the same thing).
17245 @kindex c %
17246 @pindex calc-convert-percent
17247 The @kbd{c %} (@code{calc-convert-percent}) command converts the
17248 value on the top of the stack from numeric to percentage form.
17249 For example, if 0.08 is on the stack, @kbd{c %} converts it to
17250 @samp{8%}.  The quantity is the same, it's just represented
17251 differently.  (Contrast this with @kbd{M-%}, which would convert
17252 this number to @samp{0.08%}.)  The @kbd{=} key is a convenient way
17253 to convert a formula like @samp{8%} back to numeric form, 0.08.
17255 To compute what percentage one quantity is of another quantity,
17256 use @kbd{/ c %}.  For example, @w{@kbd{17 RET 68 / c %}} displays
17257 @samp{25%}.
17259 @kindex b %
17260 @pindex calc-percent-change
17261 @tindex relch
17262 The @kbd{b %} (@code{calc-percent-change}) [@code{relch}] command
17263 calculates the percentage change from one number to another.
17264 For example, @kbd{40 RET 50 b %} produces the answer @samp{25%},
17265 since 50 is 25% larger than 40.  A negative result represents a
17266 decrease:  @kbd{50 RET 40 b %} produces @samp{-20%}, since 40 is
17267 20% smaller than 50.  (The answers are different in magnitude
17268 because, in the first case, we're increasing by 25% of 40, but
17269 in the second case, we're decreasing by 20% of 50.)  The effect
17270 of @kbd{40 RET 50 b %} is to compute @cite{(50-40)/40}, converting
17271 the answer to percentage form as if by @kbd{c %}.
17273 @node Future Value, Present Value, Percentages, Financial Functions
17274 @subsection Future Value
17276 @noindent
17277 @kindex b F
17278 @pindex calc-fin-fv
17279 @tindex fv
17280 The @kbd{b F} (@code{calc-fin-fv}) [@code{fv}] command computes
17281 the future value of an investment.  It takes three arguments
17282 from the stack:  @samp{fv(@var{rate}, @var{n}, @var{payment})}.
17283 If you give payments of @var{payment} every year for @var{n}
17284 years, and the money you have paid earns interest at @var{rate} per
17285 year, then this function tells you what your investment would be
17286 worth at the end of the period.  (The actual interval doesn't
17287 have to be years, as long as @var{n} and @var{rate} are expressed
17288 in terms of the same intervals.)  This function assumes payments
17289 occur at the @emph{end} of each interval.
17291 @kindex I b F
17292 @tindex fvb
17293 The @kbd{I b F} [@code{fvb}] command does the same computation,
17294 but assuming your payments are at the beginning of each interval.
17295 Suppose you plan to deposit $1000 per year in a savings account
17296 earning 5.4% interest, starting right now.  How much will be
17297 in the account after five years?  @code{fvb(5.4%, 5, 1000) = 5870.73}.
17298 Thus you will have earned $870 worth of interest over the years.
17299 Using the stack, this calculation would have been
17300 @kbd{5.4 M-% 5 RET 1000 I b F}.  Note that the rate is expressed
17301 as a number between 0 and 1, @emph{not} as a percentage.
17303 @kindex H b F
17304 @tindex fvl
17305 The @kbd{H b F} [@code{fvl}] command computes the future value
17306 of an initial lump sum investment.  Suppose you could deposit
17307 those five thousand dollars in the bank right now; how much would
17308 they be worth in five years?  @code{fvl(5.4%, 5, 5000) = 6503.89}.
17310 The algebraic functions @code{fv} and @code{fvb} accept an optional
17311 fourth argument, which is used as an initial lump sum in the sense
17312 of @code{fvl}.  In other words, @code{fv(@var{rate}, @var{n},
17313 @var{payment}, @var{initial}) = fv(@var{rate}, @var{n}, @var{payment})
17314 + fvl(@var{rate}, @var{n}, @var{initial})}.@refill
17316 To illustrate the relationships between these functions, we could
17317 do the @code{fvb} calculation ``by hand'' using @code{fvl}.  The
17318 final balance will be the sum of the contributions of our five
17319 deposits at various times.  The first deposit earns interest for
17320 five years:  @code{fvl(5.4%, 5, 1000) = 1300.78}.  The second
17321 deposit only earns interest for four years:  @code{fvl(5.4%, 4, 1000) =
17322 1234.13}.  And so on down to the last deposit, which earns one
17323 year's interest:  @code{fvl(5.4%, 1, 1000) = 1054.00}.  The sum of
17324 these five values is, sure enough, $5870.73, just as was computed
17325 by @code{fvb} directly.
17327 What does @code{fv(5.4%, 5, 1000) = 5569.96} mean?  The payments
17328 are now at the ends of the periods.  The end of one year is the same
17329 as the beginning of the next, so what this really means is that we've
17330 lost the payment at year zero (which contributed $1300.78), but we're
17331 now counting the payment at year five (which, since it didn't have
17332 a chance to earn interest, counts as $1000).  Indeed, @cite{5569.96 =
17333 5870.73 - 1300.78 + 1000} (give or take a bit of roundoff error).
17335 @node Present Value, Related Financial Functions, Future Value, Financial Functions
17336 @subsection Present Value
17338 @noindent
17339 @kindex b P
17340 @pindex calc-fin-pv
17341 @tindex pv
17342 The @kbd{b P} (@code{calc-fin-pv}) [@code{pv}] command computes
17343 the present value of an investment.  Like @code{fv}, it takes
17344 three arguments:  @code{pv(@var{rate}, @var{n}, @var{payment})}.
17345 It computes the present value of a series of regular payments.
17346 Suppose you have the chance to make an investment that will
17347 pay $2000 per year over the next four years; as you receive
17348 these payments you can put them in the bank at 9% interest.
17349 You want to know whether it is better to make the investment, or
17350 to keep the money in the bank where it earns 9% interest right
17351 from the start.  The calculation @code{pv(9%, 4, 2000)} gives the
17352 result 6479.44.  If your initial investment must be less than this,
17353 say, $6000, then the investment is worthwhile.  But if you had to
17354 put up $7000, then it would be better just to leave it in the bank.
17356 Here is the interpretation of the result of @code{pv}:  You are
17357 trying to compare the return from the investment you are
17358 considering, which is @code{fv(9%, 4, 2000) = 9146.26}, with
17359 the return from leaving the money in the bank, which is
17360 @code{fvl(9%, 4, @var{x})} where @var{x} is the amount of money
17361 you would have to put up in advance.  The @code{pv} function
17362 finds the break-even point, @cite{x = 6479.44}, at which
17363 @code{fvl(9%, 4, 6479.44)} is also equal to 9146.26.  This is
17364 the largest amount you should be willing to invest.
17366 @kindex I b P
17367 @tindex pvb
17368 The @kbd{I b P} [@code{pvb}] command solves the same problem,
17369 but with payments occurring at the beginning of each interval.
17370 It has the same relationship to @code{fvb} as @code{pv} has
17371 to @code{fv}.  For example @code{pvb(9%, 4, 2000) = 7062.59},
17372 a larger number than @code{pv} produced because we get to start
17373 earning interest on the return from our investment sooner.
17375 @kindex H b P
17376 @tindex pvl
17377 The @kbd{H b P} [@code{pvl}] command computes the present value of
17378 an investment that will pay off in one lump sum at the end of the
17379 period.  For example, if we get our $8000 all at the end of the
17380 four years, @code{pvl(9%, 4, 8000) = 5667.40}.  This is much
17381 less than @code{pv} reported, because we don't earn any interest
17382 on the return from this investment.  Note that @code{pvl} and
17383 @code{fvl} are simple inverses:  @code{fvl(9%, 4, 5667.40) = 8000}.
17385 You can give an optional fourth lump-sum argument to @code{pv}
17386 and @code{pvb}; this is handled in exactly the same way as the
17387 fourth argument for @code{fv} and @code{fvb}.
17389 @kindex b N
17390 @pindex calc-fin-npv
17391 @tindex npv
17392 The @kbd{b N} (@code{calc-fin-npv}) [@code{npv}] command computes
17393 the net present value of a series of irregular investments.
17394 The first argument is the interest rate.  The second argument is
17395 a vector which represents the expected return from the investment
17396 at the end of each interval.  For example, if the rate represents
17397 a yearly interest rate, then the vector elements are the return
17398 from the first year, second year, and so on.
17400 Thus, @code{npv(9%, [2000,2000,2000,2000]) = pv(9%, 4, 2000) = 6479.44}.
17401 Obviously this function is more interesting when the payments are
17402 not all the same!
17404 The @code{npv} function can actually have two or more arguments.
17405 Multiple arguments are interpreted in the same way as for the
17406 vector statistical functions like @code{vsum}.
17407 @xref{Single-Variable Statistics}.  Basically, if there are several
17408 payment arguments, each either a vector or a plain number, all these
17409 values are collected left-to-right into the complete list of payments.
17410 A numeric prefix argument on the @kbd{b N} command says how many
17411 payment values or vectors to take from the stack.@refill
17413 @kindex I b N
17414 @tindex npvb
17415 The @kbd{I b N} [@code{npvb}] command computes the net present
17416 value where payments occur at the beginning of each interval
17417 rather than at the end.
17419 @node Related Financial Functions, Depreciation Functions, Present Value, Financial Functions
17420 @subsection Related Financial Functions
17422 @noindent
17423 The functions in this section are basically inverses of the
17424 present value functions with respect to the various arguments.
17426 @kindex b M
17427 @pindex calc-fin-pmt
17428 @tindex pmt
17429 The @kbd{b M} (@code{calc-fin-pmt}) [@code{pmt}] command computes
17430 the amount of periodic payment necessary to amortize a loan.
17431 Thus @code{pmt(@var{rate}, @var{n}, @var{amount})} equals the
17432 value of @var{payment} such that @code{pv(@var{rate}, @var{n},
17433 @var{payment}) = @var{amount}}.@refill
17435 @kindex I b M
17436 @tindex pmtb
17437 The @kbd{I b M} [@code{pmtb}] command does the same computation
17438 but using @code{pvb} instead of @code{pv}.  Like @code{pv} and
17439 @code{pvb}, these functions can also take a fourth argument which
17440 represents an initial lump-sum investment.
17442 @kindex H b M
17443 The @kbd{H b M} key just invokes the @code{fvl} function, which is
17444 the inverse of @code{pvl}.  There is no explicit @code{pmtl} function.
17446 @kindex b #
17447 @pindex calc-fin-nper
17448 @tindex nper
17449 The @kbd{b #} (@code{calc-fin-nper}) [@code{nper}] command computes
17450 the number of regular payments necessary to amortize a loan.
17451 Thus @code{nper(@var{rate}, @var{payment}, @var{amount})} equals
17452 the value of @var{n} such that @code{pv(@var{rate}, @var{n},
17453 @var{payment}) = @var{amount}}.  If @var{payment} is too small
17454 ever to amortize a loan for @var{amount} at interest rate @var{rate},
17455 the @code{nper} function is left in symbolic form.@refill
17457 @kindex I b #
17458 @tindex nperb
17459 The @kbd{I b #} [@code{nperb}] command does the same computation
17460 but using @code{pvb} instead of @code{pv}.  You can give a fourth
17461 lump-sum argument to these functions, but the computation will be
17462 rather slow in the four-argument case.@refill
17464 @kindex H b #
17465 @tindex nperl
17466 The @kbd{H b #} [@code{nperl}] command does the same computation
17467 using @code{pvl}.  By exchanging @var{payment} and @var{amount} you
17468 can also get the solution for @code{fvl}.  For example,
17469 @code{nperl(8%, 2000, 1000) = 9.006}, so if you place $1000 in a
17470 bank account earning 8%, it will take nine years to grow to $2000.@refill
17472 @kindex b T
17473 @pindex calc-fin-rate
17474 @tindex rate
17475 The @kbd{b T} (@code{calc-fin-rate}) [@code{rate}] command computes
17476 the rate of return on an investment.  This is also an inverse of @code{pv}:
17477 @code{rate(@var{n}, @var{payment}, @var{amount})} computes the value of
17478 @var{rate} such that @code{pv(@var{rate}, @var{n}, @var{payment}) =
17479 @var{amount}}.  The result is expressed as a formula like @samp{6.3%}.@refill
17481 @kindex I b T
17482 @kindex H b T
17483 @tindex rateb
17484 @tindex ratel
17485 The @kbd{I b T} [@code{rateb}] and @kbd{H b T} [@code{ratel}]
17486 commands solve the analogous equations with @code{pvb} or @code{pvl}
17487 in place of @code{pv}.  Also, @code{rate} and @code{rateb} can
17488 accept an optional fourth argument just like @code{pv} and @code{pvb}.
17489 To redo the above example from a different perspective,
17490 @code{ratel(9, 2000, 1000) = 8.00597%}, which says you will need an
17491 interest rate of 8% in order to double your account in nine years.@refill
17493 @kindex b I
17494 @pindex calc-fin-irr
17495 @tindex irr
17496 The @kbd{b I} (@code{calc-fin-irr}) [@code{irr}] command is the
17497 analogous function to @code{rate} but for net present value.
17498 Its argument is a vector of payments.  Thus @code{irr(@var{payments})}
17499 computes the @var{rate} such that @code{npv(@var{rate}, @var{payments}) = 0};
17500 this rate is known as the @dfn{internal rate of return}.
17502 @kindex I b I
17503 @tindex irrb
17504 The @kbd{I b I} [@code{irrb}] command computes the internal rate of
17505 return assuming payments occur at the beginning of each period.
17507 @node Depreciation Functions, Definitions of Financial Functions, Related Financial Functions, Financial Functions
17508 @subsection Depreciation Functions
17510 @noindent
17511 The functions in this section calculate @dfn{depreciation}, which is
17512 the amount of value that a possession loses over time.  These functions
17513 are characterized by three parameters:  @var{cost}, the original cost
17514 of the asset; @var{salvage}, the value the asset will have at the end
17515 of its expected ``useful life''; and @var{life}, the number of years
17516 (or other periods) of the expected useful life.
17518 There are several methods for calculating depreciation that differ in
17519 the way they spread the depreciation over the lifetime of the asset.
17521 @kindex b S
17522 @pindex calc-fin-sln
17523 @tindex sln
17524 The @kbd{b S} (@code{calc-fin-sln}) [@code{sln}] command computes the
17525 ``straight-line'' depreciation.  In this method, the asset depreciates
17526 by the same amount every year (or period).  For example,
17527 @samp{sln(12000, 2000, 5)} returns 2000.  The asset costs $12000
17528 initially and will be worth $2000 after five years; it loses $2000
17529 per year.
17531 @kindex b Y
17532 @pindex calc-fin-syd
17533 @tindex syd
17534 The @kbd{b Y} (@code{calc-fin-syd}) [@code{syd}] command computes the
17535 accelerated ``sum-of-years'-digits'' depreciation.  Here the depreciation
17536 is higher during the early years of the asset's life.  Since the
17537 depreciation is different each year, @kbd{b Y} takes a fourth @var{period}
17538 parameter which specifies which year is requested, from 1 to @var{life}.
17539 If @var{period} is outside this range, the @code{syd} function will
17540 return zero.
17542 @kindex b D
17543 @pindex calc-fin-ddb
17544 @tindex ddb
17545 The @kbd{b D} (@code{calc-fin-ddb}) [@code{ddb}] command computes an
17546 accelerated depreciation using the double-declining balance method.
17547 It also takes a fourth @var{period} parameter.
17549 For symmetry, the @code{sln} function will accept a @var{period}
17550 parameter as well, although it will ignore its value except that the
17551 return value will as usual be zero if @var{period} is out of range.
17553 For example, pushing the vector @cite{[1,2,3,4,5]} (perhaps with @kbd{v x 5})
17554 and then mapping @kbd{V M ' [sln(12000,2000,5,$), syd(12000,2000,5,$),
17555 ddb(12000,2000,5,$)] RET} produces a matrix that allows us to compare
17556 the three depreciation methods:
17558 @group
17559 @example
17560 [ [ 2000, 3333, 4800 ]
17561   [ 2000, 2667, 2880 ]
17562   [ 2000, 2000, 1728 ]
17563   [ 2000, 1333,  592 ]
17564   [ 2000,  667,   0  ] ]
17565 @end example
17566 @end group
17568 @noindent
17569 (Values have been rounded to nearest integers in this figure.)
17570 We see that @code{sln} depreciates by the same amount each year,
17571 @kbd{syd} depreciates more at the beginning and less at the end,
17572 and @kbd{ddb} weights the depreciation even more toward the beginning.
17574 Summing columns with @kbd{V R : +} yields @cite{[10000, 10000, 10000]};
17575 the total depreciation in any method is (by definition) the
17576 difference between the cost and the salvage value.
17578 @node Definitions of Financial Functions, , Depreciation Functions, Financial Functions
17579 @subsection Definitions
17581 @noindent
17582 For your reference, here are the actual formulas used to compute
17583 Calc's financial functions.
17585 Calc will not evaluate a financial function unless the @var{rate} or
17586 @var{n} argument is known.  However, @var{payment} or @var{amount} can
17587 be a variable.  Calc expands these functions according to the
17588 formulas below for symbolic arguments only when you use the @kbd{a "}
17589 (@code{calc-expand-formula}) command, or when taking derivatives or
17590 integrals or solving equations involving the functions.
17592 @ifinfo
17593 These formulas are shown using the conventions of ``Big'' display
17594 mode (@kbd{d B}); for example, the formula for @code{fv} written
17595 linearly is @samp{pmt * ((1 + rate)^n) - 1) / rate}.
17597 @example
17598                                         n
17599                               (1 + rate)  - 1
17600 fv(rate, n, pmt) =      pmt * ---------------
17601                                    rate
17603                                          n
17604                               ((1 + rate)  - 1) (1 + rate)
17605 fvb(rate, n, pmt) =     pmt * ----------------------------
17606                                          rate
17608                                         n
17609 fvl(rate, n, pmt) =     pmt * (1 + rate)
17611                                             -n
17612                               1 - (1 + rate)  
17613 pv(rate, n, pmt) =      pmt * ----------------
17614                                     rate
17616                                              -n
17617                               (1 - (1 + rate)  ) (1 + rate)
17618 pvb(rate, n, pmt) =     pmt * -----------------------------
17619                                          rate
17621                                         -n
17622 pvl(rate, n, pmt) =     pmt * (1 + rate)
17624                                     -1               -2               -3
17625 npv(rate, [a, b, c]) =  a*(1 + rate)   + b*(1 + rate)   + c*(1 + rate)
17627                                         -1               -2
17628 npvb(rate, [a, b, c]) = a + b*(1 + rate)   + c*(1 + rate)
17630                                              -n
17631                         (amt - x * (1 + rate)  ) * rate
17632 pmt(rate, n, amt, x) =  -------------------------------
17633                                              -n
17634                                1 - (1 + rate)
17636                                              -n
17637                         (amt - x * (1 + rate)  ) * rate
17638 pmtb(rate, n, amt, x) = -------------------------------
17639                                         -n
17640                          (1 - (1 + rate)  ) (1 + rate)
17642                                    amt * rate
17643 nper(rate, pmt, amt) =  - log(1 - ------------, 1 + rate)
17644                                       pmt
17646                                     amt * rate
17647 nperb(rate, pmt, amt) = - log(1 - ---------------, 1 + rate)
17648                                   pmt * (1 + rate)
17650                               amt
17651 nperl(rate, pmt, amt) = - log(---, 1 + rate)
17652                               pmt
17654                            1/n
17655                         pmt
17656 ratel(n, pmt, amt) =    ------ - 1
17657                            1/n
17658                         amt
17660                         cost - salv
17661 sln(cost, salv, life) = -----------
17662                            life
17664                              (cost - salv) * (life - per + 1)
17665 syd(cost, salv, life, per) = --------------------------------
17666                                   life * (life + 1) / 2
17668                              book * 2
17669 ddb(cost, salv, life, per) = --------,  book = cost - depreciation so far
17670                                life
17671 @end example
17672 @end ifinfo
17673 @tex
17674 \turnoffactive
17675 $$ \code{fv}(r, n, p) = p { (1 + r)^n - 1 \over r } $$
17676 $$ \code{fvb}(r, n, p) = p { ((1 + r)^n - 1) (1 + r) \over r } $$
17677 $$ \code{fvl}(r, n, p) = p (1 + r)^n $$
17678 $$ \code{pv}(r, n, p) = p { 1 - (1 + r)^{-n} \over r } $$
17679 $$ \code{pvb}(r, n, p) = p { (1 - (1 + r)^{-n}) (1 + r) \over r } $$
17680 $$ \code{pvl}(r, n, p) = p (1 + r)^{-n} $$
17681 $$ \code{npv}(r, [a,b,c]) = a (1 + r)^{-1} + b (1 + r)^{-2} + c (1 + r)^{-3} $$
17682 $$ \code{npvb}(r, [a,b,c]) = a + b (1 + r)^{-1} + c (1 + r)^{-2} $$
17683 $$ \code{pmt}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over 1 - (1 + r)^{-n} }$$
17684 $$ \code{pmtb}(r, n, a, x) = { (a - x (1 + r)^{-n}) r \over
17685                                (1 - (1 + r)^{-n}) (1 + r) } $$
17686 $$ \code{nper}(r, p, a) = -\code{log}(1 - { a r \over p }, 1 + r) $$
17687 $$ \code{nperb}(r, p, a) = -\code{log}(1 - { a r \over p (1 + r) }, 1 + r) $$
17688 $$ \code{nperl}(r, p, a) = -\code{log}({a \over p}, 1 + r) $$
17689 $$ \code{ratel}(n, p, a) = { p^{1/n} \over a^{1/n} } - 1 $$
17690 $$ \code{sln}(c, s, l) = { c - s \over l } $$
17691 $$ \code{syd}(c, s, l, p) = { (c - s) (l - p + 1) \over l (l+1) / 2 } $$
17692 $$ \code{ddb}(c, s, l, p) = { 2 (c - \hbox{depreciation so far}) \over l } $$
17693 @end tex
17695 @noindent
17696 In @code{pmt} and @code{pmtb}, @cite{x=0} if omitted.
17698 These functions accept any numeric objects, including error forms,
17699 intervals, and even (though not very usefully) complex numbers.  The
17700 above formulas specify exactly the behavior of these functions with
17701 all sorts of inputs.
17703 Note that if the first argument to the @code{log} in @code{nper} is
17704 negative, @code{nper} leaves itself in symbolic form rather than
17705 returning a (financially meaningless) complex number.
17707 @samp{rate(num, pmt, amt)} solves the equation
17708 @samp{pv(rate, num, pmt) = amt} for @samp{rate} using @kbd{H a R}
17709 (@code{calc-find-root}), with the interval @samp{[.01% .. 100%]}
17710 for an initial guess.  The @code{rateb} function is the same except
17711 that it uses @code{pvb}.  Note that @code{ratel} can be solved
17712 directly; its formula is shown in the above list.
17714 Similarly, @samp{irr(pmts)} solves the equation @samp{npv(rate, pmts) = 0}
17715 for @samp{rate}.
17717 If you give a fourth argument to @code{nper} or @code{nperb}, Calc
17718 will also use @kbd{H a R} to solve the equation using an initial
17719 guess interval of @samp{[0 .. 100]}.
17721 A fourth argument to @code{fv} simply sums the two components
17722 calculated from the above formulas for @code{fv} and @code{fvl}.
17723 The same is true of @code{fvb}, @code{pv}, and @code{pvb}.
17725 The @kbd{ddb} function is computed iteratively; the ``book'' value
17726 starts out equal to @var{cost}, and decreases according to the above
17727 formula for the specified number of periods.  If the book value
17728 would decrease below @var{salvage}, it only decreases to @var{salvage}
17729 and the depreciation is zero for all subsequent periods.  The @code{ddb}
17730 function returns the amount the book value decreased in the specified
17731 period.
17733 The Calc financial function names were borrowed mostly from Microsoft
17734 Excel and Borland's Quattro.  The @code{ratel} function corresponds to
17735 @samp{@@CGR} in Borland's Reflex.  The @code{nper} and @code{nperl}
17736 functions correspond to @samp{@@TERM} and @samp{@@CTERM} in Quattro,
17737 respectively.  Beware that the Calc functions may take their arguments
17738 in a different order than the corresponding functions in your favorite
17739 spreadsheet.
17741 @node Binary Functions, , Financial Functions, Arithmetic
17742 @section Binary Number Functions
17744 @noindent
17745 The commands in this chapter all use two-letter sequences beginning with
17746 the @kbd{b} prefix.
17748 @cindex Binary numbers
17749 The ``binary'' operations actually work regardless of the currently
17750 displayed radix, although their results make the most sense in a radix
17751 like 2, 8, or 16 (as obtained by the @kbd{d 2}, @kbd{d 8}, or @w{@kbd{d 6}}
17752 commands, respectively).  You may also wish to enable display of leading
17753 zeros with @kbd{d z}.  @xref{Radix Modes}.
17755 @cindex Word size for binary operations
17756 The Calculator maintains a current @dfn{word size} @cite{w}, an
17757 arbitrary positive or negative integer.  For a positive word size, all
17758 of the binary operations described here operate modulo @cite{2^w}.  In
17759 particular, negative arguments are converted to positive integers modulo
17760 @cite{2^w} by all binary functions.@refill
17762 If the word size is negative, binary operations produce 2's complement
17763 integers from @c{$-2^{-w-1}$}
17764 @cite{-(2^(-w-1))} to @c{$2^{-w-1}-1$}
17765 @cite{2^(-w-1)-1} inclusive.  Either
17766 mode accepts inputs in any range; the sign of @cite{w} affects only
17767 the results produced.
17769 @kindex b c
17770 @pindex calc-clip
17771 @tindex clip
17772 The @kbd{b c} (@code{calc-clip})
17773 [@code{clip}] command can be used to clip a number by reducing it modulo
17774 @cite{2^w}.  The commands described in this chapter automatically clip
17775 their results to the current word size.  Note that other operations like
17776 addition do not use the current word size, since integer addition
17777 generally is not ``binary.''  (However, @pxref{Simplification Modes},
17778 @code{calc-bin-simplify-mode}.)  For example, with a word size of 8
17779 bits @kbd{b c} converts a number to the range 0 to 255; with a word
17780 size of @i{-8} @kbd{b c} converts to the range @i{-128} to 127.@refill
17782 @kindex b w
17783 @pindex calc-word-size
17784 The default word size is 32 bits.  All operations except the shifts and
17785 rotates allow you to specify a different word size for that one
17786 operation by giving a numeric prefix argument:  @kbd{C-u 8 b c} clips the
17787 top of stack to the range 0 to 255 regardless of the current word size.
17788 To set the word size permanently, use @kbd{b w} (@code{calc-word-size}).
17789 This command displays a prompt with the current word size; press @key{RET}
17790 immediately to keep this word size, or type a new word size at the prompt.
17792 When the binary operations are written in symbolic form, they take an
17793 optional second (or third) word-size parameter.  When a formula like
17794 @samp{and(a,b)} is finally evaluated, the word size current at that time
17795 will be used, but when @samp{and(a,b,-8)} is evaluated, a word size of
17796 @i{-8} will always be used.  A symbolic binary function will be left
17797 in symbolic form unless the all of its argument(s) are integers or
17798 integer-valued floats.
17800 If either or both arguments are modulo forms for which @cite{M} is a
17801 power of two, that power of two is taken as the word size unless a
17802 numeric prefix argument overrides it.  The current word size is never
17803 consulted when modulo-power-of-two forms are involved.
17805 @kindex b a
17806 @pindex calc-and
17807 @tindex and
17808 The @kbd{b a} (@code{calc-and}) [@code{and}] command computes the bitwise
17809 AND of the two numbers on the top of the stack.  In other words, for each
17810 of the @cite{w} binary digits of the two numbers (pairwise), the corresponding
17811 bit of the result is 1 if and only if both input bits are 1:
17812 @samp{and(2#1100, 2#1010) = 2#1000}.
17814 @kindex b o
17815 @pindex calc-or
17816 @tindex or
17817 The @kbd{b o} (@code{calc-or}) [@code{or}] command computes the bitwise
17818 inclusive OR of two numbers.  A bit is 1 if either of the input bits, or
17819 both, are 1:  @samp{or(2#1100, 2#1010) = 2#1110}.
17821 @kindex b x
17822 @pindex calc-xor
17823 @tindex xor
17824 The @kbd{b x} (@code{calc-xor}) [@code{xor}] command computes the bitwise
17825 exclusive OR of two numbers.  A bit is 1 if exactly one of the input bits
17826 is 1:  @samp{xor(2#1100, 2#1010) = 2#0110}.
17828 @kindex b d
17829 @pindex calc-diff
17830 @tindex diff
17831 The @kbd{b d} (@code{calc-diff}) [@code{diff}] command computes the bitwise
17832 difference of two numbers; this is defined by @samp{diff(a,b) = and(a,not(b))},
17833 so that @samp{diff(2#1100, 2#1010) = 2#0100}.
17835 @kindex b n
17836 @pindex calc-not
17837 @tindex not
17838 The @kbd{b n} (@code{calc-not}) [@code{not}] command computes the bitwise
17839 NOT of a number.  A bit is 1 if the input bit is 0 and vice-versa.
17841 @kindex b l
17842 @pindex calc-lshift-binary
17843 @tindex lsh
17844 The @kbd{b l} (@code{calc-lshift-binary}) [@code{lsh}] command shifts a
17845 number left by one bit, or by the number of bits specified in the numeric
17846 prefix argument.  A negative prefix argument performs a logical right shift,
17847 in which zeros are shifted in on the left.  In symbolic form, @samp{lsh(a)}
17848 is short for @samp{lsh(a,1)}, which in turn is short for @samp{lsh(a,n,w)}.
17849 Bits shifted ``off the end,'' according to the current word size, are lost.
17851 @kindex H b l
17852 @kindex H b r
17853 @c @mindex @idots
17854 @kindex H b L
17855 @c @mindex @null
17856 @kindex H b R
17857 @c @mindex @null
17858 @kindex H b t
17859 The @kbd{H b l} command also does a left shift, but it takes two arguments
17860 from the stack (the value to shift, and, at top-of-stack, the number of
17861 bits to shift).  This version interprets the prefix argument just like
17862 the regular binary operations, i.e., as a word size.  The Hyperbolic flag
17863 has a similar effect on the rest of the binary shift and rotate commands.
17865 @kindex b r
17866 @pindex calc-rshift-binary
17867 @tindex rsh
17868 The @kbd{b r} (@code{calc-rshift-binary}) [@code{rsh}] command shifts a
17869 number right by one bit, or by the number of bits specified in the numeric
17870 prefix argument:  @samp{rsh(a,n) = lsh(a,-n)}.
17872 @kindex b L
17873 @pindex calc-lshift-arith
17874 @tindex ash
17875 The @kbd{b L} (@code{calc-lshift-arith}) [@code{ash}] command shifts a
17876 number left.  It is analogous to @code{lsh}, except that if the shift
17877 is rightward (the prefix argument is negative), an arithmetic shift
17878 is performed as described below.
17880 @kindex b R
17881 @pindex calc-rshift-arith
17882 @tindex rash
17883 The @kbd{b R} (@code{calc-rshift-arith}) [@code{rash}] command performs
17884 an ``arithmetic'' shift to the right, in which the leftmost bit (according
17885 to the current word size) is duplicated rather than shifting in zeros.
17886 This corresponds to dividing by a power of two where the input is interpreted
17887 as a signed, twos-complement number.  (The distinction between the @samp{rsh}
17888 and @samp{rash} operations is totally independent from whether the word
17889 size is positive or negative.)  With a negative prefix argument, this
17890 performs a standard left shift.
17892 @kindex b t
17893 @pindex calc-rotate-binary
17894 @tindex rot
17895 The @kbd{b t} (@code{calc-rotate-binary}) [@code{rot}] command rotates a
17896 number one bit to the left.  The leftmost bit (according to the current
17897 word size) is dropped off the left and shifted in on the right.  With a
17898 numeric prefix argument, the number is rotated that many bits to the left
17899 or right.
17901 @xref{Set Operations}, for the @kbd{b p} and @kbd{b u} commands that
17902 pack and unpack binary integers into sets.  (For example, @kbd{b u}
17903 unpacks the number @samp{2#11001} to the set of bit-numbers
17904 @samp{[0, 3, 4]}.)  Type @kbd{b u V #} to count the number of ``1''
17905 bits in a binary integer.
17907 Another interesting use of the set representation of binary integers
17908 is to reverse the bits in, say, a 32-bit integer.  Type @kbd{b u} to
17909 unpack; type @kbd{31 TAB -} to replace each bit-number in the set
17910 with 31 minus that bit-number; type @kbd{b p} to pack the set back
17911 into a binary integer.
17913 @node Scientific Functions, Matrix Functions, Arithmetic, Top
17914 @chapter Scientific Functions
17916 @noindent
17917 The functions described here perform trigonometric and other transcendental
17918 calculations.  They generally produce floating-point answers correct to the
17919 full current precision.  The @kbd{H} (Hyperbolic) and @kbd{I} (Inverse)
17920 flag keys must be used to get some of these functions from the keyboard.
17922 @kindex P
17923 @pindex calc-pi
17924 @cindex @code{pi} variable
17925 @vindex pi
17926 @kindex H P
17927 @cindex @code{e} variable
17928 @vindex e
17929 @kindex I P
17930 @cindex @code{gamma} variable
17931 @vindex gamma
17932 @cindex Gamma constant, Euler's
17933 @cindex Euler's gamma constant
17934 @kindex H I P
17935 @cindex @code{phi} variable
17936 @cindex Phi, golden ratio
17937 @cindex Golden ratio
17938 One miscellanous command is shift-@kbd{P} (@code{calc-pi}), which pushes
17939 the value of @c{$\pi$}
17940 @cite{pi} (at the current precision) onto the stack.  With the
17941 Hyperbolic flag, it pushes the value @cite{e}, the base of natural logarithms.
17942 With the Inverse flag, it pushes Euler's constant @c{$\gamma$}
17943 @cite{gamma} (about 0.5772).  With both Inverse and Hyperbolic, it
17944 pushes the ``golden ratio'' @c{$\phi$}
17945 @cite{phi} (about 1.618).  (At present, Euler's constant is not available
17946 to unlimited precision; Calc knows only the first 100 digits.)
17947 In Symbolic mode, these commands push the
17948 actual variables @samp{pi}, @samp{e}, @samp{gamma}, and @samp{phi},
17949 respectively, instead of their values; @pxref{Symbolic Mode}.@refill
17951 @c @mindex Q
17952 @c @mindex I Q
17953 @kindex I Q
17954 @tindex sqr
17955 The @kbd{Q} (@code{calc-sqrt}) [@code{sqrt}] function is described elsewhere;
17956 @pxref{Basic Arithmetic}.  With the Inverse flag [@code{sqr}], this command
17957 computes the square of the argument.
17959 @xref{Prefix Arguments}, for a discussion of the effect of numeric
17960 prefix arguments on commands in this chapter which do not otherwise
17961 interpret a prefix argument.
17963 @menu
17964 * Logarithmic Functions::
17965 * Trigonometric and Hyperbolic Functions::
17966 * Advanced Math Functions::
17967 * Branch Cuts::
17968 * Random Numbers::
17969 * Combinatorial Functions::
17970 * Probability Distribution Functions::
17971 @end menu
17973 @node Logarithmic Functions, Trigonometric and Hyperbolic Functions, Scientific Functions, Scientific Functions
17974 @section Logarithmic Functions
17976 @noindent
17977 @kindex L
17978 @pindex calc-ln
17979 @tindex ln
17980 @c @mindex @null
17981 @kindex I E
17982 The shift-@kbd{L} (@code{calc-ln}) [@code{ln}] command computes the natural
17983 logarithm of the real or complex number on the top of the stack.  With
17984 the Inverse flag it computes the exponential function instead, although
17985 this is redundant with the @kbd{E} command.
17987 @kindex E
17988 @pindex calc-exp
17989 @tindex exp
17990 @c @mindex @null
17991 @kindex I L
17992 The shift-@kbd{E} (@code{calc-exp}) [@code{exp}] command computes the
17993 exponential, i.e., @cite{e} raised to the power of the number on the stack.
17994 The meanings of the Inverse and Hyperbolic flags follow from those for
17995 the @code{calc-ln} command.
17997 @kindex H L
17998 @kindex H E
17999 @pindex calc-log10
18000 @tindex log10
18001 @tindex exp10
18002 @c @mindex @null
18003 @kindex H I L
18004 @c @mindex @null
18005 @kindex H I E
18006 The @kbd{H L} (@code{calc-log10}) [@code{log10}] command computes the common
18007 (base-10) logarithm of a number.  (With the Inverse flag [@code{exp10}],
18008 it raises ten to a given power.)  Note that the common logarithm of a
18009 complex number is computed by taking the natural logarithm and dividing
18010 by @c{$\ln10$}
18011 @cite{ln(10)}.
18013 @kindex B
18014 @kindex I B
18015 @pindex calc-log
18016 @tindex log
18017 @tindex alog
18018 The @kbd{B} (@code{calc-log}) [@code{log}] command computes a logarithm
18019 to any base.  For example, @kbd{1024 @key{RET} 2 B} produces 10, since
18020 @c{$2^{10} = 1024$}
18021 @cite{2^10 = 1024}.  In certain cases like @samp{log(3,9)}, the result
18022 will be either @cite{1:2} or @cite{0.5} depending on the current Fraction
18023 Mode setting.  With the Inverse flag [@code{alog}], this command is
18024 similar to @kbd{^} except that the order of the arguments is reversed.
18026 @kindex f I
18027 @pindex calc-ilog
18028 @tindex ilog
18029 The @kbd{f I} (@code{calc-ilog}) [@code{ilog}] command computes the
18030 integer logarithm of a number to any base.  The number and the base must
18031 themselves be positive integers.  This is the true logarithm, rounded
18032 down to an integer.  Thus @kbd{ilog(x,10)} is 3 for all @cite{x} in the
18033 range from 1000 to 9999.  If both arguments are positive integers, exact
18034 integer arithmetic is used; otherwise, this is equivalent to
18035 @samp{floor(log(x,b))}.
18037 @kindex f E
18038 @pindex calc-expm1
18039 @tindex expm1
18040 The @kbd{f E} (@code{calc-expm1}) [@code{expm1}] command computes
18041 @c{$e^x - 1$}
18042 @cite{exp(x)-1}, but using an algorithm that produces a more accurate
18043 answer when the result is close to zero, i.e., when @c{$e^x$}
18044 @cite{exp(x)} is close
18045 to one.
18047 @kindex f L
18048 @pindex calc-lnp1
18049 @tindex lnp1
18050 The @kbd{f L} (@code{calc-lnp1}) [@code{lnp1}] command computes
18051 @c{$\ln(x+1)$}
18052 @cite{ln(x+1)}, producing a more accurate answer when @cite{x} is close
18053 to zero.
18055 @node Trigonometric and Hyperbolic Functions, Advanced Math Functions, Logarithmic Functions, Scientific Functions
18056 @section Trigonometric/Hyperbolic Functions
18058 @noindent
18059 @kindex S
18060 @pindex calc-sin
18061 @tindex sin
18062 The shift-@kbd{S} (@code{calc-sin}) [@code{sin}] command computes the sine
18063 of an angle or complex number.  If the input is an HMS form, it is interpreted
18064 as degrees-minutes-seconds; otherwise, the input is interpreted according
18065 to the current angular mode.  It is best to use Radians mode when operating
18066 on complex numbers.@refill
18068 Calc's ``units'' mechanism includes angular units like @code{deg},
18069 @code{rad}, and @code{grad}.  While @samp{sin(45 deg)} is not evaluated
18070 all the time, the @kbd{u s} (@code{calc-simplify-units}) command will
18071 simplify @samp{sin(45 deg)} by taking the sine of 45 degrees, regardless
18072 of the current angular mode.  @xref{Basic Operations on Units}.
18074 Also, the symbolic variable @code{pi} is not ordinarily recognized in
18075 arguments to trigonometric functions, as in @samp{sin(3 pi / 4)}, but
18076 the @kbd{a s} (@code{calc-simplify}) command recognizes many such
18077 formulas when the current angular mode is radians @emph{and} symbolic
18078 mode is enabled; this example would be replaced by @samp{sqrt(2) / 2}.
18079 @xref{Symbolic Mode}.  Beware, this simplification occurs even if you
18080 have stored a different value in the variable @samp{pi}; this is one
18081 reason why changing built-in variables is a bad idea.  Arguments of
18082 the form @cite{x} plus a multiple of @c{$\pi/2$}
18083 @cite{pi/2} are also simplified.
18084 Calc includes similar formulas for @code{cos} and @code{tan}.@refill
18086 The @kbd{a s} command knows all angles which are integer multiples of
18087 @c{$\pi/12$}
18088 @cite{pi/12}, @c{$\pi/10$}
18089 @cite{pi/10}, or @c{$\pi/8$}
18090 @cite{pi/8} radians.  In degrees mode,
18091 analogous simplifications occur for integer multiples of 15 or 18
18092 degrees, and for arguments plus multiples of 90 degrees.
18094 @kindex I S
18095 @pindex calc-arcsin
18096 @tindex arcsin
18097 With the Inverse flag, @code{calc-sin} computes an arcsine.  This is also
18098 available as the @code{calc-arcsin} command or @code{arcsin} algebraic
18099 function.  The returned argument is converted to degrees, radians, or HMS
18100 notation depending on the current angular mode.
18102 @kindex H S
18103 @pindex calc-sinh
18104 @tindex sinh
18105 @kindex H I S
18106 @pindex calc-arcsinh
18107 @tindex arcsinh
18108 With the Hyperbolic flag, @code{calc-sin} computes the hyperbolic
18109 sine, also available as @code{calc-sinh} [@code{sinh}].  With the
18110 Hyperbolic and Inverse flags, it computes the hyperbolic arcsine
18111 (@code{calc-arcsinh}) [@code{arcsinh}].
18113 @kindex C
18114 @pindex calc-cos
18115 @tindex cos
18116 @c @mindex @idots
18117 @kindex I C
18118 @pindex calc-arccos
18119 @c @mindex @null
18120 @tindex arccos
18121 @c @mindex @null
18122 @kindex H C
18123 @pindex calc-cosh
18124 @c @mindex @null
18125 @tindex cosh
18126 @c @mindex @null
18127 @kindex H I C
18128 @pindex calc-arccosh
18129 @c @mindex @null
18130 @tindex arccosh
18131 @c @mindex @null
18132 @kindex T
18133 @pindex calc-tan
18134 @c @mindex @null
18135 @tindex tan
18136 @c @mindex @null
18137 @kindex I T
18138 @pindex calc-arctan
18139 @c @mindex @null
18140 @tindex arctan
18141 @c @mindex @null
18142 @kindex H T
18143 @pindex calc-tanh
18144 @c @mindex @null
18145 @tindex tanh
18146 @c @mindex @null
18147 @kindex H I T
18148 @pindex calc-arctanh
18149 @c @mindex @null
18150 @tindex arctanh
18151 The shift-@kbd{C} (@code{calc-cos}) [@code{cos}] command computes the cosine
18152 of an angle or complex number, and shift-@kbd{T} (@code{calc-tan}) [@code{tan}]
18153 computes the tangent, along with all the various inverse and hyperbolic
18154 variants of these functions.
18156 @kindex f T
18157 @pindex calc-arctan2
18158 @tindex arctan2
18159 The @kbd{f T} (@code{calc-arctan2}) [@code{arctan2}] command takes two
18160 numbers from the stack and computes the arc tangent of their ratio.  The
18161 result is in the full range from @i{-180} (exclusive) to @i{+180}
18162 (inclusive) degrees, or the analogous range in radians.  A similar
18163 result would be obtained with @kbd{/} followed by @kbd{I T}, but the
18164 value would only be in the range from @i{-90} to @i{+90} degrees
18165 since the division loses information about the signs of the two
18166 components, and an error might result from an explicit division by zero
18167 which @code{arctan2} would avoid.  By (arbitrary) definition,
18168 @samp{arctan2(0,0)=0}.
18170 @pindex calc-sincos
18171 @c @starindex
18172 @tindex sincos
18173 @c @starindex
18174 @c @mindex arc@idots
18175 @tindex arcsincos
18176 The @code{calc-sincos} [@code{sincos}] command computes the sine and
18177 cosine of a number, returning them as a vector of the form
18178 @samp{[@var{cos}, @var{sin}]}.
18179 With the Inverse flag [@code{arcsincos}], this command takes a two-element
18180 vector as an argument and computes @code{arctan2} of the elements.
18181 (This command does not accept the Hyperbolic flag.)@refill
18183 @node Advanced Math Functions, Branch Cuts, Trigonometric and Hyperbolic Functions, Scientific Functions
18184 @section Advanced Mathematical Functions
18186 @noindent
18187 Calc can compute a variety of less common functions that arise in
18188 various branches of mathematics.  All of the functions described in
18189 this section allow arbitrary complex arguments and, except as noted,
18190 will work to arbitrarily large precisions.  They can not at present
18191 handle error forms or intervals as arguments.
18193 NOTE:  These functions are still experimental.  In particular, their
18194 accuracy is not guaranteed in all domains.  It is advisable to set the
18195 current precision comfortably higher than you actually need when
18196 using these functions.  Also, these functions may be impractically
18197 slow for some values of the arguments.
18199 @kindex f g
18200 @pindex calc-gamma
18201 @tindex gamma
18202 The @kbd{f g} (@code{calc-gamma}) [@code{gamma}] command computes the Euler
18203 gamma function.  For positive integer arguments, this is related to the
18204 factorial function:  @samp{gamma(n+1) = fact(n)}.  For general complex
18205 arguments the gamma function can be defined by the following definite
18206 integral:  @c{$\Gamma(a) = \int_0^\infty t^{a-1} e^t dt$}
18207 @cite{gamma(a) = integ(t^(a-1) exp(t), t, 0, inf)}.
18208 (The actual implementation uses far more efficient computational methods.)
18210 @kindex f G
18211 @tindex gammaP
18212 @c @mindex @idots
18213 @kindex I f G
18214 @c @mindex @null
18215 @kindex H f G
18216 @c @mindex @null
18217 @kindex H I f G
18218 @pindex calc-inc-gamma
18219 @c @mindex @null
18220 @tindex gammaQ
18221 @c @mindex @null
18222 @tindex gammag
18223 @c @mindex @null
18224 @tindex gammaG
18225 The @kbd{f G} (@code{calc-inc-gamma}) [@code{gammaP}] command computes
18226 the incomplete gamma function, denoted @samp{P(a,x)}.  This is defined by
18227 the integral, @c{$P(a,x) = \left( \int_0^x t^{a-1} e^t dt \right) / \Gamma(a)$}
18228 @cite{gammaP(a,x) = integ(t^(a-1) exp(t), t, 0, x) / gamma(a)}.
18229 This implies that @samp{gammaP(a,inf) = 1} for any @cite{a} (see the
18230 definition of the normal gamma function).
18232 Several other varieties of incomplete gamma function are defined.
18233 The complement of @cite{P(a,x)}, called @cite{Q(a,x) = 1-P(a,x)} by
18234 some authors, is computed by the @kbd{I f G} [@code{gammaQ}] command.
18235 You can think of this as taking the other half of the integral, from
18236 @cite{x} to infinity.
18238 @ifinfo
18239 The functions corresponding to the integrals that define @cite{P(a,x)}
18240 and @cite{Q(a,x)} but without the normalizing @cite{1/gamma(a)}
18241 factor are called @cite{g(a,x)} and @cite{G(a,x)}, respectively
18242 (where @cite{g} and @cite{G} represent the lower- and upper-case Greek
18243 letter gamma).  You can obtain these using the @kbd{H f G} [@code{gammag}]
18244 and @kbd{H I f G} [@code{gammaG}] commands.
18245 @end ifinfo
18246 @tex
18247 \turnoffactive
18248 The functions corresponding to the integrals that define $P(a,x)$
18249 and $Q(a,x)$ but without the normalizing $1/\Gamma(a)$
18250 factor are called $\gamma(a,x)$ and $\Gamma(a,x)$, respectively.
18251 You can obtain these using the \kbd{H f G} [\code{gammag}] and
18252 \kbd{I H f G} [\code{gammaG}] commands.
18253 @end tex
18255 @kindex f b
18256 @pindex calc-beta
18257 @tindex beta
18258 The @kbd{f b} (@code{calc-beta}) [@code{beta}] command computes the
18259 Euler beta function, which is defined in terms of the gamma function as
18260 @c{$B(a,b) = \Gamma(a) \Gamma(b) / \Gamma(a+b)$}
18261 @cite{beta(a,b) = gamma(a) gamma(b) / gamma(a+b)}, or by
18262 @c{$B(a,b) = \int_0^1 t^{a-1} (1-t)^{b-1} dt$}
18263 @cite{beta(a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, 1)}.
18265 @kindex f B
18266 @kindex H f B
18267 @pindex calc-inc-beta
18268 @tindex betaI
18269 @tindex betaB
18270 The @kbd{f B} (@code{calc-inc-beta}) [@code{betaI}] command computes
18271 the incomplete beta function @cite{I(x,a,b)}.  It is defined by
18272 @c{$I(x,a,b) = \left( \int_0^x t^{a-1} (1-t)^{b-1} dt \right) / B(a,b)$}
18273 @cite{betaI(x,a,b) = integ(t^(a-1) (1-t)^(b-1), t, 0, x) / beta(a,b)}.
18274 Once again, the @kbd{H} (hyperbolic) prefix gives the corresponding
18275 un-normalized version [@code{betaB}].
18277 @kindex f e
18278 @kindex I f e
18279 @pindex calc-erf
18280 @tindex erf
18281 @tindex erfc
18282 The @kbd{f e} (@code{calc-erf}) [@code{erf}] command computes the
18283 error function @c{$\hbox{erf}(x) = {2 \over \sqrt{\pi}} \int_0^x e^{-t^2} dt$}
18284 @cite{erf(x) = 2 integ(exp(-(t^2)), t, 0, x) / sqrt(pi)}.
18285 The complementary error function @kbd{I f e} (@code{calc-erfc}) [@code{erfc}]
18286 is the corresponding integral from @samp{x} to infinity; the sum
18287 @c{$\hbox{erf}(x) + \hbox{erfc}(x) = 1$}
18288 @cite{erf(x) + erfc(x) = 1}.
18290 @kindex f j
18291 @kindex f y
18292 @pindex calc-bessel-J
18293 @pindex calc-bessel-Y
18294 @tindex besJ
18295 @tindex besY
18296 The @kbd{f j} (@code{calc-bessel-J}) [@code{besJ}] and @kbd{f y}
18297 (@code{calc-bessel-Y}) [@code{besY}] commands compute the Bessel
18298 functions of the first and second kinds, respectively.
18299 In @samp{besJ(n,x)} and @samp{besY(n,x)} the ``order'' parameter
18300 @cite{n} is often an integer, but is not required to be one.
18301 Calc's implementation of the Bessel functions currently limits the
18302 precision to 8 digits, and may not be exact even to that precision.
18303 Use with care!@refill
18305 @node Branch Cuts, Random Numbers, Advanced Math Functions, Scientific Functions
18306 @section Branch Cuts and Principal Values
18308 @noindent
18309 @cindex Branch cuts
18310 @cindex Principal values
18311 All of the logarithmic, trigonometric, and other scientific functions are
18312 defined for complex numbers as well as for reals.
18313 This section describes the values
18314 returned in cases where the general result is a family of possible values.
18315 Calc follows section 12.5.3 of Steele's @dfn{Common Lisp, the Language},
18316 second edition, in these matters.  This section will describe each
18317 function briefly; for a more detailed discussion (including some nifty
18318 diagrams), consult Steele's book.
18320 Note that the branch cuts for @code{arctan} and @code{arctanh} were
18321 changed between the first and second editions of Steele.  Versions of
18322 Calc starting with 2.00 follow the second edition.
18324 The new branch cuts exactly match those of the HP-28/48 calculators.
18325 They also match those of Mathematica 1.2, except that Mathematica's
18326 @code{arctan} cut is always in the right half of the complex plane,
18327 and its @code{arctanh} cut is always in the top half of the plane.
18328 Calc's cuts are continuous with quadrants I and III for @code{arctan},
18329 or II and IV for @code{arctanh}.
18331 Note:  The current implementations of these functions with complex arguments
18332 are designed with proper behavior around the branch cuts in mind, @emph{not}
18333 efficiency or accuracy.  You may need to increase the floating precision
18334 and wait a while to get suitable answers from them.
18336 For @samp{sqrt(a+bi)}:  When @cite{a<0} and @cite{b} is small but positive
18337 or zero, the result is close to the @cite{+i} axis.  For @cite{b} small and
18338 negative, the result is close to the @cite{-i} axis.  The result always lies
18339 in the right half of the complex plane.
18341 For @samp{ln(a+bi)}:  The real part is defined as @samp{ln(abs(a+bi))}.
18342 The imaginary part is defined as @samp{arg(a+bi) = arctan2(b,a)}.
18343 Thus the branch cuts for @code{sqrt} and @code{ln} both lie on the
18344 negative real axis.
18346 The following table describes these branch cuts in another way.
18347 If the real and imaginary parts of @cite{z} are as shown, then
18348 the real and imaginary parts of @cite{f(z)} will be as shown.
18349 Here @code{eps} stands for a small positive value; each
18350 occurrence of @code{eps} may stand for a different small value.
18352 @smallexample
18353      z           sqrt(z)       ln(z)
18354 ----------------------------------------
18355    +,   0         +,  0       any, 0
18356    -,   0         0,  +       any, pi
18357    -, +eps      +eps, +      +eps, +
18358    -, -eps      +eps, -      +eps, -
18359 @end smallexample
18361 For @samp{z1^z2}:  This is defined by @samp{exp(ln(z1)*z2)}.
18362 One interesting consequence of this is that @samp{(-8)^1:3} does
18363 not evaluate to @i{-2} as you might expect, but to the complex
18364 number @cite{(1., 1.732)}.  Both of these are valid cube roots
18365 of @i{-8} (as is @cite{(1., -1.732)}); Calc chooses a perhaps
18366 less-obvious root for the sake of mathematical consistency.
18368 For @samp{arcsin(z)}:  This is defined by @samp{-i*ln(i*z + sqrt(1-z^2))}.
18369 The branch cuts are on the real axis, less than @i{-1} and greater than 1.
18371 For @samp{arccos(z)}:  This is defined by @samp{-i*ln(z + i*sqrt(1-z^2))},
18372 or equivalently by @samp{pi/2 - arcsin(z)}.  The branch cuts are on
18373 the real axis, less than @i{-1} and greater than 1.
18375 For @samp{arctan(z)}:  This is defined by
18376 @samp{(ln(1+i*z) - ln(1-i*z)) / (2*i)}.  The branch cuts are on the
18377 imaginary axis, below @cite{-i} and above @cite{i}.
18379 For @samp{arcsinh(z)}:  This is defined by @samp{ln(z + sqrt(1+z^2))}.
18380 The branch cuts are on the imaginary axis, below @cite{-i} and
18381 above @cite{i}.
18383 For @samp{arccosh(z)}:  This is defined by
18384 @samp{ln(z + (z+1)*sqrt((z-1)/(z+1)))}.  The branch cut is on the
18385 real axis less than 1.
18387 For @samp{arctanh(z)}:  This is defined by @samp{(ln(1+z) - ln(1-z)) / 2}.
18388 The branch cuts are on the real axis, less than @i{-1} and greater than 1.
18390 The following tables for @code{arcsin}, @code{arccos}, and
18391 @code{arctan} assume the current angular mode is radians.  The
18392 hyperbolic functions operate independently of the angular mode.
18394 @smallexample
18395        z             arcsin(z)            arccos(z)
18396 -------------------------------------------------------
18397  (-1..1),  0      (-pi/2..pi/2), 0       (0..pi), 0
18398  (-1..1), +eps    (-pi/2..pi/2), +eps    (0..pi), -eps
18399  (-1..1), -eps    (-pi/2..pi/2), -eps    (0..pi), +eps
18400    <-1,    0          -pi/2,     +         pi,    -
18401    <-1,  +eps      -pi/2 + eps,  +      pi - eps, -
18402    <-1,  -eps      -pi/2 + eps,  -      pi - eps, +
18403     >1,    0           pi/2,     -          0,    +
18404     >1,  +eps       pi/2 - eps,  +        +eps,   -
18405     >1,  -eps       pi/2 - eps,  -        +eps,   +
18406 @end smallexample
18408 @smallexample
18409        z            arccosh(z)         arctanh(z)
18410 -----------------------------------------------------
18411  (-1..1),  0        0,  (0..pi)       any,     0
18412  (-1..1), +eps    +eps, (0..pi)       any,    +eps
18413  (-1..1), -eps    +eps, (-pi..0)      any,    -eps
18414    <-1,    0        +,    pi           -,     pi/2
18415    <-1,  +eps       +,  pi - eps       -,  pi/2 - eps
18416    <-1,  -eps       +, -pi + eps       -, -pi/2 + eps
18417     >1,    0        +,     0           +,    -pi/2
18418     >1,  +eps       +,   +eps          +,  pi/2 - eps
18419     >1,  -eps       +,   -eps          +, -pi/2 + eps
18420 @end smallexample
18422 @smallexample
18423        z           arcsinh(z)           arctan(z)
18424 -----------------------------------------------------
18425    0, (-1..1)    0, (-pi/2..pi/2)         0,     any
18426    0,   <-1      -,    -pi/2            -pi/2,    -
18427  +eps,  <-1      +, -pi/2 + eps       pi/2 - eps, -
18428  -eps,  <-1      -, -pi/2 + eps      -pi/2 + eps, -
18429    0,    >1      +,     pi/2             pi/2,    +
18430  +eps,   >1      +,  pi/2 - eps       pi/2 - eps, +
18431  -eps,   >1      -,  pi/2 - eps      -pi/2 + eps, +
18432 @end smallexample
18434 Finally, the following identities help to illustrate the relationship
18435 between the complex trigonometric and hyperbolic functions.  They
18436 are valid everywhere, including on the branch cuts.
18438 @smallexample
18439 sin(i*z)  = i*sinh(z)       arcsin(i*z)  = i*arcsinh(z)
18440 cos(i*z)  =   cosh(z)       arcsinh(i*z) = i*arcsin(z)
18441 tan(i*z)  = i*tanh(z)       arctan(i*z)  = i*arctanh(z)
18442 sinh(i*z) = i*sin(z)        cosh(i*z)    =   cos(z)
18443 @end smallexample
18445 The ``advanced math'' functions (gamma, Bessel, etc.@:) are also defined
18446 for general complex arguments, but their branch cuts and principal values
18447 are not rigorously specified at present.
18449 @node Random Numbers, Combinatorial Functions, Branch Cuts, Scientific Functions
18450 @section Random Numbers
18452 @noindent
18453 @kindex k r
18454 @pindex calc-random
18455 @tindex random
18456 The @kbd{k r} (@code{calc-random}) [@code{random}] command produces
18457 random numbers of various sorts.
18459 Given a positive numeric prefix argument @cite{M}, it produces a random
18460 integer @cite{N} in the range @c{$0 \le N < M$}
18461 @cite{0 <= N < M}.  Each of the @cite{M}
18462 values appears with equal probability.@refill
18464 With no numeric prefix argument, the @kbd{k r} command takes its argument
18465 from the stack instead.  Once again, if this is a positive integer @cite{M}
18466 the result is a random integer less than @cite{M}.  However, note that
18467 while numeric prefix arguments are limited to six digits or so, an @cite{M}
18468 taken from the stack can be arbitrarily large.  If @cite{M} is negative,
18469 the result is a random integer in the range @c{$M < N \le 0$}
18470 @cite{M < N <= 0}.
18472 If the value on the stack is a floating-point number @cite{M}, the result
18473 is a random floating-point number @cite{N} in the range @c{$0 \le N < M$}
18474 @cite{0 <= N < M}
18475 or @c{$M < N \le 0$}
18476 @cite{M < N <= 0}, according to the sign of @cite{M}.
18478 If @cite{M} is zero, the result is a Gaussian-distributed random real
18479 number; the distribution has a mean of zero and a standard deviation
18480 of one.  The algorithm used generates random numbers in pairs; thus,
18481 every other call to this function will be especially fast.
18483 If @cite{M} is an error form @c{$m$ @code{+/-} $\sigma$}
18484 @samp{m +/- s} where @i{m}
18485 and @c{$\sigma$}
18486 @i{s} are both real numbers, the result uses a Gaussian
18487 distribution with mean @i{m} and standard deviation @c{$\sigma$}
18488 @i{s}.
18490 If @cite{M} is an interval form, the lower and upper bounds specify the
18491 acceptable limits of the random numbers.  If both bounds are integers,
18492 the result is a random integer in the specified range.  If either bound
18493 is floating-point, the result is a random real number in the specified
18494 range.  If the interval is open at either end, the result will be sure
18495 not to equal that end value.  (This makes a big difference for integer
18496 intervals, but for floating-point intervals it's relatively minor:
18497 with a precision of 6, @samp{random([1.0..2.0))} will return any of one
18498 million numbers from 1.00000 to 1.99999; @samp{random([1.0..2.0])} may
18499 additionally return 2.00000, but the probability of this happening is
18500 extremely small.)
18502 If @cite{M} is a vector, the result is one element taken at random from
18503 the vector.  All elements of the vector are given equal probabilities.
18505 @vindex RandSeed
18506 The sequence of numbers produced by @kbd{k r} is completely random by
18507 default, i.e., the sequence is seeded each time you start Calc using
18508 the current time and other information.  You can get a reproducible
18509 sequence by storing a particular ``seed value'' in the Calc variable
18510 @code{RandSeed}.  Any integer will do for a seed; integers of from 1
18511 to 12 digits are good.  If you later store a different integer into
18512 @code{RandSeed}, Calc will switch to a different pseudo-random
18513 sequence.  If you ``unstore'' @code{RandSeed}, Calc will re-seed itself
18514 from the current time.  If you store the same integer that you used
18515 before back into @code{RandSeed}, you will get the exact same sequence
18516 of random numbers as before.
18518 @pindex calc-rrandom
18519 The @code{calc-rrandom} command (not on any key) produces a random real
18520 number between zero and one.  It is equivalent to @samp{random(1.0)}.
18522 @kindex k a
18523 @pindex calc-random-again
18524 The @kbd{k a} (@code{calc-random-again}) command produces another random
18525 number, re-using the most recent value of @cite{M}.  With a numeric
18526 prefix argument @var{n}, it produces @var{n} more random numbers using
18527 that value of @cite{M}.
18529 @kindex k h
18530 @pindex calc-shuffle
18531 @tindex shuffle
18532 The @kbd{k h} (@code{calc-shuffle}) command produces a vector of several
18533 random values with no duplicates.  The value on the top of the stack
18534 specifies the set from which the random values are drawn, and may be any
18535 of the @cite{M} formats described above.  The numeric prefix argument
18536 gives the length of the desired list.  (If you do not provide a numeric
18537 prefix argument, the length of the list is taken from the top of the
18538 stack, and @cite{M} from second-to-top.)
18540 If @cite{M} is a floating-point number, zero, or an error form (so
18541 that the random values are being drawn from the set of real numbers)
18542 there is little practical difference between using @kbd{k h} and using
18543 @kbd{k r} several times.  But if the set of possible values consists
18544 of just a few integers, or the elements of a vector, then there is
18545 a very real chance that multiple @kbd{k r}'s will produce the same
18546 number more than once.  The @kbd{k h} command produces a vector whose
18547 elements are always distinct.  (Actually, there is a slight exception:
18548 If @cite{M} is a vector, no given vector element will be drawn more
18549 than once, but if several elements of @cite{M} are equal, they may
18550 each make it into the result vector.)
18552 One use of @kbd{k h} is to rearrange a list at random.  This happens
18553 if the prefix argument is equal to the number of values in the list:
18554 @kbd{[1, 1.5, 2, 2.5, 3] 5 k h} might produce the permuted list
18555 @samp{[2.5, 1, 1.5, 3, 2]}.  As a convenient feature, if the argument
18556 @var{n} is negative it is replaced by the size of the set represented
18557 by @cite{M}.  Naturally, this is allowed only when @cite{M} specifies
18558 a small discrete set of possibilities.
18560 To do the equivalent of @kbd{k h} but with duplications allowed,
18561 given @cite{M} on the stack and with @var{n} just entered as a numeric
18562 prefix, use @kbd{v b} to build a vector of copies of @cite{M}, then use
18563 @kbd{V M k r} to ``map'' the normal @kbd{k r} function over the
18564 elements of this vector.  @xref{Matrix Functions}.
18566 @menu
18567 * Random Number Generator::     (Complete description of Calc's algorithm)
18568 @end menu
18570 @node Random Number Generator, , Random Numbers, Random Numbers
18571 @subsection Random Number Generator
18573 Calc's random number generator uses several methods to ensure that
18574 the numbers it produces are highly random.  Knuth's @emph{Art of
18575 Computer Programming}, Volume II, contains a thorough description
18576 of the theory of random number generators and their measurement and
18577 characterization.
18579 If @code{RandSeed} has no stored value, Calc calls Emacs' built-in
18580 @code{random} function to get a stream of random numbers, which it
18581 then treats in various ways to avoid problems inherent in the simple
18582 random number generators that many systems use to implement @code{random}.
18584 When Calc's random number generator is first invoked, it ``seeds''
18585 the low-level random sequence using the time of day, so that the
18586 random number sequence will be different every time you use Calc.
18588 Since Emacs Lisp doesn't specify the range of values that will be
18589 returned by its @code{random} function, Calc exercises the function
18590 several times to estimate the range.  When Calc subsequently uses
18591 the @code{random} function, it takes only 10 bits of the result
18592 near the most-significant end.  (It avoids at least the bottom
18593 four bits, preferably more, and also tries to avoid the top two
18594 bits.)  This strategy works well with the linear congruential
18595 generators that are typically used to implement @code{random}.
18597 If @code{RandSeed} contains an integer, Calc uses this integer to
18598 seed an ``additive congruential'' method (Knuth's algorithm 3.2.2A,
18599 computing @c{$X_{n-55} - X_{n-24}$}
18600 @cite{X_n-55 - X_n-24}).  This method expands the seed
18601 value into a large table which is maintained internally; the variable
18602 @code{RandSeed} is changed from, e.g., 42 to the vector @cite{[42]}
18603 to indicate that the seed has been absorbed into this table.  When
18604 @code{RandSeed} contains a vector, @kbd{k r} and related commands
18605 continue to use the same internal table as last time.  There is no
18606 way to extract the complete state of the random number generator
18607 so that you can restart it from any point; you can only restart it
18608 from the same initial seed value.  A simple way to restart from the
18609 same seed is to type @kbd{s r RandSeed} to get the seed vector,
18610 @kbd{v u} to unpack it back into a number, then @kbd{s t RandSeed}
18611 to reseed the generator with that number.
18613 Calc uses a ``shuffling'' method as described in algorithm 3.2.2B
18614 of Knuth.  It fills a table with 13 random 10-bit numbers.  Then,
18615 to generate a new random number, it uses the previous number to
18616 index into the table, picks the value it finds there as the new
18617 random number, then replaces that table entry with a new value
18618 obtained from a call to the base random number generator (either
18619 the additive congruential generator or the @code{random} function
18620 supplied by the system).  If there are any flaws in the base
18621 generator, shuffling will tend to even them out.  But if the system
18622 provides an excellent @code{random} function, shuffling will not
18623 damage its randomness.
18625 To create a random integer of a certain number of digits, Calc
18626 builds the integer three decimal digits at a time.  For each group
18627 of three digits, Calc calls its 10-bit shuffling random number generator
18628 (which returns a value from 0 to 1023); if the random value is 1000
18629 or more, Calc throws it out and tries again until it gets a suitable
18630 value.
18632 To create a random floating-point number with precision @var{p}, Calc
18633 simply creates a random @var{p}-digit integer and multiplies by
18634 @c{$10^{-p}$}
18635 @cite{10^-p}.  The resulting random numbers should be very clean, but note
18636 that relatively small numbers will have few significant random digits.
18637 In other words, with a precision of 12, you will occasionally get
18638 numbers on the order of @c{$10^{-9}$}
18639 @cite{10^-9} or @c{$10^{-10}$}
18640 @cite{10^-10}, but those numbers
18641 will only have two or three random digits since they correspond to small
18642 integers times @c{$10^{-12}$}
18643 @cite{10^-12}.
18645 To create a random integer in the interval @samp{[0 .. @var{m})}, Calc
18646 counts the digits in @var{m}, creates a random integer with three
18647 additional digits, then reduces modulo @var{m}.  Unless @var{m} is a
18648 power of ten the resulting values will be very slightly biased toward
18649 the lower numbers, but this bias will be less than 0.1%.  (For example,
18650 if @var{m} is 42, Calc will reduce a random integer less than 100000
18651 modulo 42 to get a result less than 42.  It is easy to show that the
18652 numbers 40 and 41 will be only 2380/2381 as likely to result from this
18653 modulo operation as numbers 39 and below.)  If @var{m} is a power of
18654 ten, however, the numbers should be completely unbiased.
18656 The Gaussian random numbers generated by @samp{random(0.0)} use the
18657 ``polar'' method described in Knuth section 3.4.1C.  This method
18658 generates a pair of Gaussian random numbers at a time, so only every
18659 other call to @samp{random(0.0)} will require significant calculations.
18661 @node Combinatorial Functions, Probability Distribution Functions, Random Numbers, Scientific Functions
18662 @section Combinatorial Functions
18664 @noindent
18665 Commands relating to combinatorics and number theory begin with the
18666 @kbd{k} key prefix.
18668 @kindex k g
18669 @pindex calc-gcd
18670 @tindex gcd
18671 The @kbd{k g} (@code{calc-gcd}) [@code{gcd}] command computes the
18672 Greatest Common Divisor of two integers.  It also accepts fractions;
18673 the GCD of two fractions is defined by taking the GCD of the
18674 numerators, and the LCM of the denominators.  This definition is
18675 consistent with the idea that @samp{a / gcd(a,x)} should yield an
18676 integer for any @samp{a} and @samp{x}.  For other types of arguments,
18677 the operation is left in symbolic form.@refill
18679 @kindex k l
18680 @pindex calc-lcm
18681 @tindex lcm
18682 The @kbd{k l} (@code{calc-lcm}) [@code{lcm}] command computes the
18683 Least Common Multiple of two integers or fractions.  The product of
18684 the LCM and GCD of two numbers is equal to the product of the
18685 numbers.@refill
18687 @kindex k E
18688 @pindex calc-extended-gcd
18689 @tindex egcd
18690 The @kbd{k E} (@code{calc-extended-gcd}) [@code{egcd}] command computes
18691 the GCD of two integers @cite{x} and @cite{y} and returns a vector
18692 @cite{[g, a, b]} where @c{$g = \gcd(x,y) = a x + b y$}
18693 @cite{g = gcd(x,y) = a x + b y}.
18695 @kindex !
18696 @pindex calc-factorial
18697 @tindex fact
18698 @c @mindex @null
18699 @tindex !
18700 The @kbd{!} (@code{calc-factorial}) [@code{fact}] command computes the
18701 factorial of the number at the top of the stack.  If the number is an
18702 integer, the result is an exact integer.  If the number is an
18703 integer-valued float, the result is a floating-point approximation.  If
18704 the number is a non-integral real number, the generalized factorial is used,
18705 as defined by the Euler Gamma function.  Please note that computation of
18706 large factorials can be slow; using floating-point format will help
18707 since fewer digits must be maintained.  The same is true of many of
18708 the commands in this section.@refill
18710 @kindex k d
18711 @pindex calc-double-factorial
18712 @tindex dfact
18713 @c @mindex @null
18714 @tindex !!
18715 The @kbd{k d} (@code{calc-double-factorial}) [@code{dfact}] command
18716 computes the ``double factorial'' of an integer.  For an even integer,
18717 this is the product of even integers from 2 to @cite{N}.  For an odd
18718 integer, this is the product of odd integers from 3 to @cite{N}.  If
18719 the argument is an integer-valued float, the result is a floating-point
18720 approximation.  This function is undefined for negative even integers.
18721 The notation @cite{N!!} is also recognized for double factorials.@refill
18723 @kindex k c
18724 @pindex calc-choose
18725 @tindex choose
18726 The @kbd{k c} (@code{calc-choose}) [@code{choose}] command computes the
18727 binomial coefficient @cite{N}-choose-@cite{M}, where @cite{M} is the number
18728 on the top of the stack and @cite{N} is second-to-top.  If both arguments
18729 are integers, the result is an exact integer.  Otherwise, the result is a
18730 floating-point approximation.  The binomial coefficient is defined for all
18731 real numbers by @c{$N! \over M! (N-M)!\,$}
18732 @cite{N! / M! (N-M)!}.
18734 @kindex H k c
18735 @pindex calc-perm
18736 @tindex perm
18737 @ifinfo
18738 The @kbd{H k c} (@code{calc-perm}) [@code{perm}] command computes the
18739 number-of-permutations function @cite{N! / (N-M)!}.
18740 @end ifinfo
18741 @tex
18742 The \kbd{H k c} (\code{calc-perm}) [\code{perm}] command computes the
18743 number-of-perm\-utations function $N! \over (N-M)!\,$.
18744 @end tex
18746 @kindex k b
18747 @kindex H k b
18748 @pindex calc-bernoulli-number
18749 @tindex bern
18750 The @kbd{k b} (@code{calc-bernoulli-number}) [@code{bern}] command
18751 computes a given Bernoulli number.  The value at the top of the stack
18752 is a nonnegative integer @cite{n} that specifies which Bernoulli number
18753 is desired.  The @kbd{H k b} command computes a Bernoulli polynomial,
18754 taking @cite{n} from the second-to-top position and @cite{x} from the
18755 top of the stack.  If @cite{x} is a variable or formula the result is
18756 a polynomial in @cite{x}; if @cite{x} is a number the result is a number.
18758 @kindex k e
18759 @kindex H k e
18760 @pindex calc-euler-number
18761 @tindex euler
18762 The @kbd{k e} (@code{calc-euler-number}) [@code{euler}] command similarly
18763 computes an Euler number, and @w{@kbd{H k e}} computes an Euler polynomial.
18764 Bernoulli and Euler numbers occur in the Taylor expansions of several
18765 functions.
18767 @kindex k s
18768 @kindex H k s
18769 @pindex calc-stirling-number
18770 @tindex stir1
18771 @tindex stir2
18772 The @kbd{k s} (@code{calc-stirling-number}) [@code{stir1}] command
18773 computes a Stirling number of the first kind@c{ $n \brack m$}
18774 @asis{}, given two integers
18775 @cite{n} and @cite{m} on the stack.  The @kbd{H k s} [@code{stir2}]
18776 command computes a Stirling number of the second kind@c{ $n \brace m$}
18777 @asis{}.  These are
18778 the number of @cite{m}-cycle permutations of @cite{n} objects, and
18779 the number of ways to partition @cite{n} objects into @cite{m}
18780 non-empty sets, respectively.
18782 @kindex k p
18783 @pindex calc-prime-test
18784 @cindex Primes
18785 The @kbd{k p} (@code{calc-prime-test}) command checks if the integer on
18786 the top of the stack is prime.  For integers less than eight million, the
18787 answer is always exact and reasonably fast.  For larger integers, a
18788 probabilistic method is used (see Knuth vol. II, section 4.5.4, algorithm P).
18789 The number is first checked against small prime factors (up to 13).  Then,
18790 any number of iterations of the algorithm are performed.  Each step either
18791 discovers that the number is non-prime, or substantially increases the
18792 certainty that the number is prime.  After a few steps, the chance that
18793 a number was mistakenly described as prime will be less than one percent.
18794 (Indeed, this is a worst-case estimate of the probability; in practice
18795 even a single iteration is quite reliable.)  After the @kbd{k p} command,
18796 the number will be reported as definitely prime or non-prime if possible,
18797 or otherwise ``probably'' prime with a certain probability of error.
18799 @c @starindex
18800 @tindex prime
18801 The normal @kbd{k p} command performs one iteration of the primality
18802 test.  Pressing @kbd{k p} repeatedly for the same integer will perform
18803 additional iterations.  Also, @kbd{k p} with a numeric prefix performs
18804 the specified number of iterations.  There is also an algebraic function
18805 @samp{prime(n)} or @samp{prime(n,iters)} which returns 1 if @cite{n}
18806 is (probably) prime and 0 if not.
18808 @kindex k f
18809 @pindex calc-prime-factors
18810 @tindex prfac
18811 The @kbd{k f} (@code{calc-prime-factors}) [@code{prfac}] command
18812 attempts to decompose an integer into its prime factors.  For numbers up
18813 to 25 million, the answer is exact although it may take some time.  The
18814 result is a vector of the prime factors in increasing order.  For larger
18815 inputs, prime factors above 5000 may not be found, in which case the
18816 last number in the vector will be an unfactored integer greater than 25
18817 million (with a warning message).  For negative integers, the first
18818 element of the list will be @i{-1}.  For inputs @i{-1}, @i{0}, and
18819 @i{1}, the result is a list of the same number.
18821 @kindex k n
18822 @pindex calc-next-prime
18823 @c @mindex nextpr@idots
18824 @tindex nextprime
18825 The @kbd{k n} (@code{calc-next-prime}) [@code{nextprime}] command finds
18826 the next prime above a given number.  Essentially, it searches by calling
18827 @code{calc-prime-test} on successive integers until it finds one that
18828 passes the test.  This is quite fast for integers less than eight million,
18829 but once the probabilistic test comes into play the search may be rather
18830 slow.  Ordinarily this command stops for any prime that passes one iteration
18831 of the primality test.  With a numeric prefix argument, a number must pass
18832 the specified number of iterations before the search stops.  (This only
18833 matters when searching above eight million.)  You can always use additional
18834 @kbd{k p} commands to increase your certainty that the number is indeed
18835 prime.
18837 @kindex I k n
18838 @pindex calc-prev-prime
18839 @c @mindex prevpr@idots
18840 @tindex prevprime
18841 The @kbd{I k n} (@code{calc-prev-prime}) [@code{prevprime}] command
18842 analogously finds the next prime less than a given number.
18844 @kindex k t
18845 @pindex calc-totient
18846 @tindex totient
18847 The @kbd{k t} (@code{calc-totient}) [@code{totient}] command computes the
18848 Euler ``totient'' function@c{ $\phi(n)$}
18849 @asis{}, the number of integers less than @cite{n} which
18850 are relatively prime to @cite{n}.
18852 @kindex k m
18853 @pindex calc-moebius
18854 @tindex moebius
18855 The @kbd{k m} (@code{calc-moebius}) [@code{moebius}] command computes the
18856 @c{M\"obius $\mu$}
18857 @asis{Moebius ``mu''} function.  If the input number is a product of @cite{k}
18858 distinct factors, this is @cite{(-1)^k}.  If the input number has any
18859 duplicate factors (i.e., can be divided by the same prime more than once),
18860 the result is zero.
18862 @node Probability Distribution Functions, , Combinatorial Functions, Scientific Functions
18863 @section Probability Distribution Functions
18865 @noindent
18866 The functions in this section compute various probability distributions.
18867 For continuous distributions, this is the integral of the probability
18868 density function from @cite{x} to infinity.  (These are the ``upper
18869 tail'' distribution functions; there are also corresponding ``lower
18870 tail'' functions which integrate from minus infinity to @cite{x}.)
18871 For discrete distributions, the upper tail function gives the sum
18872 from @cite{x} to infinity; the lower tail function gives the sum
18873 from minus infinity up to, but not including,@w{ }@cite{x}.
18875 To integrate from @cite{x} to @cite{y}, just use the distribution
18876 function twice and subtract.  For example, the probability that a
18877 Gaussian random variable with mean 2 and standard deviation 1 will
18878 lie in the range from 2.5 to 2.8 is @samp{utpn(2.5,2,1) - utpn(2.8,2,1)}
18879 (``the probability that it is greater than 2.5, but not greater than 2.8''),
18880 or equivalently @samp{ltpn(2.8,2,1) - ltpn(2.5,2,1)}.
18882 @kindex k B
18883 @kindex I k B
18884 @pindex calc-utpb
18885 @tindex utpb
18886 @tindex ltpb
18887 The @kbd{k B} (@code{calc-utpb}) [@code{utpb}] function uses the
18888 binomial distribution.  Push the parameters @var{n}, @var{p}, and
18889 then @var{x} onto the stack; the result (@samp{utpb(x,n,p)}) is the
18890 probability that an event will occur @var{x} or more times out
18891 of @var{n} trials, if its probability of occurring in any given
18892 trial is @var{p}.  The @kbd{I k B} [@code{ltpb}] function is
18893 the probability that the event will occur fewer than @var{x} times.
18895 The other probability distribution functions similarly take the
18896 form @kbd{k @var{X}} (@code{calc-utp@var{x}}) [@code{utp@var{x}}]
18897 and @kbd{I k @var{X}} [@code{ltp@var{x}}], for various letters
18898 @var{x}.  The arguments to the algebraic functions are the value of
18899 the random variable first, then whatever other parameters define the
18900 distribution.  Note these are among the few Calc functions where the
18901 order of the arguments in algebraic form differs from the order of
18902 arguments as found on the stack.  (The random variable comes last on
18903 the stack, so that you can type, e.g., @kbd{2 @key{RET} 1 @key{RET} 2.5
18904 k N M-@key{RET} @key{DEL} 2.8 k N -}, using @kbd{M-@key{RET} @key{DEL}} to
18905 recover the original arguments but substitute a new value for @cite{x}.)
18907 @kindex k C
18908 @pindex calc-utpc
18909 @tindex utpc
18910 @c @mindex @idots
18911 @kindex I k C
18912 @c @mindex @null
18913 @tindex ltpc
18914 The @samp{utpc(x,v)} function uses the chi-square distribution with
18915 @c{$\nu$}
18916 @cite{v} degrees of freedom.  It is the probability that a model is
18917 correct if its chi-square statistic is @cite{x}.
18919 @kindex k F
18920 @pindex calc-utpf
18921 @tindex utpf
18922 @c @mindex @idots
18923 @kindex I k F
18924 @c @mindex @null
18925 @tindex ltpf
18926 The @samp{utpf(F,v1,v2)} function uses the F distribution, used in
18927 various statistical tests.  The parameters @c{$\nu_1$}
18928 @cite{v1} and @c{$\nu_2$}
18929 @cite{v2}
18930 are the degrees of freedom in the numerator and denominator,
18931 respectively, used in computing the statistic @cite{F}.
18933 @kindex k N
18934 @pindex calc-utpn
18935 @tindex utpn
18936 @c @mindex @idots
18937 @kindex I k N
18938 @c @mindex @null
18939 @tindex ltpn
18940 The @samp{utpn(x,m,s)} function uses a normal (Gaussian) distribution
18941 with mean @cite{m} and standard deviation @c{$\sigma$}
18942 @cite{s}.  It is the
18943 probability that such a normal-distributed random variable would
18944 exceed @cite{x}.
18946 @kindex k P
18947 @pindex calc-utpp
18948 @tindex utpp
18949 @c @mindex @idots
18950 @kindex I k P
18951 @c @mindex @null
18952 @tindex ltpp
18953 The @samp{utpp(n,x)} function uses a Poisson distribution with
18954 mean @cite{x}.  It is the probability that @cite{n} or more such
18955 Poisson random events will occur.
18957 @kindex k T
18958 @pindex calc-ltpt
18959 @tindex utpt
18960 @c @mindex @idots
18961 @kindex I k T
18962 @c @mindex @null
18963 @tindex ltpt
18964 The @samp{utpt(t,v)} function uses the Student's ``t'' distribution
18965 with @c{$\nu$}
18966 @cite{v} degrees of freedom.  It is the probability that a
18967 t-distributed random variable will be greater than @cite{t}.
18968 (Note:  This computes the distribution function @c{$A(t|\nu)$}
18969 @cite{A(t|v)}
18970 where @c{$A(0|\nu) = 1$}
18971 @cite{A(0|v) = 1} and @c{$A(\infty|\nu) \to 0$}
18972 @cite{A(inf|v) -> 0}.  The
18973 @code{UTPT} operation on the HP-48 uses a different definition
18974 which returns half of Calc's value:  @samp{UTPT(t,v) = .5*utpt(t,v)}.)
18976 While Calc does not provide inverses of the probability distribution
18977 functions, the @kbd{a R} command can be used to solve for the inverse.
18978 Since the distribution functions are monotonic, @kbd{a R} is guaranteed
18979 to be able to find a solution given any initial guess.
18980 @xref{Numerical Solutions}.
18982 @node Matrix Functions, Algebra, Scientific Functions, Top
18983 @chapter Vector/Matrix Functions
18985 @noindent
18986 Many of the commands described here begin with the @kbd{v} prefix.
18987 (For convenience, the shift-@kbd{V} prefix is equivalent to @kbd{v}.)
18988 The commands usually apply to both plain vectors and matrices; some
18989 apply only to matrices or only to square matrices.  If the argument
18990 has the wrong dimensions the operation is left in symbolic form.
18992 Vectors are entered and displayed using @samp{[a,b,c]} notation.
18993 Matrices are vectors of which all elements are vectors of equal length.
18994 (Though none of the standard Calc commands use this concept, a
18995 three-dimensional matrix or rank-3 tensor could be defined as a
18996 vector of matrices, and so on.)
18998 @menu
18999 * Packing and Unpacking::
19000 * Building Vectors::
19001 * Extracting Elements::
19002 * Manipulating Vectors::
19003 * Vector and Matrix Arithmetic::
19004 * Set Operations::
19005 * Statistical Operations::
19006 * Reducing and Mapping::
19007 * Vector and Matrix Formats::
19008 @end menu
19010 @node Packing and Unpacking, Building Vectors, Matrix Functions, Matrix Functions
19011 @section Packing and Unpacking
19013 @noindent
19014 Calc's ``pack'' and ``unpack'' commands collect stack entries to build
19015 composite objects such as vectors and complex numbers.  They are
19016 described in this chapter because they are most often used to build
19017 vectors.
19019 @kindex v p
19020 @pindex calc-pack
19021 The @kbd{v p} (@code{calc-pack}) [@code{pack}] command collects several
19022 elements from the stack into a matrix, complex number, HMS form, error
19023 form, etc.  It uses a numeric prefix argument to specify the kind of
19024 object to be built; this argument is referred to as the ``packing mode.''
19025 If the packing mode is a nonnegative integer, a vector of that
19026 length is created.  For example, @kbd{C-u 5 v p} will pop the top
19027 five stack elements and push back a single vector of those five
19028 elements.  (@kbd{C-u 0 v p} simply creates an empty vector.)
19030 The same effect can be had by pressing @kbd{[} to push an incomplete
19031 vector on the stack, using @key{TAB} (@code{calc-roll-down}) to sneak
19032 the incomplete object up past a certain number of elements, and
19033 then pressing @kbd{]} to complete the vector.
19035 Negative packing modes create other kinds of composite objects:
19037 @table @cite
19038 @item -1
19039 Two values are collected to build a complex number.  For example,
19040 @kbd{5 @key{RET} 7 C-u -1 v p} creates the complex number
19041 @cite{(5, 7)}.  The result is always a rectangular complex
19042 number.  The two input values must both be real numbers,
19043 i.e., integers, fractions, or floats.  If they are not, Calc
19044 will instead build a formula like @samp{a + (0, 1) b}.  (The
19045 other packing modes also create a symbolic answer if the
19046 components are not suitable.)
19048 @item -2
19049 Two values are collected to build a polar complex number.
19050 The first is the magnitude; the second is the phase expressed
19051 in either degrees or radians according to the current angular
19052 mode.
19054 @item -3
19055 Three values are collected into an HMS form.  The first
19056 two values (hours and minutes) must be integers or
19057 integer-valued floats.  The third value may be any real
19058 number.
19060 @item -4
19061 Two values are collected into an error form.  The inputs
19062 may be real numbers or formulas.
19064 @item -5
19065 Two values are collected into a modulo form.  The inputs
19066 must be real numbers.
19068 @item -6
19069 Two values are collected into the interval @samp{[a .. b]}.
19070 The inputs may be real numbers, HMS or date forms, or formulas.
19072 @item -7
19073 Two values are collected into the interval @samp{[a .. b)}.
19075 @item -8
19076 Two values are collected into the interval @samp{(a .. b]}.
19078 @item -9
19079 Two values are collected into the interval @samp{(a .. b)}.
19081 @item -10
19082 Two integer values are collected into a fraction.
19084 @item -11
19085 Two values are collected into a floating-point number.
19086 The first is the mantissa; the second, which must be an
19087 integer, is the exponent.  The result is the mantissa
19088 times ten to the power of the exponent.
19090 @item -12
19091 This is treated the same as @i{-11} by the @kbd{v p} command.
19092 When unpacking, @i{-12} specifies that a floating-point mantissa
19093 is desired.
19095 @item -13
19096 A real number is converted into a date form.
19098 @item -14
19099 Three numbers (year, month, day) are packed into a pure date form.
19101 @item -15
19102 Six numbers are packed into a date/time form.
19103 @end table
19105 With any of the two-input negative packing modes, either or both
19106 of the inputs may be vectors.  If both are vectors of the same
19107 length, the result is another vector made by packing corresponding
19108 elements of the input vectors.  If one input is a vector and the
19109 other is a plain number, the number is packed along with each vector
19110 element to produce a new vector.  For example, @kbd{C-u -4 v p}
19111 could be used to convert a vector of numbers and a vector of errors
19112 into a single vector of error forms; @kbd{C-u -5 v p} could convert
19113 a vector of numbers and a single number @var{M} into a vector of
19114 numbers modulo @var{M}.
19116 If you don't give a prefix argument to @kbd{v p}, it takes
19117 the packing mode from the top of the stack.  The elements to
19118 be packed then begin at stack level 2.  Thus
19119 @kbd{1 @key{RET} 2 @key{RET} 4 n v p} is another way to
19120 enter the error form @samp{1 +/- 2}.
19122 If the packing mode taken from the stack is a vector, the result is a
19123 matrix with the dimensions specified by the elements of the vector,
19124 which must each be integers.  For example, if the packing mode is
19125 @samp{[2, 3]}, then six numbers will be taken from the stack and
19126 returned in the form @samp{[@w{[a, b, c]}, [d, e, f]]}.
19128 If any elements of the vector are negative, other kinds of
19129 packing are done at that level as described above.  For
19130 example, @samp{[2, 3, -4]} takes 12 objects and creates a
19131 @c{$2\times3$}
19132 @asis{2x3} matrix of error forms: @samp{[[a +/- b, c +/- d ... ]]}.
19133 Also, @samp{[-4, -10]} will convert four integers into an
19134 error form consisting of two fractions:  @samp{a:b +/- c:d}.
19136 @c @starindex
19137 @tindex pack
19138 There is an equivalent algebraic function,
19139 @samp{pack(@var{mode}, @var{items})} where @var{mode} is a
19140 packing mode (an integer or a vector of integers) and @var{items}
19141 is a vector of objects to be packed (re-packed, really) according
19142 to that mode.  For example, @samp{pack([3, -4], [a,b,c,d,e,f])}
19143 yields @samp{[a +/- b, @w{c +/- d}, e +/- f]}.  The function is
19144 left in symbolic form if the packing mode is illegal, or if the
19145 number of data items does not match the number of items required
19146 by the mode.
19148 @kindex v u
19149 @pindex calc-unpack
19150 The @kbd{v u} (@code{calc-unpack}) command takes the vector, complex
19151 number, HMS form, or other composite object on the top of the stack and
19152 ``unpacks'' it, pushing each of its elements onto the stack as separate
19153 objects.  Thus, it is the ``inverse'' of @kbd{v p}.  If the value
19154 at the top of the stack is a formula, @kbd{v u} unpacks it by pushing
19155 each of the arguments of the top-level operator onto the stack.
19157 You can optionally give a numeric prefix argument to @kbd{v u}
19158 to specify an explicit (un)packing mode.  If the packing mode is
19159 negative and the input is actually a vector or matrix, the result
19160 will be two or more similar vectors or matrices of the elements.
19161 For example, given the vector @samp{[@w{a +/- b}, c^2, d +/- 7]},
19162 the result of @kbd{C-u -4 v u} will be the two vectors
19163 @samp{[a, c^2, d]} and @w{@samp{[b, 0, 7]}}.
19165 Note that the prefix argument can have an effect even when the input is
19166 not a vector.  For example, if the input is the number @i{-5}, then
19167 @kbd{c-u -1 v u} yields @i{-5} and 0 (the components of @i{-5}
19168 when viewed as a rectangular complex number); @kbd{C-u -2 v u} yields 5
19169 and 180 (assuming degrees mode); and @kbd{C-u -10 v u} yields @i{-5}
19170 and 1 (the numerator and denominator of @i{-5}, viewed as a rational
19171 number).  Plain @kbd{v u} with this input would complain that the input
19172 is not a composite object.
19174 Unpacking mode @i{-11} converts a float into an integer mantissa and
19175 an integer exponent, where the mantissa is not divisible by 10
19176 (except that 0.0 is represented by a mantissa and exponent of 0).
19177 Unpacking mode @i{-12} converts a float into a floating-point mantissa
19178 and integer exponent, where the mantissa (for non-zero numbers)
19179 is guaranteed to lie in the range [1 .. 10).  In both cases,
19180 the mantissa is shifted left or right (and the exponent adjusted
19181 to compensate) in order to satisfy these constraints.
19183 Positive unpacking modes are treated differently than for @kbd{v p}.
19184 A mode of 1 is much like plain @kbd{v u} with no prefix argument,
19185 except that in addition to the components of the input object,
19186 a suitable packing mode to re-pack the object is also pushed.
19187 Thus, @kbd{C-u 1 v u} followed by @kbd{v p} will re-build the
19188 original object.
19190 A mode of 2 unpacks two levels of the object; the resulting
19191 re-packing mode will be a vector of length 2.  This might be used
19192 to unpack a matrix, say, or a vector of error forms.  Higher
19193 unpacking modes unpack the input even more deeply.
19195 @c @starindex
19196 @tindex unpack
19197 There are two algebraic functions analogous to @kbd{v u}.
19198 The @samp{unpack(@var{mode}, @var{item})} function unpacks the
19199 @var{item} using the given @var{mode}, returning the result as
19200 a vector of components.  Here the @var{mode} must be an
19201 integer, not a vector.  For example, @samp{unpack(-4, a +/- b)}
19202 returns @samp{[a, b]}, as does @samp{unpack(1, a +/- b)}.
19204 @c @starindex
19205 @tindex unpackt
19206 The @code{unpackt} function is like @code{unpack} but instead
19207 of returning a simple vector of items, it returns a vector of
19208 two things:  The mode, and the vector of items.  For example,
19209 @samp{unpackt(1, 2:3 +/- 1:4)} returns @samp{[-4, [2:3, 1:4]]},
19210 and @samp{unpackt(2, 2:3 +/- 1:4)} returns @samp{[[-4, -10], [2, 3, 1, 4]]}.
19211 The identity for re-building the original object is
19212 @samp{apply(pack, unpackt(@var{n}, @var{x})) = @var{x}}.  (The
19213 @code{apply} function builds a function call given the function
19214 name and a vector of arguments.)
19216 @cindex Numerator of a fraction, extracting
19217 Subscript notation is a useful way to extract a particular part
19218 of an object.  For example, to get the numerator of a rational
19219 number, you can use @samp{unpack(-10, @var{x})_1}.
19221 @node Building Vectors, Extracting Elements, Packing and Unpacking, Matrix Functions
19222 @section Building Vectors
19224 @noindent
19225 Vectors and matrices can be added,
19226 subtracted, multiplied, and divided; @pxref{Basic Arithmetic}.@refill
19228 @kindex |
19229 @pindex calc-concat
19230 @c @mindex @null
19231 @tindex |
19232 The @kbd{|} (@code{calc-concat}) command ``concatenates'' two vectors
19233 into one.  For example, after @kbd{@w{[ 1 , 2 ]} [ 3 , 4 ] |}, the stack
19234 will contain the single vector @samp{[1, 2, 3, 4]}.  If the arguments
19235 are matrices, the rows of the first matrix are concatenated with the
19236 rows of the second.  (In other words, two matrices are just two vectors
19237 of row-vectors as far as @kbd{|} is concerned.)
19239 If either argument to @kbd{|} is a scalar (a non-vector), it is treated
19240 like a one-element vector for purposes of concatenation:  @kbd{1 [ 2 , 3 ] |}
19241 produces the vector @samp{[1, 2, 3]}.  Likewise, if one argument is a
19242 matrix and the other is a plain vector, the vector is treated as a
19243 one-row matrix.
19245 @kindex H |
19246 @tindex append
19247 The @kbd{H |} (@code{calc-append}) [@code{append}] command concatenates
19248 two vectors without any special cases.  Both inputs must be vectors.
19249 Whether or not they are matrices is not taken into account.  If either
19250 argument is a scalar, the @code{append} function is left in symbolic form.
19251 See also @code{cons} and @code{rcons} below.
19253 @kindex I |
19254 @kindex H I |
19255 The @kbd{I |} and @kbd{H I |} commands are similar, but they use their
19256 two stack arguments in the opposite order.  Thus @kbd{I |} is equivalent
19257 to @kbd{TAB |}, but possibly more convenient and also a bit faster.
19259 @kindex v d
19260 @pindex calc-diag
19261 @tindex diag
19262 The @kbd{v d} (@code{calc-diag}) [@code{diag}] function builds a diagonal
19263 square matrix.  The optional numeric prefix gives the number of rows
19264 and columns in the matrix.  If the value at the top of the stack is a
19265 vector, the elements of the vector are used as the diagonal elements; the
19266 prefix, if specified, must match the size of the vector.  If the value on
19267 the stack is a scalar, it is used for each element on the diagonal, and
19268 the prefix argument is required.
19270 To build a constant square matrix, e.g., a @c{$3\times3$}
19271 @asis{3x3} matrix filled with ones,
19272 use @kbd{0 M-3 v d 1 +}, i.e., build a zero matrix first and then add a
19273 constant value to that matrix.  (Another alternative would be to use
19274 @kbd{v b} and @kbd{v a}; see below.)
19276 @kindex v i
19277 @pindex calc-ident
19278 @tindex idn
19279 The @kbd{v i} (@code{calc-ident}) [@code{idn}] function builds an identity
19280 matrix of the specified size.  It is a convenient form of @kbd{v d}
19281 where the diagonal element is always one.  If no prefix argument is given,
19282 this command prompts for one.
19284 In algebraic notation, @samp{idn(a,n)} acts much like @samp{diag(a,n)},
19285 except that @cite{a} is required to be a scalar (non-vector) quantity.
19286 If @cite{n} is omitted, @samp{idn(a)} represents @cite{a} times an
19287 identity matrix of unknown size.  Calc can operate algebraically on
19288 such generic identity matrices, and if one is combined with a matrix
19289 whose size is known, it is converted automatically to an identity
19290 matrix of a suitable matching size.  The @kbd{v i} command with an
19291 argument of zero creates a generic identity matrix, @samp{idn(1)}.
19292 Note that in dimensioned matrix mode (@pxref{Matrix Mode}), generic
19293 identity matrices are immediately expanded to the current default
19294 dimensions.
19296 @kindex v x
19297 @pindex calc-index
19298 @tindex index
19299 The @kbd{v x} (@code{calc-index}) [@code{index}] function builds a vector
19300 of consecutive integers from 1 to @var{n}, where @var{n} is the numeric
19301 prefix argument.  If you do not provide a prefix argument, you will be
19302 prompted to enter a suitable number.  If @var{n} is negative, the result
19303 is a vector of negative integers from @var{n} to @i{-1}.
19305 With a prefix argument of just @kbd{C-u}, the @kbd{v x} command takes
19306 three values from the stack: @var{n}, @var{start}, and @var{incr} (with
19307 @var{incr} at top-of-stack).  Counting starts at @var{start} and increases
19308 by @var{incr} for successive vector elements.  If @var{start} or @var{n}
19309 is in floating-point format, the resulting vector elements will also be
19310 floats.  Note that @var{start} and @var{incr} may in fact be any kind
19311 of numbers or formulas.
19313 When @var{start} and @var{incr} are specified, a negative @var{n} has a
19314 different interpretation:  It causes a geometric instead of arithmetic
19315 sequence to be generated.  For example, @samp{index(-3, a, b)} produces
19316 @samp{[a, a b, a b^2]}.  If you omit @var{incr} in the algebraic form,
19317 @samp{index(@var{n}, @var{start})}, the default value for @var{incr}
19318 is one for positive @var{n} or two for negative @var{n}.
19320 @kindex v b
19321 @pindex calc-build-vector
19322 @tindex cvec
19323 The @kbd{v b} (@code{calc-build-vector}) [@code{cvec}] function builds a
19324 vector of @var{n} copies of the value on the top of the stack, where @var{n}
19325 is the numeric prefix argument.  In algebraic formulas, @samp{cvec(x,n,m)}
19326 can also be used to build an @var{n}-by-@var{m} matrix of copies of @var{x}.
19327 (Interactively, just use @kbd{v b} twice: once to build a row, then again
19328 to build a matrix of copies of that row.)
19330 @kindex v h
19331 @kindex I v h
19332 @pindex calc-head
19333 @pindex calc-tail
19334 @tindex head
19335 @tindex tail
19336 The @kbd{v h} (@code{calc-head}) [@code{head}] function returns the first
19337 element of a vector.  The @kbd{I v h} (@code{calc-tail}) [@code{tail}]
19338 function returns the vector with its first element removed.  In both
19339 cases, the argument must be a non-empty vector.
19341 @kindex v k
19342 @pindex calc-cons
19343 @tindex cons
19344 The @kbd{v k} (@code{calc-cons}) [@code{cons}] function takes a value @var{h}
19345 and a vector @var{t} from the stack, and produces the vector whose head is
19346 @var{h} and whose tail is @var{t}.  This is similar to @kbd{|}, except
19347 if @var{h} is itself a vector, @kbd{|} will concatenate the two vectors
19348 whereas @code{cons} will insert @var{h} at the front of the vector @var{t}.
19350 @kindex H v h
19351 @tindex rhead
19352 @c @mindex @idots
19353 @kindex H I v h
19354 @c @mindex @null
19355 @kindex H v k
19356 @c @mindex @null
19357 @tindex rtail
19358 @c @mindex @null
19359 @tindex rcons
19360 Each of these three functions also accepts the Hyperbolic flag [@code{rhead},
19361 @code{rtail}, @code{rcons}] in which case @var{t} instead represents
19362 the @emph{last} single element of the vector, with @var{h}
19363 representing the remainder of the vector.  Thus the vector
19364 @samp{[a, b, c, d] = cons(a, [b, c, d]) = rcons([a, b, c], d)}.
19365 Also, @samp{head([a, b, c, d]) = a}, @samp{tail([a, b, c, d]) = [b, c, d]},
19366 @samp{rhead([a, b, c, d]) = [a, b, c]}, and @samp{rtail([a, b, c, d]) = d}.
19368 @node Extracting Elements, Manipulating Vectors, Building Vectors, Matrix Functions
19369 @section Extracting Vector Elements
19371 @noindent
19372 @kindex v r
19373 @pindex calc-mrow
19374 @tindex mrow
19375 The @kbd{v r} (@code{calc-mrow}) [@code{mrow}] command extracts one row of
19376 the matrix on the top of the stack, or one element of the plain vector on
19377 the top of the stack.  The row or element is specified by the numeric
19378 prefix argument; the default is to prompt for the row or element number.
19379 The matrix or vector is replaced by the specified row or element in the
19380 form of a vector or scalar, respectively.
19382 @cindex Permutations, applying
19383 With a prefix argument of @kbd{C-u} only, @kbd{v r} takes the index of
19384 the element or row from the top of the stack, and the vector or matrix
19385 from the second-to-top position.  If the index is itself a vector of
19386 integers, the result is a vector of the corresponding elements of the
19387 input vector, or a matrix of the corresponding rows of the input matrix.
19388 This command can be used to obtain any permutation of a vector.
19390 With @kbd{C-u}, if the index is an interval form with integer components,
19391 it is interpreted as a range of indices and the corresponding subvector or
19392 submatrix is returned.
19394 @cindex Subscript notation
19395 @kindex a _
19396 @pindex calc-subscript
19397 @tindex subscr
19398 @tindex _
19399 Subscript notation in algebraic formulas (@samp{a_b}) stands for the
19400 Calc function @code{subscr}, which is synonymous with @code{mrow}.
19401 Thus, @samp{[x, y, z]_k} produces @cite{x}, @cite{y}, or @cite{z} if
19402 @cite{k} is one, two, or three, respectively.  A double subscript
19403 (@samp{M_i_j}, equivalent to @samp{subscr(subscr(M, i), j)}) will
19404 access the element at row @cite{i}, column @cite{j} of a matrix.
19405 The @kbd{a _} (@code{calc-subscript}) command creates a subscript
19406 formula @samp{a_b} out of two stack entries.  (It is on the @kbd{a}
19407 ``algebra'' prefix because subscripted variables are often used
19408 purely as an algebraic notation.)
19410 @tindex mrrow
19411 Given a negative prefix argument, @kbd{v r} instead deletes one row or
19412 element from the matrix or vector on the top of the stack.  Thus
19413 @kbd{C-u 2 v r} replaces a matrix with its second row, but @kbd{C-u -2 v r}
19414 replaces the matrix with the same matrix with its second row removed.
19415 In algebraic form this function is called @code{mrrow}.
19417 @tindex getdiag
19418 Given a prefix argument of zero, @kbd{v r} extracts the diagonal elements
19419 of a square matrix in the form of a vector.  In algebraic form this
19420 function is called @code{getdiag}.
19422 @kindex v c
19423 @pindex calc-mcol
19424 @tindex mcol
19425 @tindex mrcol
19426 The @kbd{v c} (@code{calc-mcol}) [@code{mcol} or @code{mrcol}] command is
19427 the analogous operation on columns of a matrix.  Given a plain vector
19428 it extracts (or removes) one element, just like @kbd{v r}.  If the
19429 index in @kbd{C-u v c} is an interval or vector and the argument is a
19430 matrix, the result is a submatrix with only the specified columns
19431 retained (and possibly permuted in the case of a vector index).@refill
19433 To extract a matrix element at a given row and column, use @kbd{v r} to
19434 extract the row as a vector, then @kbd{v c} to extract the column element
19435 from that vector.  In algebraic formulas, it is often more convenient to
19436 use subscript notation:  @samp{m_i_j} gives row @cite{i}, column @cite{j}
19437 of matrix @cite{m}.
19439 @kindex v s
19440 @pindex calc-subvector
19441 @tindex subvec
19442 The @kbd{v s} (@code{calc-subvector}) [@code{subvec}] command extracts
19443 a subvector of a vector.  The arguments are the vector, the starting
19444 index, and the ending index, with the ending index in the top-of-stack
19445 position.  The starting index indicates the first element of the vector
19446 to take.  The ending index indicates the first element @emph{past} the
19447 range to be taken.  Thus, @samp{subvec([a, b, c, d, e], 2, 4)} produces
19448 the subvector @samp{[b, c]}.  You could get the same result using
19449 @samp{mrow([a, b, c, d, e], @w{[2 .. 4)})}.
19451 If either the start or the end index is zero or negative, it is
19452 interpreted as relative to the end of the vector.  Thus
19453 @samp{subvec([a, b, c, d, e], 2, -2)} also produces @samp{[b, c]}.  In
19454 the algebraic form, the end index can be omitted in which case it
19455 is taken as zero, i.e., elements from the starting element to the
19456 end of the vector are used.  The infinity symbol, @code{inf}, also
19457 has this effect when used as the ending index.
19459 @kindex I v s
19460 @tindex rsubvec
19461 With the Inverse flag, @kbd{I v s} [@code{rsubvec}] removes a subvector
19462 from a vector.  The arguments are interpreted the same as for the
19463 normal @kbd{v s} command.  Thus, @samp{rsubvec([a, b, c, d, e], 2, 4)}
19464 produces @samp{[a, d, e]}.  It is always true that @code{subvec} and
19465 @code{rsubvec} return complementary parts of the input vector.
19467 @xref{Selecting Subformulas}, for an alternative way to operate on
19468 vectors one element at a time.
19470 @node Manipulating Vectors, Vector and Matrix Arithmetic, Extracting Elements, Matrix Functions
19471 @section Manipulating Vectors
19473 @noindent
19474 @kindex v l
19475 @pindex calc-vlength
19476 @tindex vlen
19477 The @kbd{v l} (@code{calc-vlength}) [@code{vlen}] command computes the
19478 length of a vector.  The length of a non-vector is considered to be zero.
19479 Note that matrices are just vectors of vectors for the purposes of this
19480 command.@refill
19482 @kindex H v l
19483 @tindex mdims
19484 With the Hyperbolic flag, @kbd{H v l} [@code{mdims}] computes a vector
19485 of the dimensions of a vector, matrix, or higher-order object.  For
19486 example, @samp{mdims([[a,b,c],[d,e,f]])} returns @samp{[2, 3]} since
19487 its argument is a @c{$2\times3$}
19488 @asis{2x3} matrix.
19490 @kindex v f
19491 @pindex calc-vector-find
19492 @tindex find
19493 The @kbd{v f} (@code{calc-vector-find}) [@code{find}] command searches
19494 along a vector for the first element equal to a given target.  The target
19495 is on the top of the stack; the vector is in the second-to-top position.
19496 If a match is found, the result is the index of the matching element.
19497 Otherwise, the result is zero.  The numeric prefix argument, if given,
19498 allows you to select any starting index for the search.
19500 @kindex v a
19501 @pindex calc-arrange-vector
19502 @tindex arrange
19503 @cindex Arranging a matrix
19504 @cindex Reshaping a matrix
19505 @cindex Flattening a matrix
19506 The @kbd{v a} (@code{calc-arrange-vector}) [@code{arrange}] command
19507 rearranges a vector to have a certain number of columns and rows.  The
19508 numeric prefix argument specifies the number of columns; if you do not
19509 provide an argument, you will be prompted for the number of columns.
19510 The vector or matrix on the top of the stack is @dfn{flattened} into a
19511 plain vector.  If the number of columns is nonzero, this vector is
19512 then formed into a matrix by taking successive groups of @var{n} elements.
19513 If the number of columns does not evenly divide the number of elements
19514 in the vector, the last row will be short and the result will not be
19515 suitable for use as a matrix.  For example, with the matrix
19516 @samp{[[1, 2], @w{[3, 4]}]} on the stack, @kbd{v a 4} produces
19517 @samp{[[1, 2, 3, 4]]} (a @c{$1\times4$}
19518 @asis{1x4} matrix), @kbd{v a 1} produces
19519 @samp{[[1], [2], [3], [4]]} (a @c{$4\times1$}
19520 @asis{4x1} matrix), @kbd{v a 2} produces
19521 @samp{[[1, 2], [3, 4]]} (the original @c{$2\times2$}
19522 @asis{2x2} matrix), @w{@kbd{v a 3}} produces
19523 @samp{[[1, 2, 3], [4]]} (not a matrix), and @kbd{v a 0} produces
19524 the flattened list @samp{[1, 2, @w{3, 4}]}.
19526 @cindex Sorting data
19527 @kindex V S
19528 @kindex I V S
19529 @pindex calc-sort
19530 @tindex sort
19531 @tindex rsort
19532 The @kbd{V S} (@code{calc-sort}) [@code{sort}] command sorts the elements of
19533 a vector into increasing order.  Real numbers, real infinities, and
19534 constant interval forms come first in this ordering; next come other
19535 kinds of numbers, then variables (in alphabetical order), then finally
19536 come formulas and other kinds of objects; these are sorted according
19537 to a kind of lexicographic ordering with the useful property that
19538 one vector is less or greater than another if the first corresponding
19539 unequal elements are less or greater, respectively.  Since quoted strings
19540 are stored by Calc internally as vectors of ASCII character codes
19541 (@pxref{Strings}), this means vectors of strings are also sorted into
19542 alphabetical order by this command.
19544 The @kbd{I V S} [@code{rsort}] command sorts a vector into decreasing order.
19546 @cindex Permutation, inverse of
19547 @cindex Inverse of permutation
19548 @cindex Index tables
19549 @cindex Rank tables
19550 @kindex V G
19551 @kindex I V G
19552 @pindex calc-grade
19553 @tindex grade
19554 @tindex rgrade
19555 The @kbd{V G} (@code{calc-grade}) [@code{grade}, @code{rgrade}] command
19556 produces an index table or permutation vector which, if applied to the
19557 input vector (as the index of @kbd{C-u v r}, say), would sort the vector.
19558 A permutation vector is just a vector of integers from 1 to @var{n}, where
19559 each integer occurs exactly once.  One application of this is to sort a
19560 matrix of data rows using one column as the sort key; extract that column,
19561 grade it with @kbd{V G}, then use the result to reorder the original matrix
19562 with @kbd{C-u v r}.  Another interesting property of the @code{V G} command
19563 is that, if the input is itself a permutation vector, the result will
19564 be the inverse of the permutation.  The inverse of an index table is
19565 a rank table, whose @var{k}th element says where the @var{k}th original
19566 vector element will rest when the vector is sorted.  To get a rank
19567 table, just use @kbd{V G V G}.
19569 With the Inverse flag, @kbd{I V G} produces an index table that would
19570 sort the input into decreasing order.  Note that @kbd{V S} and @kbd{V G}
19571 use a ``stable'' sorting algorithm, i.e., any two elements which are equal
19572 will not be moved out of their original order.  Generally there is no way
19573 to tell with @kbd{V S}, since two elements which are equal look the same,
19574 but with @kbd{V G} this can be an important issue.  In the matrix-of-rows
19575 example, suppose you have names and telephone numbers as two columns and
19576 you wish to sort by phone number primarily, and by name when the numbers
19577 are equal.  You can sort the data matrix by names first, and then again
19578 by phone numbers.  Because the sort is stable, any two rows with equal
19579 phone numbers will remain sorted by name even after the second sort.
19581 @cindex Histograms
19582 @kindex V H
19583 @pindex calc-histogram
19584 @c @mindex histo@idots
19585 @tindex histogram
19586 The @kbd{V H} (@code{calc-histogram}) [@code{histogram}] command builds a
19587 histogram of a vector of numbers.  Vector elements are assumed to be
19588 integers or real numbers in the range [0..@var{n}) for some ``number of
19589 bins'' @var{n}, which is the numeric prefix argument given to the
19590 command.  The result is a vector of @var{n} counts of how many times
19591 each value appeared in the original vector.  Non-integers in the input
19592 are rounded down to integers.  Any vector elements outside the specified
19593 range are ignored.  (You can tell if elements have been ignored by noting
19594 that the counts in the result vector don't add up to the length of the
19595 input vector.)
19597 @kindex H V H
19598 With the Hyperbolic flag, @kbd{H V H} pulls two vectors from the stack.
19599 The second-to-top vector is the list of numbers as before.  The top
19600 vector is an equal-sized list of ``weights'' to attach to the elements
19601 of the data vector.  For example, if the first data element is 4.2 and
19602 the first weight is 10, then 10 will be added to bin 4 of the result
19603 vector.  Without the hyperbolic flag, every element has a weight of one.
19605 @kindex v t
19606 @pindex calc-transpose
19607 @tindex trn
19608 The @kbd{v t} (@code{calc-transpose}) [@code{trn}] command computes
19609 the transpose of the matrix at the top of the stack.  If the argument
19610 is a plain vector, it is treated as a row vector and transposed into
19611 a one-column matrix.
19613 @kindex v v
19614 @pindex calc-reverse-vector
19615 @tindex rev
19616 The @kbd{v v} (@code{calc-reverse-vector}) [@code{vec}] command reverses
19617 a vector end-for-end.  Given a matrix, it reverses the order of the rows.
19618 (To reverse the columns instead, just use @kbd{v t v v v t}.  The same
19619 principle can be used to apply other vector commands to the columns of
19620 a matrix.)
19622 @kindex v m
19623 @pindex calc-mask-vector
19624 @tindex vmask
19625 The @kbd{v m} (@code{calc-mask-vector}) [@code{vmask}] command uses
19626 one vector as a mask to extract elements of another vector.  The mask
19627 is in the second-to-top position; the target vector is on the top of
19628 the stack.  These vectors must have the same length.  The result is
19629 the same as the target vector, but with all elements which correspond
19630 to zeros in the mask vector deleted.  Thus, for example,
19631 @samp{vmask([1, 0, 1, 0, 1], [a, b, c, d, e])} produces @samp{[a, c, e]}.
19632 @xref{Logical Operations}.
19634 @kindex v e
19635 @pindex calc-expand-vector
19636 @tindex vexp
19637 The @kbd{v e} (@code{calc-expand-vector}) [@code{vexp}] command
19638 expands a vector according to another mask vector.  The result is a
19639 vector the same length as the mask, but with nonzero elements replaced
19640 by successive elements from the target vector.  The length of the target
19641 vector is normally the number of nonzero elements in the mask.  If the
19642 target vector is longer, its last few elements are lost.  If the target
19643 vector is shorter, the last few nonzero mask elements are left
19644 unreplaced in the result.  Thus @samp{vexp([2, 0, 3, 0, 7], [a, b])}
19645 produces @samp{[a, 0, b, 0, 7]}.
19647 @kindex H v e
19648 With the Hyperbolic flag, @kbd{H v e} takes a filler value from the
19649 top of the stack; the mask and target vectors come from the third and
19650 second elements of the stack.  This filler is used where the mask is
19651 zero:  @samp{vexp([2, 0, 3, 0, 7], [a, b], z)} produces
19652 @samp{[a, z, c, z, 7]}.  If the filler value is itself a vector,
19653 then successive values are taken from it, so that the effect is to
19654 interleave two vectors according to the mask:
19655 @samp{vexp([2, 0, 3, 7, 0, 0], [a, b], [x, y])} produces
19656 @samp{[a, x, b, 7, y, 0]}.
19658 Another variation on the masking idea is to combine @samp{[a, b, c, d, e]}
19659 with the mask @samp{[1, 0, 1, 0, 1]} to produce @samp{[a, 0, c, 0, e]}.
19660 You can accomplish this with @kbd{V M a &}, mapping the logical ``and''
19661 operation across the two vectors.  @xref{Logical Operations}.  Note that
19662 the @code{? :} operation also discussed there allows other types of
19663 masking using vectors.
19665 @node Vector and Matrix Arithmetic, Set Operations, Manipulating Vectors, Matrix Functions
19666 @section Vector and Matrix Arithmetic
19668 @noindent
19669 Basic arithmetic operations like addition and multiplication are defined
19670 for vectors and matrices as well as for numbers.  Division of matrices, in
19671 the sense of multiplying by the inverse, is supported.  (Division by a
19672 matrix actually uses LU-decomposition for greater accuracy and speed.)
19673 @xref{Basic Arithmetic}.
19675 The following functions are applied element-wise if their arguments are
19676 vectors or matrices: @code{change-sign}, @code{conj}, @code{arg},
19677 @code{re}, @code{im}, @code{polar}, @code{rect}, @code{clean},
19678 @code{float}, @code{frac}.  @xref{Function Index}.@refill
19680 @kindex V J
19681 @pindex calc-conj-transpose
19682 @tindex ctrn
19683 The @kbd{V J} (@code{calc-conj-transpose}) [@code{ctrn}] command computes
19684 the conjugate transpose of its argument, i.e., @samp{conj(trn(x))}.
19686 @c @mindex A
19687 @kindex A (vectors)
19688 @pindex calc-abs (vectors)
19689 @c @mindex abs
19690 @tindex abs (vectors)
19691 The @kbd{A} (@code{calc-abs}) [@code{abs}] command computes the
19692 Frobenius norm of a vector or matrix argument.  This is the square
19693 root of the sum of the squares of the absolute values of the
19694 elements of the vector or matrix.  If the vector is interpreted as
19695 a point in two- or three-dimensional space, this is the distance
19696 from that point to the origin.@refill
19698 @kindex v n
19699 @pindex calc-rnorm
19700 @tindex rnorm
19701 The @kbd{v n} (@code{calc-rnorm}) [@code{rnorm}] command computes
19702 the row norm, or infinity-norm, of a vector or matrix.  For a plain
19703 vector, this is the maximum of the absolute values of the elements.
19704 For a matrix, this is the maximum of the row-absolute-value-sums,
19705 i.e., of the sums of the absolute values of the elements along the
19706 various rows.
19708 @kindex V N
19709 @pindex calc-cnorm
19710 @tindex cnorm
19711 The @kbd{V N} (@code{calc-cnorm}) [@code{cnorm}] command computes
19712 the column norm, or one-norm, of a vector or matrix.  For a plain
19713 vector, this is the sum of the absolute values of the elements.
19714 For a matrix, this is the maximum of the column-absolute-value-sums.
19715 General @cite{k}-norms for @cite{k} other than one or infinity are
19716 not provided.
19718 @kindex V C
19719 @pindex calc-cross
19720 @tindex cross
19721 The @kbd{V C} (@code{calc-cross}) [@code{cross}] command computes the
19722 right-handed cross product of two vectors, each of which must have
19723 exactly three elements.
19725 @c @mindex &
19726 @kindex & (matrices)
19727 @pindex calc-inv (matrices)
19728 @c @mindex inv
19729 @tindex inv (matrices)
19730 The @kbd{&} (@code{calc-inv}) [@code{inv}] command computes the
19731 inverse of a square matrix.  If the matrix is singular, the inverse
19732 operation is left in symbolic form.  Matrix inverses are recorded so
19733 that once an inverse (or determinant) of a particular matrix has been
19734 computed, the inverse and determinant of the matrix can be recomputed
19735 quickly in the future.
19737 If the argument to @kbd{&} is a plain number @cite{x}, this
19738 command simply computes @cite{1/x}.  This is okay, because the
19739 @samp{/} operator also does a matrix inversion when dividing one
19740 by a matrix.
19742 @kindex V D
19743 @pindex calc-mdet
19744 @tindex det
19745 The @kbd{V D} (@code{calc-mdet}) [@code{det}] command computes the
19746 determinant of a square matrix.
19748 @kindex V L
19749 @pindex calc-mlud
19750 @tindex lud
19751 The @kbd{V L} (@code{calc-mlud}) [@code{lud}] command computes the
19752 LU decomposition of a matrix.  The result is a list of three matrices
19753 which, when multiplied together left-to-right, form the original matrix.
19754 The first is a permutation matrix that arises from pivoting in the
19755 algorithm, the second is lower-triangular with ones on the diagonal,
19756 and the third is upper-triangular.
19758 @kindex V T
19759 @pindex calc-mtrace
19760 @tindex tr
19761 The @kbd{V T} (@code{calc-mtrace}) [@code{tr}] command computes the
19762 trace of a square matrix.  This is defined as the sum of the diagonal
19763 elements of the matrix.
19765 @node Set Operations, Statistical Operations, Vector and Matrix Arithmetic, Matrix Functions
19766 @section Set Operations using Vectors
19768 @noindent
19769 @cindex Sets, as vectors
19770 Calc includes several commands which interpret vectors as @dfn{sets} of
19771 objects.  A set is a collection of objects; any given object can appear
19772 only once in the set.  Calc stores sets as vectors of objects in
19773 sorted order.  Objects in a Calc set can be any of the usual things,
19774 such as numbers, variables, or formulas.  Two set elements are considered
19775 equal if they are identical, except that numerically equal numbers like
19776 the integer 4 and the float 4.0 are considered equal even though they
19777 are not ``identical.''  Variables are treated like plain symbols without
19778 attached values by the set operations; subtracting the set @samp{[b]}
19779 from @samp{[a, b]} always yields the set @samp{[a]} even though if
19780 the variables @samp{a} and @samp{b} both equalled 17, you might
19781 expect the answer @samp{[]}.
19783 If a set contains interval forms, then it is assumed to be a set of
19784 real numbers.  In this case, all set operations require the elements
19785 of the set to be only things that are allowed in intervals:  Real
19786 numbers, plus and minus infinity, HMS forms, and date forms.  If
19787 there are variables or other non-real objects present in a real set,
19788 all set operations on it will be left in unevaluated form.
19790 If the input to a set operation is a plain number or interval form
19791 @var{a}, it is treated like the one-element vector @samp{[@var{a}]}.
19792 The result is always a vector, except that if the set consists of a
19793 single interval, the interval itself is returned instead.
19795 @xref{Logical Operations}, for the @code{in} function which tests if
19796 a certain value is a member of a given set.  To test if the set @cite{A}
19797 is a subset of the set @cite{B}, use @samp{vdiff(A, B) = []}.
19799 @kindex V +
19800 @pindex calc-remove-duplicates
19801 @tindex rdup
19802 The @kbd{V +} (@code{calc-remove-duplicates}) [@code{rdup}] command
19803 converts an arbitrary vector into set notation.  It works by sorting
19804 the vector as if by @kbd{V S}, then removing duplicates.  (For example,
19805 @kbd{[a, 5, 4, a, 4.0]} is sorted to @samp{[4, 4.0, 5, a, a]} and then
19806 reduced to @samp{[4, 5, a]}).  Overlapping intervals are merged as
19807 necessary.  You rarely need to use @kbd{V +} explicitly, since all the
19808 other set-based commands apply @kbd{V +} to their inputs before using
19809 them.
19811 @kindex V V
19812 @pindex calc-set-union
19813 @tindex vunion
19814 The @kbd{V V} (@code{calc-set-union}) [@code{vunion}] command computes
19815 the union of two sets.  An object is in the union of two sets if and
19816 only if it is in either (or both) of the input sets.  (You could
19817 accomplish the same thing by concatenating the sets with @kbd{|},
19818 then using @kbd{V +}.)
19820 @kindex V ^
19821 @pindex calc-set-intersect
19822 @tindex vint
19823 The @kbd{V ^} (@code{calc-set-intersect}) [@code{vint}] command computes
19824 the intersection of two sets.  An object is in the intersection if
19825 and only if it is in both of the input sets.  Thus if the input
19826 sets are disjoint, i.e., if they share no common elements, the result
19827 will be the empty vector @samp{[]}.  Note that the characters @kbd{V}
19828 and @kbd{^} were chosen to be close to the conventional mathematical
19829 notation for set union@c{ ($A \cup B$)}
19830 @asis{} and intersection@c{ ($A \cap B$)}
19831 @asis{}.
19833 @kindex V -
19834 @pindex calc-set-difference
19835 @tindex vdiff
19836 The @kbd{V -} (@code{calc-set-difference}) [@code{vdiff}] command computes
19837 the difference between two sets.  An object is in the difference
19838 @cite{A - B} if and only if it is in @cite{A} but not in @cite{B}.
19839 Thus subtracting @samp{[y,z]} from a set will remove the elements
19840 @samp{y} and @samp{z} if they are present.  You can also think of this
19841 as a general @dfn{set complement} operator; if @cite{A} is the set of
19842 all possible values, then @cite{A - B} is the ``complement'' of @cite{B}.
19843 Obviously this is only practical if the set of all possible values in
19844 your problem is small enough to list in a Calc vector (or simple
19845 enough to express in a few intervals).
19847 @kindex V X
19848 @pindex calc-set-xor
19849 @tindex vxor
19850 The @kbd{V X} (@code{calc-set-xor}) [@code{vxor}] command computes
19851 the ``exclusive-or,'' or ``symmetric difference'' of two sets.
19852 An object is in the symmetric difference of two sets if and only
19853 if it is in one, but @emph{not} both, of the sets.  Objects that
19854 occur in both sets ``cancel out.''
19856 @kindex V ~
19857 @pindex calc-set-complement
19858 @tindex vcompl
19859 The @kbd{V ~} (@code{calc-set-complement}) [@code{vcompl}] command
19860 computes the complement of a set with respect to the real numbers.
19861 Thus @samp{vcompl(x)} is equivalent to @samp{vdiff([-inf .. inf], x)}.
19862 For example, @samp{vcompl([2, (3 .. 4]])} evaluates to
19863 @samp{[[-inf .. 2), (2 .. 3], (4 .. inf]]}.
19865 @kindex V F
19866 @pindex calc-set-floor
19867 @tindex vfloor
19868 The @kbd{V F} (@code{calc-set-floor}) [@code{vfloor}] command
19869 reinterprets a set as a set of integers.  Any non-integer values,
19870 and intervals that do not enclose any integers, are removed.  Open
19871 intervals are converted to equivalent closed intervals.  Successive
19872 integers are converted into intervals of integers.  For example, the
19873 complement of the set @samp{[2, 6, 7, 8]} is messy, but if you wanted
19874 the complement with respect to the set of integers you could type
19875 @kbd{V ~ V F} to get @samp{[[-inf .. 1], [3 .. 5], [9 .. inf]]}.
19877 @kindex V E
19878 @pindex calc-set-enumerate
19879 @tindex venum
19880 The @kbd{V E} (@code{calc-set-enumerate}) [@code{venum}] command
19881 converts a set of integers into an explicit vector.  Intervals in
19882 the set are expanded out to lists of all integers encompassed by
19883 the intervals.  This only works for finite sets (i.e., sets which
19884 do not involve @samp{-inf} or @samp{inf}).
19886 @kindex V :
19887 @pindex calc-set-span
19888 @tindex vspan
19889 The @kbd{V :} (@code{calc-set-span}) [@code{vspan}] command converts any
19890 set of reals into an interval form that encompasses all its elements.
19891 The lower limit will be the smallest element in the set; the upper
19892 limit will be the largest element.  For an empty set, @samp{vspan([])}
19893 returns the empty interval @w{@samp{[0 .. 0)}}.
19895 @kindex V #
19896 @pindex calc-set-cardinality
19897 @tindex vcard
19898 The @kbd{V #} (@code{calc-set-cardinality}) [@code{vcard}] command counts
19899 the number of integers in a set.  The result is the length of the vector
19900 that would be produced by @kbd{V E}, although the computation is much
19901 more efficient than actually producing that vector.
19903 @cindex Sets, as binary numbers
19904 Another representation for sets that may be more appropriate in some
19905 cases is binary numbers.  If you are dealing with sets of integers
19906 in the range 0 to 49, you can use a 50-bit binary number where a
19907 particular bit is 1 if the corresponding element is in the set.
19908 @xref{Binary Functions}, for a list of commands that operate on
19909 binary numbers.  Note that many of the above set operations have
19910 direct equivalents in binary arithmetic:  @kbd{b o} (@code{calc-or}),
19911 @kbd{b a} (@code{calc-and}), @kbd{b d} (@code{calc-diff}),
19912 @kbd{b x} (@code{calc-xor}), and @kbd{b n} (@code{calc-not}),
19913 respectively.  You can use whatever representation for sets is most
19914 convenient to you.
19916 @kindex b p
19917 @kindex b u
19918 @pindex calc-pack-bits
19919 @pindex calc-unpack-bits
19920 @tindex vpack
19921 @tindex vunpack
19922 The @kbd{b u} (@code{calc-unpack-bits}) [@code{vunpack}] command
19923 converts an integer that represents a set in binary into a set
19924 in vector/interval notation.  For example, @samp{vunpack(67)}
19925 returns @samp{[[0 .. 1], 6]}.  If the input is negative, the set
19926 it represents is semi-infinite: @samp{vunpack(-4) = [2 .. inf)}.
19927 Use @kbd{V E} afterwards to expand intervals to individual
19928 values if you wish.  Note that this command uses the @kbd{b}
19929 (binary) prefix key.
19931 The @kbd{b p} (@code{calc-pack-bits}) [@code{vpack}] command
19932 converts the other way, from a vector or interval representing
19933 a set of nonnegative integers into a binary integer describing
19934 the same set.  The set may include positive infinity, but must
19935 not include any negative numbers.  The input is interpreted as a
19936 set of integers in the sense of @kbd{V F} (@code{vfloor}).  Beware
19937 that a simple input like @samp{[100]} can result in a huge integer
19938 representation (@c{$2^{100}$}
19939 @cite{2^100}, a 31-digit integer, in this case).
19941 @node Statistical Operations, Reducing and Mapping, Set Operations, Matrix Functions
19942 @section Statistical Operations on Vectors
19944 @noindent
19945 @cindex Statistical functions
19946 The commands in this section take vectors as arguments and compute
19947 various statistical measures on the data stored in the vectors.  The
19948 references used in the definitions of these functions are Bevington's
19949 @emph{Data Reduction and Error Analysis for the Physical Sciences},
19950 and @emph{Numerical Recipes} by Press, Flannery, Teukolsky and
19951 Vetterling.
19953 The statistical commands use the @kbd{u} prefix key followed by
19954 a shifted letter or other character.
19956 @xref{Manipulating Vectors}, for a description of @kbd{V H}
19957 (@code{calc-histogram}).
19959 @xref{Curve Fitting}, for the @kbd{a F} command for doing
19960 least-squares fits to statistical data.
19962 @xref{Probability Distribution Functions}, for several common
19963 probability distribution functions.
19965 @menu
19966 * Single-Variable Statistics::
19967 * Paired-Sample Statistics::
19968 @end menu
19970 @node Single-Variable Statistics, Paired-Sample Statistics, Statistical Operations, Statistical Operations
19971 @subsection Single-Variable Statistics
19973 @noindent
19974 These functions do various statistical computations on single
19975 vectors.  Given a numeric prefix argument, they actually pop
19976 @var{n} objects from the stack and combine them into a data
19977 vector.  Each object may be either a number or a vector; if a
19978 vector, any sub-vectors inside it are ``flattened'' as if by
19979 @kbd{v a 0}; @pxref{Manipulating Vectors}.  By default one object
19980 is popped, which (in order to be useful) is usually a vector.
19982 If an argument is a variable name, and the value stored in that
19983 variable is a vector, then the stored vector is used.  This method
19984 has the advantage that if your data vector is large, you can avoid
19985 the slow process of manipulating it directly on the stack.
19987 These functions are left in symbolic form if any of their arguments
19988 are not numbers or vectors, e.g., if an argument is a formula, or
19989 a non-vector variable.  However, formulas embedded within vector
19990 arguments are accepted; the result is a symbolic representation
19991 of the computation, based on the assumption that the formula does
19992 not itself represent a vector.  All varieties of numbers such as
19993 error forms and interval forms are acceptable.
19995 Some of the functions in this section also accept a single error form
19996 or interval as an argument.  They then describe a property of the
19997 normal or uniform (respectively) statistical distribution described
19998 by the argument.  The arguments are interpreted in the same way as
19999 the @var{M} argument of the random number function @kbd{k r}.  In
20000 particular, an interval with integer limits is considered an integer
20001 distribution, so that @samp{[2 .. 6)} is the same as @samp{[2 .. 5]}.
20002 An interval with at least one floating-point limit is a continuous
20003 distribution:  @samp{[2.0 .. 6.0)} is @emph{not} the same as
20004 @samp{[2.0 .. 5.0]}!
20006 @kindex u #
20007 @pindex calc-vector-count
20008 @tindex vcount
20009 The @kbd{u #} (@code{calc-vector-count}) [@code{vcount}] command
20010 computes the number of data values represented by the inputs.
20011 For example, @samp{vcount(1, [2, 3], [[4, 5], [], x, y])} returns 7.
20012 If the argument is a single vector with no sub-vectors, this
20013 simply computes the length of the vector.
20015 @kindex u +
20016 @kindex u *
20017 @pindex calc-vector-sum
20018 @pindex calc-vector-prod
20019 @tindex vsum
20020 @tindex vprod
20021 @cindex Summations (statistical)
20022 The @kbd{u +} (@code{calc-vector-sum}) [@code{vsum}] command
20023 computes the sum of the data values.  The @kbd{u *}
20024 (@code{calc-vector-prod}) [@code{vprod}] command computes the
20025 product of the data values.  If the input is a single flat vector,
20026 these are the same as @kbd{V R +} and @kbd{V R *}
20027 (@pxref{Reducing and Mapping}).@refill
20029 @kindex u X
20030 @kindex u N
20031 @pindex calc-vector-max
20032 @pindex calc-vector-min
20033 @tindex vmax
20034 @tindex vmin
20035 The @kbd{u X} (@code{calc-vector-max}) [@code{vmax}] command
20036 computes the maximum of the data values, and the @kbd{u N}
20037 (@code{calc-vector-min}) [@code{vmin}] command computes the minimum.
20038 If the argument is an interval, this finds the minimum or maximum
20039 value in the interval.  (Note that @samp{vmax([2..6)) = 5} as
20040 described above.)  If the argument is an error form, this returns
20041 plus or minus infinity.
20043 @kindex u M
20044 @pindex calc-vector-mean
20045 @tindex vmean
20046 @cindex Mean of data values
20047 The @kbd{u M} (@code{calc-vector-mean}) [@code{vmean}] command
20048 computes the average (arithmetic mean) of the data values.
20049 If the inputs are error forms @c{$x$ @code{+/-} $\sigma$}
20050 @samp{x +/- s}, this is the weighted
20051 mean of the @cite{x} values with weights @c{$1 / \sigma^2$}
20052 @cite{1 / s^2}.
20053 @tex
20054 \turnoffactive
20055 $$ \mu = { \displaystyle \sum { x_i \over \sigma_i^2 } \over
20056            \displaystyle \sum { 1 \over \sigma_i^2 } } $$
20057 @end tex
20058 If the inputs are not error forms, this is simply the sum of the
20059 values divided by the count of the values.@refill
20061 Note that a plain number can be considered an error form with
20062 error @c{$\sigma = 0$}
20063 @cite{s = 0}.  If the input to @kbd{u M} is a mixture of
20064 plain numbers and error forms, the result is the mean of the
20065 plain numbers, ignoring all values with non-zero errors.  (By the
20066 above definitions it's clear that a plain number effectively
20067 has an infinite weight, next to which an error form with a finite
20068 weight is completely negligible.)
20070 This function also works for distributions (error forms or
20071 intervals).  The mean of an error form `@i{a} @t{+/-} @i{b}' is simply
20072 @cite{a}.  The mean of an interval is the mean of the minimum
20073 and maximum values of the interval.
20075 @kindex I u M
20076 @pindex calc-vector-mean-error
20077 @tindex vmeane
20078 The @kbd{I u M} (@code{calc-vector-mean-error}) [@code{vmeane}]
20079 command computes the mean of the data points expressed as an
20080 error form.  This includes the estimated error associated with
20081 the mean.  If the inputs are error forms, the error is the square
20082 root of the reciprocal of the sum of the reciprocals of the squares
20083 of the input errors.  (I.e., the variance is the reciprocal of the
20084 sum of the reciprocals of the variances.)
20085 @tex
20086 \turnoffactive
20087 $$ \sigma_\mu^2 = {1 \over \displaystyle \sum {1 \over \sigma_i^2}} $$
20088 @end tex
20089 If the inputs are plain
20090 numbers, the error is equal to the standard deviation of the values
20091 divided by the square root of the number of values.  (This works
20092 out to be equivalent to calculating the standard deviation and
20093 then assuming each value's error is equal to this standard
20094 deviation.)@refill
20095 @tex
20096 \turnoffactive
20097 $$ \sigma_\mu^2 = {\sigma^2 \over N} $$
20098 @end tex
20100 @kindex H u M
20101 @pindex calc-vector-median
20102 @tindex vmedian
20103 @cindex Median of data values
20104 The @kbd{H u M} (@code{calc-vector-median}) [@code{vmedian}]
20105 command computes the median of the data values.  The values are
20106 first sorted into numerical order; the median is the middle
20107 value after sorting.  (If the number of data values is even,
20108 the median is taken to be the average of the two middle values.)
20109 The median function is different from the other functions in
20110 this section in that the arguments must all be real numbers;
20111 variables are not accepted even when nested inside vectors.
20112 (Otherwise it is not possible to sort the data values.)  If
20113 any of the input values are error forms, their error parts are
20114 ignored.
20116 The median function also accepts distributions.  For both normal
20117 (error form) and uniform (interval) distributions, the median is
20118 the same as the mean.
20120 @kindex H I u M
20121 @pindex calc-vector-harmonic-mean
20122 @tindex vhmean
20123 @cindex Harmonic mean
20124 The @kbd{H I u M} (@code{calc-vector-harmonic-mean}) [@code{vhmean}]
20125 command computes the harmonic mean of the data values.  This is
20126 defined as the reciprocal of the arithmetic mean of the reciprocals
20127 of the values.
20128 @tex
20129 \turnoffactive
20130 $$ { N \over \displaystyle \sum {1 \over x_i} } $$
20131 @end tex
20133 @kindex u G
20134 @pindex calc-vector-geometric-mean
20135 @tindex vgmean
20136 @cindex Geometric mean
20137 The @kbd{u G} (@code{calc-vector-geometric-mean}) [@code{vgmean}]
20138 command computes the geometric mean of the data values.  This
20139 is the @i{N}th root of the product of the values.  This is also
20140 equal to the @code{exp} of the arithmetic mean of the logarithms
20141 of the data values.
20142 @tex
20143 \turnoffactive
20144 $$ \exp \left ( \sum { \ln x_i } \right ) =
20145    \left ( \prod { x_i } \right)^{1 / N} $$
20146 @end tex
20148 @kindex H u G
20149 @tindex agmean
20150 The @kbd{H u G} [@code{agmean}] command computes the ``arithmetic-geometric
20151 mean'' of two numbers taken from the stack.  This is computed by
20152 replacing the two numbers with their arithmetic mean and geometric
20153 mean, then repeating until the two values converge.
20154 @tex
20155 \turnoffactive
20156 $$ a_{i+1} = { a_i + b_i \over 2 } , \qquad b_{i+1} = \sqrt{a_i b_i} $$
20157 @end tex
20159 @cindex Root-mean-square
20160 Another commonly used mean, the RMS (root-mean-square), can be computed
20161 for a vector of numbers simply by using the @kbd{A} command.
20163 @kindex u S
20164 @pindex calc-vector-sdev
20165 @tindex vsdev
20166 @cindex Standard deviation
20167 @cindex Sample statistics
20168 The @kbd{u S} (@code{calc-vector-sdev}) [@code{vsdev}] command
20169 computes the standard deviation@c{ $\sigma$}
20170 @asis{} of the data values.  If the
20171 values are error forms, the errors are used as weights just
20172 as for @kbd{u M}.  This is the @emph{sample} standard deviation,
20173 whose value is the square root of the sum of the squares of the
20174 differences between the values and the mean of the @cite{N} values,
20175 divided by @cite{N-1}.
20176 @tex
20177 \turnoffactive
20178 $$ \sigma^2 = {1 \over N - 1} \sum (x_i - \mu)^2 $$
20179 @end tex
20181 This function also applies to distributions.  The standard deviation
20182 of a single error form is simply the error part.  The standard deviation
20183 of a continuous interval happens to equal the difference between the
20184 limits, divided by @c{$\sqrt{12}$}
20185 @cite{sqrt(12)}.  The standard deviation of an
20186 integer interval is the same as the standard deviation of a vector
20187 of those integers.
20189 @kindex I u S
20190 @pindex calc-vector-pop-sdev
20191 @tindex vpsdev
20192 @cindex Population statistics
20193 The @kbd{I u S} (@code{calc-vector-pop-sdev}) [@code{vpsdev}]
20194 command computes the @emph{population} standard deviation.
20195 It is defined by the same formula as above but dividing
20196 by @cite{N} instead of by @cite{N-1}.  The population standard
20197 deviation is used when the input represents the entire set of
20198 data values in the distribution; the sample standard deviation
20199 is used when the input represents a sample of the set of all
20200 data values, so that the mean computed from the input is itself
20201 only an estimate of the true mean.
20202 @tex
20203 \turnoffactive
20204 $$ \sigma^2 = {1 \over N} \sum (x_i - \mu)^2 $$
20205 @end tex
20207 For error forms and continuous intervals, @code{vpsdev} works
20208 exactly like @code{vsdev}.  For integer intervals, it computes the
20209 population standard deviation of the equivalent vector of integers.
20211 @kindex H u S
20212 @kindex H I u S
20213 @pindex calc-vector-variance
20214 @pindex calc-vector-pop-variance
20215 @tindex vvar
20216 @tindex vpvar
20217 @cindex Variance of data values
20218 The @kbd{H u S} (@code{calc-vector-variance}) [@code{vvar}] and
20219 @kbd{H I u S} (@code{calc-vector-pop-variance}) [@code{vpvar}]
20220 commands compute the variance of the data values.  The variance
20221 is the square@c{ $\sigma^2$}
20222 @asis{} of the standard deviation, i.e., the sum of the
20223 squares of the deviations of the data values from the mean.
20224 (This definition also applies when the argument is a distribution.)
20226 @c @starindex
20227 @tindex vflat
20228 The @code{vflat} algebraic function returns a vector of its
20229 arguments, interpreted in the same way as the other functions
20230 in this section.  For example, @samp{vflat(1, [2, [3, 4]], 5)}
20231 returns @samp{[1, 2, 3, 4, 5]}.
20233 @node Paired-Sample Statistics, , Single-Variable Statistics, Statistical Operations
20234 @subsection Paired-Sample Statistics
20236 @noindent
20237 The functions in this section take two arguments, which must be
20238 vectors of equal size.  The vectors are each flattened in the same
20239 way as by the single-variable statistical functions.  Given a numeric
20240 prefix argument of 1, these functions instead take one object from
20241 the stack, which must be an @c{$N\times2$}
20242 @asis{Nx2} matrix of data values.  Once
20243 again, variable names can be used in place of actual vectors and
20244 matrices.
20246 @kindex u C
20247 @pindex calc-vector-covariance
20248 @tindex vcov
20249 @cindex Covariance
20250 The @kbd{u C} (@code{calc-vector-covariance}) [@code{vcov}] command
20251 computes the sample covariance of two vectors.  The covariance
20252 of vectors @var{x} and @var{y} is the sum of the products of the
20253 differences between the elements of @var{x} and the mean of @var{x}
20254 times the differences between the corresponding elements of @var{y}
20255 and the mean of @var{y}, all divided by @cite{N-1}.  Note that
20256 the variance of a vector is just the covariance of the vector
20257 with itself.  Once again, if the inputs are error forms the
20258 errors are used as weight factors.  If both @var{x} and @var{y}
20259 are composed of error forms, the error for a given data point
20260 is taken as the square root of the sum of the squares of the two
20261 input errors.
20262 @tex
20263 \turnoffactive
20264 $$ \sigma_{x\!y}^2 = {1 \over N-1} \sum (x_i - \mu_x) (y_i - \mu_y) $$
20265 $$ \sigma_{x\!y}^2 =
20266     {\displaystyle {1 \over N-1}
20267                    \sum {(x_i - \mu_x) (y_i - \mu_y) \over \sigma_i^2}
20268      \over \displaystyle {1 \over N} \sum {1 \over \sigma_i^2}}
20270 @end tex
20272 @kindex I u C
20273 @pindex calc-vector-pop-covariance
20274 @tindex vpcov
20275 The @kbd{I u C} (@code{calc-vector-pop-covariance}) [@code{vpcov}]
20276 command computes the population covariance, which is the same as the
20277 sample covariance computed by @kbd{u C} except dividing by @cite{N}
20278 instead of @cite{N-1}.
20280 @kindex H u C
20281 @pindex calc-vector-correlation
20282 @tindex vcorr
20283 @cindex Correlation coefficient
20284 @cindex Linear correlation
20285 The @kbd{H u C} (@code{calc-vector-correlation}) [@code{vcorr}]
20286 command computes the linear correlation coefficient of two vectors.
20287 This is defined by the covariance of the vectors divided by the
20288 product of their standard deviations.  (There is no difference
20289 between sample or population statistics here.)
20290 @tex
20291 \turnoffactive
20292 $$ r_{x\!y} = { \sigma_{x\!y}^2 \over \sigma_x^2 \sigma_y^2 } $$
20293 @end tex
20295 @node Reducing and Mapping, Vector and Matrix Formats, Statistical Operations, Matrix Functions
20296 @section Reducing and Mapping Vectors
20298 @noindent
20299 The commands in this section allow for more general operations on the
20300 elements of vectors.
20302 @kindex V A
20303 @pindex calc-apply
20304 @tindex apply
20305 The simplest of these operations is @kbd{V A} (@code{calc-apply})
20306 [@code{apply}], which applies a given operator to the elements of a vector.
20307 For example, applying the hypothetical function @code{f} to the vector
20308 @w{@samp{[1, 2, 3]}} would produce the function call @samp{f(1, 2, 3)}.
20309 Applying the @code{+} function to the vector @samp{[a, b]} gives
20310 @samp{a + b}.  Applying @code{+} to the vector @samp{[a, b, c]} is an
20311 error, since the @code{+} function expects exactly two arguments.
20313 While @kbd{V A} is useful in some cases, you will usually find that either
20314 @kbd{V R} or @kbd{V M}, described below, is closer to what you want.
20316 @menu
20317 * Specifying Operators::
20318 * Mapping::
20319 * Reducing::
20320 * Nesting and Fixed Points::
20321 * Generalized Products::
20322 @end menu
20324 @node Specifying Operators, Mapping, Reducing and Mapping, Reducing and Mapping
20325 @subsection Specifying Operators
20327 @noindent
20328 Commands in this section (like @kbd{V A}) prompt you to press the key
20329 corresponding to the desired operator.  Press @kbd{?} for a partial
20330 list of the available operators.  Generally, an operator is any key or
20331 sequence of keys that would normally take one or more arguments from
20332 the stack and replace them with a result.  For example, @kbd{V A H C}
20333 uses the hyperbolic cosine operator, @code{cosh}.  (Since @code{cosh}
20334 expects one argument, @kbd{V A H C} requires a vector with a single
20335 element as its argument.)
20337 You can press @kbd{x} at the operator prompt to select any algebraic
20338 function by name to use as the operator.  This includes functions you
20339 have defined yourself using the @kbd{Z F} command.  (@xref{Algebraic
20340 Definitions}.)  If you give a name for which no function has been
20341 defined, the result is left in symbolic form, as in @samp{f(1, 2, 3)}.
20342 Calc will prompt for the number of arguments the function takes if it
20343 can't figure it out on its own (say, because you named a function that
20344 is currently undefined).  It is also possible to type a digit key before
20345 the function name to specify the number of arguments, e.g.,
20346 @kbd{V M 3 x f RET} calls @code{f} with three arguments even if it
20347 looks like it ought to have only two.  This technique may be necessary
20348 if the function allows a variable number of arguments.  For example,
20349 the @kbd{v e} [@code{vexp}] function accepts two or three arguments;
20350 if you want to map with the three-argument version, you will have to
20351 type @kbd{V M 3 v e}.
20353 It is also possible to apply any formula to a vector by treating that
20354 formula as a function.  When prompted for the operator to use, press
20355 @kbd{'} (the apostrophe) and type your formula as an algebraic entry.
20356 You will then be prompted for the argument list, which defaults to a
20357 list of all variables that appear in the formula, sorted into alphabetic
20358 order.  For example, suppose you enter the formula @w{@samp{x + 2y^x}}.
20359 The default argument list would be @samp{(x y)}, which means that if
20360 this function is applied to the arguments @samp{[3, 10]} the result will
20361 be @samp{3 + 2*10^3}.  (If you plan to use a certain formula in this
20362 way often, you might consider defining it as a function with @kbd{Z F}.)
20364 Another way to specify the arguments to the formula you enter is with
20365 @kbd{$}, @kbd{$$}, and so on.  For example, @kbd{V A ' $$ + 2$^$$}
20366 has the same effect as the previous example.  The argument list is
20367 automatically taken to be @samp{($$ $)}.  (The order of the arguments
20368 may seem backwards, but it is analogous to the way normal algebraic
20369 entry interacts with the stack.)
20371 If you press @kbd{$} at the operator prompt, the effect is similar to
20372 the apostrophe except that the relevant formula is taken from top-of-stack
20373 instead.  The actual vector arguments of the @kbd{V A $} or related command
20374 then start at the second-to-top stack position.  You will still be
20375 prompted for an argument list.
20377 @cindex Nameless functions
20378 @cindex Generic functions
20379 A function can be written without a name using the notation @samp{<#1 - #2>},
20380 which means ``a function of two arguments that computes the first
20381 argument minus the second argument.''  The symbols @samp{#1} and @samp{#2}
20382 are placeholders for the arguments.  You can use any names for these
20383 placeholders if you wish, by including an argument list followed by a
20384 colon:  @samp{<x, y : x - y>}.  When you type @kbd{V A ' $$ + 2$^$$ RET},
20385 Calc builds the nameless function @samp{<#1 + 2 #2^#1>} as the function
20386 to map across the vectors.  When you type @kbd{V A ' x + 2y^x RET RET},
20387 Calc builds the nameless function @w{@samp{<x, y : x + 2 y^x>}}.  In both
20388 cases, Calc also writes the nameless function to the Trail so that you
20389 can get it back later if you wish.
20391 If there is only one argument, you can write @samp{#} in place of @samp{#1}.
20392 (Note that @samp{< >} notation is also used for date forms.  Calc tells
20393 that @samp{<@var{stuff}>} is a nameless function by the presence of
20394 @samp{#} signs inside @var{stuff}, or by the fact that @var{stuff}
20395 begins with a list of variables followed by a colon.)
20397 You can type a nameless function directly to @kbd{V A '}, or put one on
20398 the stack and use it with @w{@kbd{V A $}}.  Calc will not prompt for an
20399 argument list in this case, since the nameless function specifies the
20400 argument list as well as the function itself.  In @kbd{V A '}, you can
20401 omit the @samp{< >} marks if you use @samp{#} notation for the arguments,
20402 so that @kbd{V A ' #1+#2 RET} is the same as @kbd{V A ' <#1+#2> RET},
20403 which in turn is the same as @kbd{V A ' $$+$ RET}.
20405 @cindex Lambda expressions
20406 @c @starindex
20407 @tindex lambda
20408 The internal format for @samp{<x, y : x + y>} is @samp{lambda(x, y, x + y)}.
20409 (The word @code{lambda} derives from Lisp notation and the theory of
20410 functions.)  The internal format for @samp{<#1 + #2>} is @samp{lambda(ArgA,
20411 ArgB, ArgA + ArgB)}.  Note that there is no actual Calc function called
20412 @code{lambda}; the whole point is that the @code{lambda} expression is
20413 used in its symbolic form, not evaluated for an answer until it is applied
20414 to specific arguments by a command like @kbd{V A} or @kbd{V M}.
20416 (Actually, @code{lambda} does have one special property:  Its arguments
20417 are never evaluated; for example, putting @samp{<(2/3) #>} on the stack
20418 will not simplify the @samp{2/3} until the nameless function is actually
20419 called.)
20421 @tindex add
20422 @tindex sub
20423 @c @mindex @idots
20424 @tindex mul
20425 @c @mindex @null
20426 @tindex div
20427 @c @mindex @null
20428 @tindex pow
20429 @c @mindex @null
20430 @tindex neg
20431 @c @mindex @null
20432 @tindex mod
20433 @c @mindex @null
20434 @tindex vconcat
20435 As usual, commands like @kbd{V A} have algebraic function name equivalents.
20436 For example, @kbd{V A k g} with an argument of @samp{v} is equivalent to
20437 @samp{apply(gcd, v)}.  The first argument specifies the operator name,
20438 and is either a variable whose name is the same as the function name,
20439 or a nameless function like @samp{<#^3+1>}.  Operators that are normally
20440 written as algebraic symbols have the names @code{add}, @code{sub},
20441 @code{mul}, @code{div}, @code{pow}, @code{neg}, @code{mod}, and
20442 @code{vconcat}.@refill
20444 @c @starindex
20445 @tindex call
20446 The @code{call} function builds a function call out of several arguments:
20447 @samp{call(gcd, x, y)} is the same as @samp{apply(gcd, [x, y])}, which
20448 in turn is the same as @samp{gcd(x, y)}.  The first argument of @code{call},
20449 like the other functions described here, may be either a variable naming a
20450 function, or a nameless function (@samp{call(<#1+2#2>, x, y)} is the same
20451 as @samp{x + 2y}).
20453 (Experts will notice that it's not quite proper to use a variable to name
20454 a function, since the name @code{gcd} corresponds to the Lisp variable
20455 @code{var-gcd} but to the Lisp function @code{calcFunc-gcd}.  Calc
20456 automatically makes this translation, so you don't have to worry
20457 about it.)
20459 @node Mapping, Reducing, Specifying Operators, Reducing and Mapping
20460 @subsection Mapping
20462 @noindent
20463 @kindex V M
20464 @pindex calc-map
20465 @tindex map
20466 The @kbd{V M} (@code{calc-map}) [@code{map}] command applies a given
20467 operator elementwise to one or more vectors.  For example, mapping
20468 @code{A} [@code{abs}] produces a vector of the absolute values of the
20469 elements in the input vector.  Mapping @code{+} pops two vectors from
20470 the stack, which must be of equal length, and produces a vector of the
20471 pairwise sums of the elements.  If either argument is a non-vector, it
20472 is duplicated for each element of the other vector.  For example,
20473 @kbd{[1,2,3] 2 V M ^} squares the elements of the specified vector.
20474 With the 2 listed first, it would have computed a vector of powers of
20475 two.  Mapping a user-defined function pops as many arguments from the
20476 stack as the function requires.  If you give an undefined name, you will
20477 be prompted for the number of arguments to use.@refill
20479 If any argument to @kbd{V M} is a matrix, the operator is normally mapped
20480 across all elements of the matrix.  For example, given the matrix
20481 @cite{[[1, -2, 3], [-4, 5, -6]]}, @kbd{V M A} takes six absolute values to
20482 produce another @c{$3\times2$}
20483 @asis{3x2} matrix, @cite{[[1, 2, 3], [4, 5, 6]]}.
20485 @tindex mapr
20486 The command @kbd{V M _} [@code{mapr}] (i.e., type an underscore at the
20487 operator prompt) maps by rows instead.  For example, @kbd{V M _ A} views
20488 the above matrix as a vector of two 3-element row vectors.  It produces
20489 a new vector which contains the absolute values of those row vectors,
20490 namely @cite{[3.74, 8.77]}.  (Recall, the absolute value of a vector is
20491 defined as the square root of the sum of the squares of the elements.)
20492 Some operators accept vectors and return new vectors; for example,
20493 @kbd{v v} reverses a vector, so @kbd{V M _ v v} would reverse each row
20494 of the matrix to get a new matrix, @cite{[[3, -2, 1], [-6, 5, -4]]}.
20496 Sometimes a vector of vectors (representing, say, strings, sets, or lists)
20497 happens to look like a matrix.  If so, remember to use @kbd{V M _} if you
20498 want to map a function across the whole strings or sets rather than across
20499 their individual elements.
20501 @tindex mapc
20502 The command @kbd{V M :} [@code{mapc}] maps by columns.  Basically, it
20503 transposes the input matrix, maps by rows, and then, if the result is a
20504 matrix, transposes again.  For example, @kbd{V M : A} takes the absolute
20505 values of the three columns of the matrix, treating each as a 2-vector,
20506 and @kbd{V M : v v} reverses the columns to get the matrix
20507 @cite{[[-4, 5, -6], [1, -2, 3]]}.
20509 (The symbols @kbd{_} and @kbd{:} were chosen because they had row-like
20510 and column-like appearances, and were not already taken by useful
20511 operators.  Also, they appear shifted on most keyboards so they are easy
20512 to type after @kbd{V M}.)
20514 The @kbd{_} and @kbd{:} modifiers have no effect on arguments that are
20515 not matrices (so if none of the arguments are matrices, they have no
20516 effect at all).  If some of the arguments are matrices and others are
20517 plain numbers, the plain numbers are held constant for all rows of the
20518 matrix (so that @kbd{2 V M _ ^} squares every row of a matrix; squaring
20519 a vector takes a dot product of the vector with itself).
20521 If some of the arguments are vectors with the same lengths as the
20522 rows (for @kbd{V M _}) or columns (for @kbd{V M :}) of the matrix
20523 arguments, those vectors are also held constant for every row or
20524 column.
20526 Sometimes it is useful to specify another mapping command as the operator
20527 to use with @kbd{V M}.  For example, @kbd{V M _ V A +} applies @kbd{V A +}
20528 to each row of the input matrix, which in turn adds the two values on that
20529 row.  If you give another vector-operator command as the operator for
20530 @kbd{V M}, it automatically uses map-by-rows mode if you don't specify
20531 otherwise; thus @kbd{V M V A +} is equivalent to @kbd{V M _ V A +}.  (If
20532 you really want to map-by-elements another mapping command, you can use
20533 a triple-nested mapping command:  @kbd{V M V M V A +} means to map
20534 @kbd{V M V A +} over the rows of the matrix; in turn, @kbd{V A +} is
20535 mapped over the elements of each row.)
20537 @tindex mapa
20538 @tindex mapd
20539 Previous versions of Calc had ``map across'' and ``map down'' modes
20540 that are now considered obsolete; the old ``map across'' is now simply
20541 @kbd{V M V A}, and ``map down'' is now @kbd{V M : V A}.  The algebraic
20542 functions @code{mapa} and @code{mapd} are still supported, though.
20543 Note also that, while the old mapping modes were persistent (once you
20544 set the mode, it would apply to later mapping commands until you reset
20545 it), the new @kbd{:} and @kbd{_} modifiers apply only to the current
20546 mapping command.  The default @kbd{V M} always means map-by-elements.
20548 @xref{Algebraic Manipulation}, for the @kbd{a M} command, which is like
20549 @kbd{V M} but for equations and inequalities instead of vectors.
20550 @xref{Storing Variables}, for the @kbd{s m} command which modifies a
20551 variable's stored value using a @kbd{V M}-like operator.
20553 @node Reducing, Nesting and Fixed Points, Mapping, Reducing and Mapping
20554 @subsection Reducing
20556 @noindent
20557 @kindex V R
20558 @pindex calc-reduce
20559 @tindex reduce
20560 The @kbd{V R} (@code{calc-reduce}) [@code{reduce}] command applies a given
20561 binary operator across all the elements of a vector.  A binary operator is
20562 a function such as @code{+} or @code{max} which takes two arguments.  For
20563 example, reducing @code{+} over a vector computes the sum of the elements
20564 of the vector.  Reducing @code{-} computes the first element minus each of
20565 the remaining elements.  Reducing @code{max} computes the maximum element
20566 and so on.  In general, reducing @code{f} over the vector @samp{[a, b, c, d]}
20567 produces @samp{f(f(f(a, b), c), d)}.
20569 @kindex I V R
20570 @tindex rreduce
20571 The @kbd{I V R} [@code{rreduce}] command is similar to @kbd{V R} except
20572 that works from right to left through the vector.  For example, plain
20573 @kbd{V R -} on the vector @samp{[a, b, c, d]} produces @samp{a - b - c - d}
20574 but @kbd{I V R -} on the same vector produces @samp{a - (b - (c - d))},
20575 or @samp{a - b + c - d}.  This ``alternating sum'' occurs frequently
20576 in power series expansions.
20578 @kindex V U
20579 @tindex accum
20580 The @kbd{V U} (@code{calc-accumulate}) [@code{accum}] command does an
20581 accumulation operation.  Here Calc does the corresponding reduction
20582 operation, but instead of producing only the final result, it produces
20583 a vector of all the intermediate results.  Accumulating @code{+} over
20584 the vector @samp{[a, b, c, d]} produces the vector
20585 @samp{[a, a + b, a + b + c, a + b + c + d]}.
20587 @kindex I V U
20588 @tindex raccum
20589 The @kbd{I V U} [@code{raccum}] command does a right-to-left accumulation.
20590 For example, @kbd{I V U -} on the vector @samp{[a, b, c, d]} produces the
20591 vector @samp{[a - b + c - d, b - c + d, c - d, d]}.
20593 @tindex reducea
20594 @tindex rreducea
20595 @tindex reduced
20596 @tindex rreduced
20597 As for @kbd{V M}, @kbd{V R} normally reduces a matrix elementwise.  For
20598 example, given the matrix @cite{[[a, b, c], [d, e, f]]}, @kbd{V R +} will
20599 compute @cite{a + b + c + d + e + f}.  You can type @kbd{V R _} or
20600 @kbd{V R :} to modify this behavior.  The @kbd{V R _} [@code{reducea}]
20601 command reduces ``across'' the matrix; it reduces each row of the matrix
20602 as a vector, then collects the results.  Thus @kbd{V R _ +} of this
20603 matrix would produce @cite{[a + b + c, d + e + f]}.  Similarly, @kbd{V R :}
20604 [@code{reduced}] reduces down; @kbd{V R : +} would produce @cite{[a + d,
20605 b + e, c + f]}.
20607 @tindex reducer
20608 @tindex rreducer
20609 There is a third ``by rows'' mode for reduction that is occasionally
20610 useful; @kbd{V R =} [@code{reducer}] simply reduces the operator over
20611 the rows of the matrix themselves.  Thus @kbd{V R = +} on the above
20612 matrix would get the same result as @kbd{V R : +}, since adding two
20613 row vectors is equivalent to adding their elements.  But @kbd{V R = *}
20614 would multiply the two rows (to get a single number, their dot product),
20615 while @kbd{V R : *} would produce a vector of the products of the columns.
20617 These three matrix reduction modes work with @kbd{V R} and @kbd{I V R},
20618 but they are not currently supported with @kbd{V U} or @kbd{I V U}.
20620 @tindex reducec
20621 @tindex rreducec
20622 The obsolete reduce-by-columns function, @code{reducec}, is still
20623 supported but there is no way to get it through the @kbd{V R} command.
20625 The commands @kbd{M-# :} and @kbd{M-# _} are equivalent to typing
20626 @kbd{M-# r} to grab a rectangle of data into Calc, and then typing
20627 @kbd{V R : +} or @kbd{V R _ +}, respectively, to sum the columns or
20628 rows of the matrix.  @xref{Grabbing From Buffers}.
20630 @node Nesting and Fixed Points, Generalized Products, Reducing, Reducing and Mapping
20631 @subsection Nesting and Fixed Points
20633 @noindent
20634 @kindex H V R
20635 @tindex nest
20636 The @kbd{H V R} [@code{nest}] command applies a function to a given
20637 argument repeatedly.  It takes two values, @samp{a} and @samp{n}, from
20638 the stack, where @samp{n} must be an integer.  It then applies the
20639 function nested @samp{n} times; if the function is @samp{f} and @samp{n}
20640 is 3, the result is @samp{f(f(f(a)))}.  The number @samp{n} may be
20641 negative if Calc knows an inverse for the function @samp{f}; for
20642 example, @samp{nest(sin, a, -2)} returns @samp{arcsin(arcsin(a))}.
20644 @kindex H V U
20645 @tindex anest
20646 The @kbd{H V U} [@code{anest}] command is an accumulating version of
20647 @code{nest}:  It returns a vector of @samp{n+1} values, e.g.,
20648 @samp{[a, f(a), f(f(a)), f(f(f(a)))]}.  If @samp{n} is negative and
20649 @samp{F} is the inverse of @samp{f}, then the result is of the
20650 form @samp{[a, F(a), F(F(a)), F(F(F(a)))]}.
20652 @kindex H I V R
20653 @tindex fixp
20654 @cindex Fixed points
20655 The @kbd{H I V R} [@code{fixp}] command is like @kbd{H V R}, except
20656 that it takes only an @samp{a} value from the stack; the function is
20657 applied until it reaches a ``fixed point,'' i.e., until the result
20658 no longer changes.
20660 @kindex H I V U
20661 @tindex afixp
20662 The @kbd{H I V U} [@code{afixp}] command is an accumulating @code{fixp}.
20663 The first element of the return vector will be the initial value @samp{a};
20664 the last element will be the final result that would have been returned
20665 by @code{fixp}.
20667 For example, 0.739085 is a fixed point of the cosine function (in radians):
20668 @samp{cos(0.739085) = 0.739085}.  You can find this value by putting, say,
20669 1.0 on the stack and typing @kbd{H I V U C}.  (We use the accumulating
20670 version so we can see the intermediate results:  @samp{[1, 0.540302, 0.857553,
20671 0.65329, ...]}.  With a precision of six, this command will take 36 steps
20672 to converge to 0.739085.)
20674 Newton's method for finding roots is a classic example of iteration
20675 to a fixed point.  To find the square root of five starting with an
20676 initial guess, Newton's method would look for a fixed point of the
20677 function @samp{(x + 5/x) / 2}.  Putting a guess of 1 on the stack
20678 and typing @kbd{H I V R ' ($ + 5/$)/2 RET} quickly yields the result
20679 2.23607.  This is equivalent to using the @kbd{a R} (@code{calc-find-root})
20680 command to find a root of the equation @samp{x^2 = 5}.
20682 These examples used numbers for @samp{a} values.  Calc keeps applying
20683 the function until two successive results are equal to within the
20684 current precision.  For complex numbers, both the real parts and the
20685 imaginary parts must be equal to within the current precision.  If
20686 @samp{a} is a formula (say, a variable name), then the function is
20687 applied until two successive results are exactly the same formula.
20688 It is up to you to ensure that the function will eventually converge;
20689 if it doesn't, you may have to press @kbd{C-g} to stop the Calculator.
20691 The algebraic @code{fixp} function takes two optional arguments, @samp{n}
20692 and @samp{tol}.  The first is the maximum number of steps to be allowed,
20693 and must be either an integer or the symbol @samp{inf} (infinity, the
20694 default).  The second is a convergence tolerance.  If a tolerance is
20695 specified, all results during the calculation must be numbers, not
20696 formulas, and the iteration stops when the magnitude of the difference
20697 between two successive results is less than or equal to the tolerance.
20698 (This implies that a tolerance of zero iterates until the results are
20699 exactly equal.)
20701 Putting it all together, @samp{fixp(<(# + A/#)/2>, B, 20, 1e-10)}
20702 computes the square root of @samp{A} given the initial guess @samp{B},
20703 stopping when the result is correct within the specified tolerance, or
20704 when 20 steps have been taken, whichever is sooner.
20706 @node Generalized Products, , Nesting and Fixed Points, Reducing and Mapping
20707 @subsection Generalized Products
20709 @kindex V O
20710 @pindex calc-outer-product
20711 @tindex outer
20712 The @kbd{V O} (@code{calc-outer-product}) [@code{outer}] command applies
20713 a given binary operator to all possible pairs of elements from two
20714 vectors, to produce a matrix.  For example, @kbd{V O *} with @samp{[a, b]}
20715 and @samp{[x, y, z]} on the stack produces a multiplication table:
20716 @samp{[[a x, a y, a z], [b x, b y, b z]]}.  Element @var{r},@var{c} of
20717 the result matrix is obtained by applying the operator to element @var{r}
20718 of the lefthand vector and element @var{c} of the righthand vector.
20720 @kindex V I
20721 @pindex calc-inner-product
20722 @tindex inner
20723 The @kbd{V I} (@code{calc-inner-product}) [@code{inner}] command computes
20724 the generalized inner product of two vectors or matrices, given a
20725 ``multiplicative'' operator and an ``additive'' operator.  These can each
20726 actually be any binary operators; if they are @samp{*} and @samp{+},
20727 respectively, the result is a standard matrix multiplication.  Element
20728 @var{r},@var{c} of the result matrix is obtained by mapping the
20729 multiplicative operator across row @var{r} of the lefthand matrix and
20730 column @var{c} of the righthand matrix, and then reducing with the additive
20731 operator.  Just as for the standard @kbd{*} command, this can also do a
20732 vector-matrix or matrix-vector inner product, or a vector-vector
20733 generalized dot product.
20735 Since @kbd{V I} requires two operators, it prompts twice.  In each case,
20736 you can use any of the usual methods for entering the operator.  If you
20737 use @kbd{$} twice to take both operator formulas from the stack, the
20738 first (multiplicative) operator is taken from the top of the stack
20739 and the second (additive) operator is taken from second-to-top.
20741 @node Vector and Matrix Formats, , Reducing and Mapping, Matrix Functions
20742 @section Vector and Matrix Display Formats
20744 @noindent
20745 Commands for controlling vector and matrix display use the @kbd{v} prefix
20746 instead of the usual @kbd{d} prefix.  But they are display modes; in
20747 particular, they are influenced by the @kbd{I} and @kbd{H} prefix keys
20748 in the same way (@pxref{Display Modes}).  Matrix display is also
20749 influenced by the @kbd{d O} (@code{calc-flat-language}) mode;
20750 @pxref{Normal Language Modes}.
20752 @kindex V <
20753 @pindex calc-matrix-left-justify
20754 @kindex V =
20755 @pindex calc-matrix-center-justify
20756 @kindex V >
20757 @pindex calc-matrix-right-justify
20758 The commands @kbd{v <} (@code{calc-matrix-left-justify}), @kbd{v >}
20759 (@code{calc-matrix-right-justify}), and @w{@kbd{v =}}
20760 (@code{calc-matrix-center-justify}) control whether matrix elements
20761 are justified to the left, right, or center of their columns.@refill
20763 @kindex V [
20764 @pindex calc-vector-brackets
20765 @kindex V @{
20766 @pindex calc-vector-braces
20767 @kindex V (
20768 @pindex calc-vector-parens
20769 The @kbd{v [} (@code{calc-vector-brackets}) command turns the square
20770 brackets that surround vectors and matrices displayed in the stack on
20771 and off.  The @kbd{v @{} (@code{calc-vector-braces}) and @kbd{v (}
20772 (@code{calc-vector-parens}) commands use curly braces or parentheses,
20773 respectively, instead of square brackets.  For example, @kbd{v @{} might
20774 be used in preparation for yanking a matrix into a buffer running
20775 Mathematica.  (In fact, the Mathematica language mode uses this mode;
20776 @pxref{Mathematica Language Mode}.)  Note that, regardless of the
20777 display mode, either brackets or braces may be used to enter vectors,
20778 and parentheses may never be used for this purpose.@refill
20780 @kindex V ]
20781 @pindex calc-matrix-brackets
20782 The @kbd{v ]} (@code{calc-matrix-brackets}) command controls the
20783 ``big'' style display of matrices.  It prompts for a string of code
20784 letters; currently implemented letters are @code{R}, which enables
20785 brackets on each row of the matrix; @code{O}, which enables outer
20786 brackets in opposite corners of the matrix; and @code{C}, which
20787 enables commas or semicolons at the ends of all rows but the last.
20788 The default format is @samp{RO}.  (Before Calc 2.00, the format
20789 was fixed at @samp{ROC}.)  Here are some example matrices:
20791 @group
20792 @example
20793 [ [ 123,  0,   0  ]       [ [ 123,  0,   0  ],
20794   [  0,  123,  0  ]         [  0,  123,  0  ],
20795   [  0,   0,  123 ] ]       [  0,   0,  123 ] ]
20797          RO                        ROC
20799 @end example
20800 @end group
20801 @noindent
20802 @group
20803 @example
20804   [ 123,  0,   0            [ 123,  0,   0 ;
20805      0,  123,  0               0,  123,  0 ;
20806      0,   0,  123 ]            0,   0,  123 ]
20808           O                        OC
20810 @end example
20811 @end group
20812 @noindent
20813 @group
20814 @example
20815   [ 123,  0,   0  ]           123,  0,   0
20816   [  0,  123,  0  ]            0,  123,  0
20817   [  0,   0,  123 ]            0,   0,  123
20819           R                       @r{blank}
20820 @end example
20821 @end group
20823 @noindent
20824 Note that of the formats shown here, @samp{RO}, @samp{ROC}, and
20825 @samp{OC} are all recognized as matrices during reading, while
20826 the others are useful for display only.
20828 @kindex V ,
20829 @pindex calc-vector-commas
20830 The @kbd{v ,} (@code{calc-vector-commas}) command turns commas on and
20831 off in vector and matrix display.@refill
20833 In vectors of length one, and in all vectors when commas have been
20834 turned off, Calc adds extra parentheses around formulas that might
20835 otherwise be ambiguous.  For example, @samp{[a b]} could be a vector
20836 of the one formula @samp{a b}, or it could be a vector of two
20837 variables with commas turned off.  Calc will display the former
20838 case as @samp{[(a b)]}.  You can disable these extra parentheses
20839 (to make the output less cluttered at the expense of allowing some
20840 ambiguity) by adding the letter @code{P} to the control string you
20841 give to @kbd{v ]} (as described above).
20843 @kindex V .
20844 @pindex calc-full-vectors
20845 The @kbd{v .} (@code{calc-full-vectors}) command turns abbreviated
20846 display of long vectors on and off.  In this mode, vectors of six
20847 or more elements, or matrices of six or more rows or columns, will
20848 be displayed in an abbreviated form that displays only the first
20849 three elements and the last element:  @samp{[a, b, c, ..., z]}.
20850 When very large vectors are involved this will substantially
20851 improve Calc's display speed.
20853 @kindex t .
20854 @pindex calc-full-trail-vectors
20855 The @kbd{t .} (@code{calc-full-trail-vectors}) command controls a
20856 similar mode for recording vectors in the Trail.  If you turn on
20857 this mode, vectors of six or more elements and matrices of six or
20858 more rows or columns will be abbreviated when they are put in the
20859 Trail.  The @kbd{t y} (@code{calc-trail-yank}) command will be
20860 unable to recover those vectors.  If you are working with very
20861 large vectors, this mode will improve the speed of all operations
20862 that involve the trail.
20864 @kindex V /
20865 @pindex calc-break-vectors
20866 The @kbd{v /} (@code{calc-break-vectors}) command turns multi-line
20867 vector display on and off.  Normally, matrices are displayed with one
20868 row per line but all other types of vectors are displayed in a single
20869 line.  This mode causes all vectors, whether matrices or not, to be
20870 displayed with a single element per line.  Sub-vectors within the
20871 vectors will still use the normal linear form.
20873 @node Algebra, Units, Matrix Functions, Top
20874 @chapter Algebra
20876 @noindent
20877 This section covers the Calc features that help you work with
20878 algebraic formulas.  First, the general sub-formula selection
20879 mechanism is described; this works in conjunction with any Calc
20880 commands.  Then, commands for specific algebraic operations are
20881 described.  Finally, the flexible @dfn{rewrite rule} mechanism
20882 is discussed.
20884 The algebraic commands use the @kbd{a} key prefix; selection
20885 commands use the @kbd{j} (for ``just a letter that wasn't used
20886 for anything else'') prefix.
20888 @xref{Editing Stack Entries}, to see how to manipulate formulas
20889 using regular Emacs editing commands.@refill
20891 When doing algebraic work, you may find several of the Calculator's
20892 modes to be helpful, including algebraic-simplification mode (@kbd{m A})
20893 or no-simplification mode (@kbd{m O}),
20894 algebraic-entry mode (@kbd{m a}), fraction mode (@kbd{m f}), and
20895 symbolic mode (@kbd{m s}).  @xref{Mode Settings}, for discussions
20896 of these modes.  You may also wish to select ``big'' display mode (@kbd{d B}).
20897 @xref{Normal Language Modes}.@refill
20899 @menu
20900 * Selecting Subformulas::
20901 * Algebraic Manipulation::
20902 * Simplifying Formulas::
20903 * Polynomials::
20904 * Calculus::
20905 * Solving Equations::
20906 * Numerical Solutions::
20907 * Curve Fitting::
20908 * Summations::
20909 * Logical Operations::
20910 * Rewrite Rules::
20911 @end menu
20913 @node Selecting Subformulas, Algebraic Manipulation, Algebra, Algebra
20914 @section Selecting Sub-Formulas
20916 @noindent
20917 @cindex Selections
20918 @cindex Sub-formulas
20919 @cindex Parts of formulas
20920 When working with an algebraic formula it is often necessary to
20921 manipulate a portion of the formula rather than the formula as a
20922 whole.  Calc allows you to ``select'' a portion of any formula on
20923 the stack.  Commands which would normally operate on that stack
20924 entry will now operate only on the sub-formula, leaving the
20925 surrounding part of the stack entry alone.
20927 One common non-algebraic use for selection involves vectors.  To work
20928 on one element of a vector in-place, simply select that element as a
20929 ``sub-formula'' of the vector.
20931 @menu
20932 * Making Selections::
20933 * Changing Selections::
20934 * Displaying Selections::
20935 * Operating on Selections::
20936 * Rearranging with Selections::
20937 @end menu
20939 @node Making Selections, Changing Selections, Selecting Subformulas, Selecting Subformulas
20940 @subsection Making Selections
20942 @noindent
20943 @kindex j s
20944 @pindex calc-select-here
20945 To select a sub-formula, move the Emacs cursor to any character in that
20946 sub-formula, and press @w{@kbd{j s}} (@code{calc-select-here}).  Calc will
20947 highlight the smallest portion of the formula that contains that
20948 character.  By default the sub-formula is highlighted by blanking out
20949 all of the rest of the formula with dots.  Selection works in any
20950 display mode but is perhaps easiest in ``big'' (@kbd{d B}) mode.
20951 Suppose you enter the following formula:
20953 @group
20954 @smallexample
20955            3    ___
20956     (a + b)  + V c
20957 1:  ---------------
20958         2 x + 1
20959 @end smallexample
20960 @end group
20962 @noindent
20963 (by typing @kbd{' ((a+b)^3 + sqrt(c)) / (2x+1)}).  If you move the
20964 cursor to the letter @samp{b} and press @w{@kbd{j s}}, the display changes
20967 @group
20968 @smallexample
20969            .    ...
20970     .. . b.  . . .
20971 1*  ...............
20972         . . . .
20973 @end smallexample
20974 @end group
20976 @noindent
20977 Every character not part of the sub-formula @samp{b} has been changed
20978 to a dot.  The @samp{*} next to the line number is to remind you that
20979 the formula has a portion of it selected.  (In this case, it's very
20980 obvious, but it might not always be.  If Embedded Mode is enabled,
20981 the word @samp{Sel} also appears in the mode line because the stack
20982 may not be visible.  @pxref{Embedded Mode}.)
20984 If you had instead placed the cursor on the parenthesis immediately to
20985 the right of the @samp{b}, the selection would have been:
20987 @group
20988 @smallexample
20989            .    ...
20990     (a + b)  . . .
20991 1*  ...............
20992         . . . .
20993 @end smallexample
20994 @end group
20996 @noindent
20997 The portion selected is always large enough to be considered a complete
20998 formula all by itself, so selecting the parenthesis selects the whole
20999 formula that it encloses.  Putting the cursor on the the @samp{+} sign
21000 would have had the same effect.
21002 (Strictly speaking, the Emacs cursor is really the manifestation of
21003 the Emacs ``point,'' which is a position @emph{between} two characters
21004 in the buffer.  So purists would say that Calc selects the smallest
21005 sub-formula which contains the character to the right of ``point.'')
21007 If you supply a numeric prefix argument @var{n}, the selection is
21008 expanded to the @var{n}th enclosing sub-formula.  Thus, positioning
21009 the cursor on the @samp{b} and typing @kbd{C-u 1 j s} will select
21010 @samp{a + b}; typing @kbd{C-u 2 j s} will select @samp{(a + b)^3},
21011 and so on.
21013 If the cursor is not on any part of the formula, or if you give a
21014 numeric prefix that is too large, the entire formula is selected.
21016 If the cursor is on the @samp{.} line that marks the top of the stack
21017 (i.e., its normal ``rest position''), this command selects the entire
21018 formula at stack level 1.  Most selection commands similarly operate
21019 on the formula at the top of the stack if you haven't positioned the
21020 cursor on any stack entry.
21022 @kindex j a
21023 @pindex calc-select-additional
21024 The @kbd{j a} (@code{calc-select-additional}) command enlarges the
21025 current selection to encompass the cursor.  To select the smallest
21026 sub-formula defined by two different points, move to the first and
21027 press @kbd{j s}, then move to the other and press @kbd{j a}.  This
21028 is roughly analogous to using @kbd{C-@@} (@code{set-mark-command}) to
21029 select the two ends of a region of text during normal Emacs editing.
21031 @kindex j o
21032 @pindex calc-select-once
21033 The @kbd{j o} (@code{calc-select-once}) command selects a formula in
21034 exactly the same way as @kbd{j s}, except that the selection will
21035 last only as long as the next command that uses it.  For example,
21036 @kbd{j o 1 +} is a handy way to add one to the sub-formula indicated
21037 by the cursor.
21039 (A somewhat more precise definition: The @kbd{j o} command sets a flag
21040 such that the next command involving selected stack entries will clear
21041 the selections on those stack entries afterwards.  All other selection
21042 commands except @kbd{j a} and @kbd{j O} clear this flag.)
21044 @kindex j S
21045 @kindex j O
21046 @pindex calc-select-here-maybe
21047 @pindex calc-select-once-maybe
21048 The @kbd{j S} (@code{calc-select-here-maybe}) and @kbd{j O}
21049 (@code{calc-select-once-maybe}) commands are equivalent to @kbd{j s}
21050 and @kbd{j o}, respectively, except that if the formula already
21051 has a selection they have no effect.  This is analogous to the
21052 behavior of some commands such as @kbd{j r} (@code{calc-rewrite-selection};
21053 @pxref{Selections with Rewrite Rules}) and is mainly intended to be
21054 used in keyboard macros that implement your own selection-oriented
21055 commands.@refill
21057 Selection of sub-formulas normally treats associative terms like
21058 @samp{a + b - c + d} and @samp{x * y * z} as single levels of the formula.
21059 If you place the cursor anywhere inside @samp{a + b - c + d} except
21060 on one of the variable names and use @kbd{j s}, you will select the
21061 entire four-term sum.
21063 @kindex j b
21064 @pindex calc-break-selections
21065 The @kbd{j b} (@code{calc-break-selections}) command controls a mode
21066 in which the ``deep structure'' of these associative formulas shows
21067 through.  Calc actually stores the above formulas as @samp{((a + b) - c) + d}
21068 and @samp{x * (y * z)}.  (Note that for certain obscure reasons, Calc
21069 treats multiplication as right-associative.)  Once you have enabled
21070 @kbd{j b} mode, selecting with the cursor on the @samp{-} sign would
21071 only select the @samp{a + b - c} portion, which makes sense when the
21072 deep structure of the sum is considered.  There is no way to select
21073 the @samp{b - c + d} portion; although this might initially look
21074 like just as legitimate a sub-formula as @samp{a + b - c}, the deep
21075 structure shows that it isn't.  The @kbd{d U} command can be used
21076 to view the deep structure of any formula (@pxref{Normal Language Modes}).
21078 When @kbd{j b} mode has not been enabled, the deep structure is
21079 generally hidden by the selection commands---what you see is what
21080 you get.
21082 @kindex j u
21083 @pindex calc-unselect
21084 The @kbd{j u} (@code{calc-unselect}) command unselects the formula
21085 that the cursor is on.  If there was no selection in the formula,
21086 this command has no effect.  With a numeric prefix argument, it
21087 unselects the @var{n}th stack element rather than using the cursor
21088 position.
21090 @kindex j c
21091 @pindex calc-clear-selections
21092 The @kbd{j c} (@code{calc-clear-selections}) command unselects all
21093 stack elements.
21095 @node Changing Selections, Displaying Selections, Making Selections, Selecting Subformulas
21096 @subsection Changing Selections
21098 @noindent
21099 @kindex j m
21100 @pindex calc-select-more
21101 Once you have selected a sub-formula, you can expand it using the
21102 @w{@kbd{j m}} (@code{calc-select-more}) command.  If @samp{a + b} is
21103 selected, pressing @w{@kbd{j m}} repeatedly works as follows:
21105 @group
21106 @smallexample
21107            3    ...                3    ___                3    ___
21108     (a + b)  . . .          (a + b)  + V c          (a + b)  + V c
21109 1*  ...............     1*  ...............     1*  ---------------
21110         . . . .                 . . . .                 2 x + 1
21111 @end smallexample
21112 @end group
21114 @noindent
21115 In the last example, the entire formula is selected.  This is roughly
21116 the same as having no selection at all, but because there are subtle
21117 differences the @samp{*} character is still there on the line number.
21119 With a numeric prefix argument @var{n}, @kbd{j m} expands @var{n}
21120 times (or until the entire formula is selected).  Note that @kbd{j s}
21121 with argument @var{n} is equivalent to plain @kbd{j s} followed by
21122 @kbd{j m} with argument @var{n}.  If @w{@kbd{j m}} is used when there
21123 is no current selection, it is equivalent to @w{@kbd{j s}}.
21125 Even though @kbd{j m} does not explicitly use the location of the
21126 cursor within the formula, it nevertheless uses the cursor to determine
21127 which stack element to operate on.  As usual, @kbd{j m} when the cursor
21128 is not on any stack element operates on the top stack element.
21130 @kindex j l
21131 @pindex calc-select-less
21132 The @kbd{j l} (@code{calc-select-less}) command reduces the current
21133 selection around the cursor position.  That is, it selects the
21134 immediate sub-formula of the current selection which contains the
21135 cursor, the opposite of @kbd{j m}.  If the cursor is not inside the
21136 current selection, the command de-selects the formula.
21138 @kindex j 1-9
21139 @pindex calc-select-part
21140 The @kbd{j 1} through @kbd{j 9} (@code{calc-select-part}) commands
21141 select the @var{n}th sub-formula of the current selection.  They are
21142 like @kbd{j l} (@code{calc-select-less}) except they use counting
21143 rather than the cursor position to decide which sub-formula to select.
21144 For example, if the current selection is @kbd{a + b + c} or
21145 @kbd{f(a, b, c)} or @kbd{[a, b, c]}, then @kbd{j 1} selects @samp{a},
21146 @kbd{j 2} selects @samp{b}, and @kbd{j 3} selects @samp{c}; in each of
21147 these cases, @kbd{j 4} through @kbd{j 9} would be errors.
21149 If there is no current selection, @kbd{j 1} through @kbd{j 9} select
21150 the @var{n}th top-level sub-formula.  (In other words, they act as if
21151 the entire stack entry were selected first.)  To select the @var{n}th
21152 sub-formula where @var{n} is greater than nine, you must instead invoke
21153 @w{@kbd{j 1}} with @var{n} as a numeric prefix argument.@refill
21155 @kindex j n
21156 @kindex j p
21157 @pindex calc-select-next
21158 @pindex calc-select-previous
21159 The @kbd{j n} (@code{calc-select-next}) and @kbd{j p}
21160 (@code{calc-select-previous}) commands change the current selection
21161 to the next or previous sub-formula at the same level.  For example,
21162 if @samp{b} is selected in @w{@samp{2 + a*b*c + x}}, then @kbd{j n}
21163 selects @samp{c}.  Further @kbd{j n} commands would be in error because,
21164 even though there is something to the right of @samp{c} (namely, @samp{x}),
21165 it is not at the same level; in this case, it is not a term of the
21166 same product as @samp{b} and @samp{c}.  However, @kbd{j m} (to select
21167 the whole product @samp{a*b*c} as a term of the sum) followed by
21168 @w{@kbd{j n}} would successfully select the @samp{x}.
21170 Similarly, @kbd{j p} moves the selection from the @samp{b} in this
21171 sample formula to the @samp{a}.  Both commands accept numeric prefix
21172 arguments to move several steps at a time.
21174 It is interesting to compare Calc's selection commands with the
21175 Emacs Info system's commands for navigating through hierarchically
21176 organized documentation.  Calc's @kbd{j n} command is completely
21177 analogous to Info's @kbd{n} command.  Likewise, @kbd{j p} maps to
21178 @kbd{p}, @kbd{j 2} maps to @kbd{2}, and Info's @kbd{u} is like @kbd{j m}.
21179 (Note that @kbd{j u} stands for @code{calc-unselect}, not ``up''.)
21180 The Info @kbd{m} command is somewhat similar to Calc's @kbd{j s} and
21181 @kbd{j l}; in each case, you can jump directly to a sub-component
21182 of the hierarchy simply by pointing to it with the cursor.
21184 @node Displaying Selections, Operating on Selections, Changing Selections, Selecting Subformulas
21185 @subsection Displaying Selections
21187 @noindent
21188 @kindex j d
21189 @pindex calc-show-selections
21190 The @kbd{j d} (@code{calc-show-selections}) command controls how
21191 selected sub-formulas are displayed.  One of the alternatives is
21192 illustrated in the above examples; if we press @kbd{j d} we switch
21193 to the other style in which the selected portion itself is obscured
21194 by @samp{#} signs:
21196 @group
21197 @smallexample
21198            3    ...                  #    ___
21199     (a + b)  . . .            ## # ##  + V c
21200 1*  ...............       1*  ---------------
21201         . . . .                   2 x + 1
21202 @end smallexample
21203 @end group
21205 @node Operating on Selections, Rearranging with Selections, Displaying Selections, Selecting Subformulas
21206 @subsection Operating on Selections
21208 @noindent
21209 Once a selection is made, all Calc commands that manipulate items
21210 on the stack will operate on the selected portions of the items
21211 instead.  (Note that several stack elements may have selections
21212 at once, though there can be only one selection at a time in any
21213 given stack element.)
21215 @kindex j e
21216 @pindex calc-enable-selections
21217 The @kbd{j e} (@code{calc-enable-selections}) command disables the
21218 effect that selections have on Calc commands.  The current selections
21219 still exist, but Calc commands operate on whole stack elements anyway.
21220 This mode can be identified by the fact that the @samp{*} markers on
21221 the line numbers are gone, even though selections are visible.  To
21222 reactivate the selections, press @kbd{j e} again.
21224 To extract a sub-formula as a new formula, simply select the
21225 sub-formula and press @key{RET}.  This normally duplicates the top
21226 stack element; here it duplicates only the selected portion of that
21227 element.
21229 To replace a sub-formula with something different, you can enter the
21230 new value onto the stack and press @key{TAB}.  This normally exchanges
21231 the top two stack elements; here it swaps the value you entered into
21232 the selected portion of the formula, returning the old selected
21233 portion to the top of the stack.
21235 @group
21236 @smallexample
21237            3    ...                    ...                    ___
21238     (a + b)  . . .           17 x y . . .           17 x y + V c
21239 2*  ...............      2*  .............      2:  -------------
21240         . . . .                 . . . .                2 x + 1
21242                                     3                      3
21243 1:  17 x y               1:  (a + b)            1:  (a + b)
21244 @end smallexample
21245 @end group
21247 In this example we select a sub-formula of our original example,
21248 enter a new formula, @key{TAB} it into place, then deselect to see
21249 the complete, edited formula.
21251 If you want to swap whole formulas around even though they contain
21252 selections, just use @kbd{j e} before and after.
21254 @kindex j '
21255 @pindex calc-enter-selection
21256 The @kbd{j '} (@code{calc-enter-selection}) command is another way
21257 to replace a selected sub-formula.  This command does an algebraic
21258 entry just like the regular @kbd{'} key.  When you press @key{RET},
21259 the formula you type replaces the original selection.  You can use
21260 the @samp{$} symbol in the formula to refer to the original
21261 selection.  If there is no selection in the formula under the cursor,
21262 the cursor is used to make a temporary selection for the purposes of
21263 the command.  Thus, to change a term of a formula, all you have to
21264 do is move the Emacs cursor to that term and press @kbd{j '}.
21266 @kindex j `
21267 @pindex calc-edit-selection
21268 The @kbd{j `} (@code{calc-edit-selection}) command is a similar
21269 analogue of the @kbd{`} (@code{calc-edit}) command.  It edits the
21270 selected sub-formula in a separate buffer.  If there is no
21271 selection, it edits the sub-formula indicated by the cursor.
21273 To delete a sub-formula, press @key{DEL}.  This generally replaces
21274 the sub-formula with the constant zero, but in a few suitable contexts
21275 it uses the constant one instead.  The @key{DEL} key automatically
21276 deselects and re-simplifies the entire formula afterwards.  Thus:
21278 @group
21279 @smallexample
21280               ###
21281     17 x y + # #          17 x y         17 # y          17 y
21282 1*  -------------     1:  -------    1*  -------    1:  -------
21283        2 x + 1            2 x + 1        2 x + 1        2 x + 1
21284 @end smallexample
21285 @end group
21287 In this example, we first delete the @samp{sqrt(c)} term; Calc
21288 accomplishes this by replacing @samp{sqrt(c)} with zero and
21289 resimplifying.  We then delete the @kbd{x} in the numerator;
21290 since this is part of a product, Calc replaces it with @samp{1}
21291 and resimplifies.
21293 If you select an element of a vector and press @key{DEL}, that
21294 element is deleted from the vector.  If you delete one side of
21295 an equation or inequality, only the opposite side remains.
21297 @kindex j DEL
21298 @pindex calc-del-selection
21299 The @kbd{j @key{DEL}} (@code{calc-del-selection}) command is like
21300 @key{DEL} but with the auto-selecting behavior of @kbd{j '} and
21301 @kbd{j `}.  It deletes the selected portion of the formula
21302 indicated by the cursor, or, in the absence of a selection, it
21303 deletes the sub-formula indicated by the cursor position.
21305 @kindex j RET
21306 @pindex calc-grab-selection
21307 (There is also an auto-selecting @kbd{j @key{RET}} (@code{calc-copy-selection})
21308 command.)
21310 Normal arithmetic operations also apply to sub-formulas.  Here we
21311 select the denominator, press @kbd{5 -} to subtract five from the
21312 denominator, press @kbd{n} to negate the denominator, then
21313 press @kbd{Q} to take the square root.
21315 @group
21316 @smallexample
21317      .. .           .. .           .. .             .. .
21318 1*  .......    1*  .......    1*  .......    1*  ..........
21319     2 x + 1        2 x - 4        4 - 2 x         _________
21320                                                  V 4 - 2 x
21321 @end smallexample
21322 @end group
21324 Certain types of operations on selections are not allowed.  For
21325 example, for an arithmetic function like @kbd{-} no more than one of
21326 the arguments may be a selected sub-formula.  (As the above example
21327 shows, the result of the subtraction is spliced back into the argument
21328 which had the selection; if there were more than one selection involved,
21329 this would not be well-defined.)  If you try to subtract two selections,
21330 the command will abort with an error message.
21332 Operations on sub-formulas sometimes leave the formula as a whole
21333 in an ``un-natural'' state.  Consider negating the @samp{2 x} term
21334 of our sample formula by selecting it and pressing @kbd{n}
21335 (@code{calc-change-sign}).@refill
21337 @group
21338 @smallexample
21339        .. .                .. .
21340 1*  ..........      1*  ...........
21341      .........           ..........
21342     . . . 2 x           . . . -2 x
21343 @end smallexample
21344 @end group
21346 Unselecting the sub-formula reveals that the minus sign, which would
21347 normally have cancelled out with the subtraction automatically, has
21348 not been able to do so because the subtraction was not part of the
21349 selected portion.  Pressing @kbd{=} (@code{calc-evaluate}) or doing
21350 any other mathematical operation on the whole formula will cause it
21351 to be simplified.
21353 @group
21354 @smallexample
21355        17 y                17 y
21356 1:  -----------     1:  ----------
21357      __________          _________
21358     V 4 - -2 x          V 4 + 2 x
21359 @end smallexample
21360 @end group
21362 @node Rearranging with Selections, , Operating on Selections, Selecting Subformulas
21363 @subsection Rearranging Formulas using Selections
21365 @noindent
21366 @kindex j R
21367 @pindex calc-commute-right
21368 The @kbd{j R} (@code{calc-commute-right}) command moves the selected
21369 sub-formula to the right in its surrounding formula.  Generally the
21370 selection is one term of a sum or product; the sum or product is
21371 rearranged according to the commutative laws of algebra.
21373 As with @kbd{j '} and @kbd{j DEL}, the term under the cursor is used
21374 if there is no selection in the current formula.  All commands described
21375 in this section share this property.  In this example, we place the
21376 cursor on the @samp{a} and type @kbd{j R}, then repeat.
21378 @smallexample
21379 1:  a + b - c          1:  b + a - c          1:  b - c + a
21380 @end smallexample
21382 @noindent
21383 Note that in the final step above, the @samp{a} is switched with
21384 the @samp{c} but the signs are adjusted accordingly.  When moving
21385 terms of sums and products, @kbd{j R} will never change the
21386 mathematical meaning of the formula.
21388 The selected term may also be an element of a vector or an argument
21389 of a function.  The term is exchanged with the one to its right.
21390 In this case, the ``meaning'' of the vector or function may of
21391 course be drastically changed.
21393 @smallexample
21394 1:  [a, b, c]          1:  [b, a, c]          1:  [b, c, a]
21396 1:  f(a, b, c)         1:  f(b, a, c)         1:  f(b, c, a)
21397 @end smallexample
21399 @kindex j L
21400 @pindex calc-commute-left
21401 The @kbd{j L} (@code{calc-commute-left}) command is like @kbd{j R}
21402 except that it swaps the selected term with the one to its left.
21404 With numeric prefix arguments, these commands move the selected
21405 term several steps at a time.  It is an error to try to move a
21406 term left or right past the end of its enclosing formula.
21407 With numeric prefix arguments of zero, these commands move the
21408 selected term as far as possible in the given direction.
21410 @kindex j D
21411 @pindex calc-sel-distribute
21412 The @kbd{j D} (@code{calc-sel-distribute}) command mixes the selected
21413 sum or product into the surrounding formula using the distributive
21414 law.  For example, in @samp{a * (b - c)} with the @samp{b - c}
21415 selected, the result is @samp{a b - a c}.  This also distributes
21416 products or quotients into surrounding powers, and can also do
21417 transformations like @samp{exp(a + b)} to @samp{exp(a) exp(b)},
21418 where @samp{a + b} is the selected term, and @samp{ln(a ^ b)}
21419 to @samp{ln(a) b}, where @samp{a ^ b} is the selected term.
21421 For multiple-term sums or products, @kbd{j D} takes off one term
21422 at a time:  @samp{a * (b + c - d)} goes to @samp{a * (c - d) + a b}
21423 with the @samp{c - d} selected so that you can type @kbd{j D}
21424 repeatedly to expand completely.  The @kbd{j D} command allows a
21425 numeric prefix argument which specifies the maximum number of
21426 times to expand at once; the default is one time only.
21428 @vindex DistribRules
21429 The @kbd{j D} command is implemented using rewrite rules.
21430 @xref{Selections with Rewrite Rules}.  The rules are stored in
21431 the Calc variable @code{DistribRules}.  A convenient way to view
21432 these rules is to use @kbd{s e} (@code{calc-edit-variable}) which
21433 displays and edits the stored value of a variable.  Press @key{M-# M-#}
21434 to return from editing mode; be careful not to make any actual changes
21435 or else you will affect the behavior of future @kbd{j D} commands!
21437 To extend @kbd{j D} to handle new cases, just edit @code{DistribRules}
21438 as described above.  You can then use the @kbd{s p} command to save
21439 this variable's value permanently for future Calc sessions.
21440 @xref{Operations on Variables}.
21442 @kindex j M
21443 @pindex calc-sel-merge
21444 @vindex MergeRules
21445 The @kbd{j M} (@code{calc-sel-merge}) command is the complement
21446 of @kbd{j D}; given @samp{a b - a c} with either @samp{a b} or
21447 @samp{a c} selected, the result is @samp{a * (b - c)}.  Once
21448 again, @kbd{j M} can also merge calls to functions like @code{exp}
21449 and @code{ln}; examine the variable @code{MergeRules} to see all
21450 the relevant rules.
21452 @kindex j C
21453 @pindex calc-sel-commute
21454 @vindex CommuteRules
21455 The @kbd{j C} (@code{calc-sel-commute}) command swaps the arguments
21456 of the selected sum, product, or equation.  It always behaves as
21457 if @kbd{j b} mode were in effect, i.e., the sum @samp{a + b + c} is
21458 treated as the nested sums @samp{(a + b) + c} by this command.
21459 If you put the cursor on the first @samp{+}, the result is
21460 @samp{(b + a) + c}; if you put the cursor on the second @samp{+}, the
21461 result is @samp{c + (a + b)} (which the default simplifications
21462 will rearrange to @samp{(c + a) + b}).  The relevant rules are stored
21463 in the variable @code{CommuteRules}.
21465 You may need to turn default simplifications off (with the @kbd{m O}
21466 command) in order to get the full benefit of @kbd{j C}.  For example,
21467 commuting @samp{a - b} produces @samp{-b + a}, but the default
21468 simplifications will ``simplify'' this right back to @samp{a - b} if
21469 you don't turn them off.  The same is true of some of the other
21470 manipulations described in this section.
21472 @kindex j N
21473 @pindex calc-sel-negate
21474 @vindex NegateRules
21475 The @kbd{j N} (@code{calc-sel-negate}) command replaces the selected
21476 term with the negative of that term, then adjusts the surrounding
21477 formula in order to preserve the meaning.  For example, given
21478 @samp{exp(a - b)} where @samp{a - b} is selected, the result is
21479 @samp{1 / exp(b - a)}.  By contrast, selecting a term and using the
21480 regular @kbd{n} (@code{calc-change-sign}) command negates the
21481 term without adjusting the surroundings, thus changing the meaning
21482 of the formula as a whole.  The rules variable is @code{NegateRules}.
21484 @kindex j &
21485 @pindex calc-sel-invert
21486 @vindex InvertRules
21487 The @kbd{j &} (@code{calc-sel-invert}) command is similar to @kbd{j N}
21488 except it takes the reciprocal of the selected term.  For example,
21489 given @samp{a - ln(b)} with @samp{b} selected, the result is
21490 @samp{a + ln(1/b)}.  The rules variable is @code{InvertRules}.
21492 @kindex j E
21493 @pindex calc-sel-jump-equals
21494 @vindex JumpRules
21495 The @kbd{j E} (@code{calc-sel-jump-equals}) command moves the
21496 selected term from one side of an equation to the other.  Given
21497 @samp{a + b = c + d} with @samp{c} selected, the result is
21498 @samp{a + b - c = d}.  This command also works if the selected
21499 term is part of a @samp{*}, @samp{/}, or @samp{^} formula.  The
21500 relevant rules variable is @code{JumpRules}.
21502 @kindex j I
21503 @kindex H j I
21504 @pindex calc-sel-isolate
21505 The @kbd{j I} (@code{calc-sel-isolate}) command isolates the
21506 selected term on its side of an equation.  It uses the @kbd{a S}
21507 (@code{calc-solve-for}) command to solve the equation, and the
21508 Hyperbolic flag affects it in the same way.  @xref{Solving Equations}.
21509 When it applies, @kbd{j I} is often easier to use than @kbd{j E}.
21510 It understands more rules of algebra, and works for inequalities
21511 as well as equations.
21513 @kindex j *
21514 @kindex j /
21515 @pindex calc-sel-mult-both-sides
21516 @pindex calc-sel-div-both-sides
21517 The @kbd{j *} (@code{calc-sel-mult-both-sides}) command prompts for a
21518 formula using algebraic entry, then multiplies both sides of the
21519 selected quotient or equation by that formula.  It simplifies each
21520 side with @kbd{a s} (@code{calc-simplify}) before re-forming the
21521 quotient or equation.  You can suppress this simplification by
21522 providing any numeric prefix argument.  There is also a @kbd{j /}
21523 (@code{calc-sel-div-both-sides}) which is similar to @kbd{j *} but
21524 dividing instead of multiplying by the factor you enter.
21526 As a special feature, if the numerator of the quotient is 1, then
21527 the denominator is expanded at the top level using the distributive
21528 law (i.e., using the @kbd{C-u -1 a x} command).  Suppose the
21529 formula on the stack is @samp{1 / (sqrt(a) + 1)}, and you wish
21530 to eliminate the square root in the denominator by multiplying both
21531 sides by @samp{sqrt(a) - 1}.  Calc's default simplifications would
21532 change the result @samp{(sqrt(a) - 1) / (sqrt(a) - 1) (sqrt(a) + 1)}
21533 right back to the original form by cancellation; Calc expands the
21534 denominator to @samp{sqrt(a) (sqrt(a) - 1) + sqrt(a) - 1} to prevent
21535 this.  (You would now want to use an @kbd{a x} command to expand
21536 the rest of the way, whereupon the denominator would cancel out to
21537 the desired form, @samp{a - 1}.)  When the numerator is not 1, this
21538 initial expansion is not necessary because Calc's default
21539 simplifications will not notice the potential cancellation.
21541 If the selection is an inequality, @kbd{j *} and @kbd{j /} will
21542 accept any factor, but will warn unless they can prove the factor
21543 is either positive or negative.  (In the latter case the direction
21544 of the inequality will be switched appropriately.)  @xref{Declarations},
21545 for ways to inform Calc that a given variable is positive or
21546 negative.  If Calc can't tell for sure what the sign of the factor
21547 will be, it will assume it is positive and display a warning
21548 message.
21550 For selections that are not quotients, equations, or inequalities,
21551 these commands pull out a multiplicative factor:  They divide (or
21552 multiply) by the entered formula, simplify, then multiply (or divide)
21553 back by the formula.
21555 @kindex j +
21556 @kindex j -
21557 @pindex calc-sel-add-both-sides
21558 @pindex calc-sel-sub-both-sides
21559 The @kbd{j +} (@code{calc-sel-add-both-sides}) and @kbd{j -}
21560 (@code{calc-sel-sub-both-sides}) commands analogously add to or
21561 subtract from both sides of an equation or inequality.  For other
21562 types of selections, they extract an additive factor.  A numeric
21563 prefix argument suppresses simplification of the intermediate
21564 results.
21566 @kindex j U
21567 @pindex calc-sel-unpack
21568 The @kbd{j U} (@code{calc-sel-unpack}) command replaces the
21569 selected function call with its argument.  For example, given
21570 @samp{a + sin(x^2)} with @samp{sin(x^2)} selected, the result
21571 is @samp{a + x^2}.  (The @samp{x^2} will remain selected; if you
21572 wanted to change the @code{sin} to @code{cos}, just press @kbd{C}
21573 now to take the cosine of the selected part.)
21575 @kindex j v
21576 @pindex calc-sel-evaluate
21577 The @kbd{j v} (@code{calc-sel-evaluate}) command performs the
21578 normal default simplifications on the selected sub-formula.
21579 These are the simplifications that are normally done automatically
21580 on all results, but which may have been partially inhibited by
21581 previous selection-related operations, or turned off altogether
21582 by the @kbd{m O} command.  This command is just an auto-selecting
21583 version of the @w{@kbd{a v}} command (@pxref{Algebraic Manipulation}).
21585 With a numeric prefix argument of 2, @kbd{C-u 2 j v} applies
21586 the @kbd{a s} (@code{calc-simplify}) command to the selected
21587 sub-formula.  With a prefix argument of 3 or more, e.g., @kbd{C-u j v}
21588 applies the @kbd{a e} (@code{calc-simplify-extended}) command.
21589 @xref{Simplifying Formulas}.  With a negative prefix argument
21590 it simplifies at the top level only, just as with @kbd{a v}.
21591 Here the ``top'' level refers to the top level of the selected
21592 sub-formula.
21594 @kindex j "
21595 @pindex calc-sel-expand-formula
21596 The @kbd{j "} (@code{calc-sel-expand-formula}) command is to @kbd{a "}
21597 (@pxref{Algebraic Manipulation}) what @kbd{j v} is to @kbd{a v}.
21599 You can use the @kbd{j r} (@code{calc-rewrite-selection}) command
21600 to define other algebraic operations on sub-formulas.  @xref{Rewrite Rules}.
21602 @node Algebraic Manipulation, Simplifying Formulas, Selecting Subformulas, Algebra
21603 @section Algebraic Manipulation
21605 @noindent
21606 The commands in this section perform general-purpose algebraic
21607 manipulations.  They work on the whole formula at the top of the
21608 stack (unless, of course, you have made a selection in that
21609 formula).
21611 Many algebra commands prompt for a variable name or formula.  If you
21612 answer the prompt with a blank line, the variable or formula is taken
21613 from top-of-stack, and the normal argument for the command is taken
21614 from the second-to-top stack level.
21616 @kindex a v
21617 @pindex calc-alg-evaluate
21618 The @kbd{a v} (@code{calc-alg-evaluate}) command performs the normal
21619 default simplifications on a formula; for example, @samp{a - -b} is
21620 changed to @samp{a + b}.  These simplifications are normally done
21621 automatically on all Calc results, so this command is useful only if
21622 you have turned default simplifications off with an @kbd{m O}
21623 command.  @xref{Simplification Modes}.
21625 It is often more convenient to type @kbd{=}, which is like @kbd{a v}
21626 but which also substitutes stored values for variables in the formula.
21627 Use @kbd{a v} if you want the variables to ignore their stored values.
21629 If you give a numeric prefix argument of 2 to @kbd{a v}, it simplifies
21630 as if in algebraic simplification mode.  This is equivalent to typing
21631 @kbd{a s}; @pxref{Simplifying Formulas}.  If you give a numeric prefix
21632 of 3 or more, it uses extended simplification mode (@kbd{a e}).
21634 If you give a negative prefix argument @i{-1}, @i{-2}, or @i{-3},
21635 it simplifies in the corresponding mode but only works on the top-level
21636 function call of the formula.  For example, @samp{(2 + 3) * (2 + 3)} will
21637 simplify to @samp{(2 + 3)^2}, without simplifying the sub-formulas
21638 @samp{2 + 3}.  As another example, typing @kbd{V R +} to sum the vector
21639 @samp{[1, 2, 3, 4]} produces the formula @samp{reduce(add, [1, 2, 3, 4])}
21640 in no-simplify mode.  Using @kbd{a v} will evaluate this all the way to
21641 10; using @kbd{C-u - a v} will evaluate it only to @samp{1 + 2 + 3 + 4}.
21642 (@xref{Reducing and Mapping}.)
21644 @tindex evalv
21645 @tindex evalvn
21646 The @kbd{=} command corresponds to the @code{evalv} function, and
21647 the related @kbd{N} command, which is like @kbd{=} but temporarily
21648 disables symbolic (@kbd{m s}) mode during the evaluation, corresponds
21649 to the @code{evalvn} function.  (These commands interpret their prefix
21650 arguments differently than @kbd{a v}; @kbd{=} treats the prefix as
21651 the number of stack elements to evaluate at once, and @kbd{N} treats
21652 it as a temporary different working precision.)
21654 The @code{evalvn} function can take an alternate working precision
21655 as an optional second argument.  This argument can be either an
21656 integer, to set the precision absolutely, or a vector containing
21657 a single integer, to adjust the precision relative to the current
21658 precision.  Note that @code{evalvn} with a larger than current
21659 precision will do the calculation at this higher precision, but the
21660 result will as usual be rounded back down to the current precision
21661 afterward.  For example, @samp{evalvn(pi - 3.1415)} at a precision
21662 of 12 will return @samp{9.265359e-5}; @samp{evalvn(pi - 3.1415, 30)}
21663 will return @samp{9.26535897932e-5} (computing a 25-digit result which
21664 is then rounded down to 12); and @samp{evalvn(pi - 3.1415, [-2])}
21665 will return @samp{9.2654e-5}.
21667 @kindex a "
21668 @pindex calc-expand-formula
21669 The @kbd{a "} (@code{calc-expand-formula}) command expands functions
21670 into their defining formulas wherever possible.  For example,
21671 @samp{deg(x^2)} is changed to @samp{180 x^2 / pi}.  Most functions,
21672 like @code{sin} and @code{gcd}, are not defined by simple formulas
21673 and so are unaffected by this command.  One important class of
21674 functions which @emph{can} be expanded is the user-defined functions
21675 created by the @kbd{Z F} command.  @xref{Algebraic Definitions}.
21676 Other functions which @kbd{a "} can expand include the probability
21677 distribution functions, most of the financial functions, and the
21678 hyperbolic and inverse hyperbolic functions.  A numeric prefix argument
21679 affects @kbd{a "} in the same way as it does @kbd{a v}:  A positive
21680 argument expands all functions in the formula and then simplifies in
21681 various ways; a negative argument expands and simplifies only the
21682 top-level function call.
21684 @kindex a M
21685 @pindex calc-map-equation
21686 @tindex mapeq
21687 The @kbd{a M} (@code{calc-map-equation}) [@code{mapeq}] command applies
21688 a given function or operator to one or more equations.  It is analogous
21689 to @kbd{V M}, which operates on vectors instead of equations.
21690 @pxref{Reducing and Mapping}.  For example, @kbd{a M S} changes
21691 @samp{x = y+1} to @samp{sin(x) = sin(y+1)}, and @kbd{a M +} with
21692 @samp{x = y+1} and @cite{6} on the stack produces @samp{x+6 = y+7}.
21693 With two equations on the stack, @kbd{a M +} would add the lefthand
21694 sides together and the righthand sides together to get the two
21695 respective sides of a new equation.
21697 Mapping also works on inequalities.  Mapping two similar inequalities
21698 produces another inequality of the same type.  Mapping an inequality
21699 with an equation produces an inequality of the same type.  Mapping a
21700 @samp{<=} with a @samp{<} or @samp{!=} (not-equal) produces a @samp{<}.
21701 If inequalities with opposite direction (e.g., @samp{<} and @samp{>})
21702 are mapped, the direction of the second inequality is reversed to
21703 match the first:  Using @kbd{a M +} on @samp{a < b} and @samp{a > 2}
21704 reverses the latter to get @samp{2 < a}, which then allows the
21705 combination @samp{a + 2 < b + a}, which the @kbd{a s} command can
21706 then simplify to get @samp{2 < b}.
21708 Using @kbd{a M *}, @kbd{a M /}, @kbd{a M n}, or @kbd{a M &} to negate
21709 or invert an inequality will reverse the direction of the inequality.
21710 Other adjustments to inequalities are @emph{not} done automatically;
21711 @kbd{a M S} will change @w{@samp{x < y}} to @samp{sin(x) < sin(y)} even
21712 though this is not true for all values of the variables.
21714 @kindex H a M
21715 @tindex mapeqp
21716 With the Hyperbolic flag, @kbd{H a M} [@code{mapeqp}] does a plain
21717 mapping operation without reversing the direction of any inequalities.
21718 Thus, @kbd{H a M &} would change @kbd{x > 2} to @kbd{1/x > 0.5}.
21719 (This change is mathematically incorrect, but perhaps you were
21720 fixing an inequality which was already incorrect.)
21722 @kindex I a M
21723 @tindex mapeqr
21724 With the Inverse flag, @kbd{I a M} [@code{mapeqr}] always reverses
21725 the direction of the inequality.  You might use @kbd{I a M C} to
21726 change @samp{x < y} to @samp{cos(x) > cos(y)} if you know you are
21727 working with small positive angles.
21729 @kindex a b
21730 @pindex calc-substitute
21731 @tindex subst
21732 The @kbd{a b} (@code{calc-substitute}) [@code{subst}] command substitutes
21733 all occurrences
21734 of some variable or sub-expression of an expression with a new
21735 sub-expression.  For example, substituting @samp{sin(x)} with @samp{cos(y)}
21736 in @samp{2 sin(x)^2 + x sin(x) + sin(2 x)} produces
21737 @samp{2 cos(y)^2 + x cos(y) + @w{sin(2 x)}}.
21738 Note that this is a purely structural substitution; the lone @samp{x} and
21739 the @samp{sin(2 x)} stayed the same because they did not look like
21740 @samp{sin(x)}.  @xref{Rewrite Rules}, for a more general method for
21741 doing substitutions.@refill
21743 The @kbd{a b} command normally prompts for two formulas, the old
21744 one and the new one.  If you enter a blank line for the first
21745 prompt, all three arguments are taken from the stack (new, then old,
21746 then target expression).  If you type an old formula but then enter a
21747 blank line for the new one, the new formula is taken from top-of-stack
21748 and the target from second-to-top.  If you answer both prompts, the
21749 target is taken from top-of-stack as usual.
21751 Note that @kbd{a b} has no understanding of commutativity or
21752 associativity.  The pattern @samp{x+y} will not match the formula
21753 @samp{y+x}.  Also, @samp{y+z} will not match inside the formula @samp{x+y+z}
21754 because the @samp{+} operator is left-associative, so the ``deep
21755 structure'' of that formula is @samp{(x+y) + z}.  Use @kbd{d U}
21756 (@code{calc-unformatted-language}) mode to see the true structure of
21757 a formula.  The rewrite rule mechanism, discussed later, does not have
21758 these limitations.
21760 As an algebraic function, @code{subst} takes three arguments:
21761 Target expression, old, new.  Note that @code{subst} is always
21762 evaluated immediately, even if its arguments are variables, so if
21763 you wish to put a call to @code{subst} onto the stack you must
21764 turn the default simplifications off first (with @kbd{m O}).
21766 @node Simplifying Formulas, Polynomials, Algebraic Manipulation, Algebra
21767 @section Simplifying Formulas
21769 @noindent
21770 @kindex a s
21771 @pindex calc-simplify
21772 @tindex simplify
21773 The @kbd{a s} (@code{calc-simplify}) [@code{simplify}] command applies
21774 various algebraic rules to simplify a formula.  This includes rules which
21775 are not part of the default simplifications because they may be too slow
21776 to apply all the time, or may not be desirable all of the time.  For
21777 example, non-adjacent terms of sums are combined, as in @samp{a + b + 2 a}
21778 to @samp{b + 3 a}, and some formulas like @samp{sin(arcsin(x))} are
21779 simplified to @samp{x}.
21781 The sections below describe all the various kinds of algebraic
21782 simplifications Calc provides in full detail.  None of Calc's
21783 simplification commands are designed to pull rabbits out of hats;
21784 they simply apply certain specific rules to put formulas into
21785 less redundant or more pleasing forms.  Serious algebra in Calc
21786 must be done manually, usually with a combination of selections
21787 and rewrite rules.  @xref{Rearranging with Selections}.
21788 @xref{Rewrite Rules}.
21790 @xref{Simplification Modes}, for commands to control what level of
21791 simplification occurs automatically.  Normally only the ``default
21792 simplifications'' occur.
21794 @menu
21795 * Default Simplifications::
21796 * Algebraic Simplifications::
21797 * Unsafe Simplifications::
21798 * Simplification of Units::
21799 @end menu
21801 @node Default Simplifications, Algebraic Simplifications, Simplifying Formulas, Simplifying Formulas
21802 @subsection Default Simplifications
21804 @noindent
21805 @cindex Default simplifications
21806 This section describes the ``default simplifications,'' those which are
21807 normally applied to all results.  For example, if you enter the variable
21808 @cite{x} on the stack twice and push @kbd{+}, Calc's default
21809 simplifications automatically change @cite{x + x} to @cite{2 x}.
21811 The @kbd{m O} command turns off the default simplifications, so that
21812 @cite{x + x} will remain in this form unless you give an explicit
21813 ``simplify'' command like @kbd{=} or @kbd{a v}.  @xref{Algebraic
21814 Manipulation}.  The @kbd{m D} command turns the default simplifications
21815 back on.
21817 The most basic default simplification is the evaluation of functions.
21818 For example, @cite{2 + 3} is evaluated to @cite{5}, and @cite{@t{sqrt}(9)}
21819 is evaluated to @cite{3}.  Evaluation does not occur if the arguments
21820 to a function are somehow of the wrong type (@cite{@t{tan}([2,3,4])},
21821 range (@cite{@t{tan}(90)}), or number (@cite{@t{tan}(3,5)}), or if the
21822 function name is not recognized (@cite{@t{f}(5)}), or if ``symbolic''
21823 mode (@pxref{Symbolic Mode}) prevents evaluation (@cite{@t{sqrt}(2)}).
21825 Calc simplifies (evaluates) the arguments to a function before it
21826 simplifies the function itself.  Thus @cite{@t{sqrt}(5+4)} is
21827 simplified to @cite{@t{sqrt}(9)} before the @code{sqrt} function
21828 itself is applied.  There are very few exceptions to this rule:
21829 @code{quote}, @code{lambda}, and @code{condition} (the @code{::}
21830 operator) do not evaluate their arguments, @code{if} (the @code{? :}
21831 operator) does not evaluate all of its arguments, and @code{evalto}
21832 does not evaluate its lefthand argument.
21834 Most commands apply the default simplifications to all arguments they
21835 take from the stack, perform a particular operation, then simplify
21836 the result before pushing it back on the stack.  In the common special
21837 case of regular arithmetic commands like @kbd{+} and @kbd{Q} [@code{sqrt}],
21838 the arguments are simply popped from the stack and collected into a
21839 suitable function call, which is then simplified (the arguments being
21840 simplified first as part of the process, as described above).
21842 The default simplifications are too numerous to describe completely
21843 here, but this section will describe the ones that apply to the
21844 major arithmetic operators.  This list will be rather technical in
21845 nature, and will probably be interesting to you only if you are
21846 a serious user of Calc's algebra facilities.
21848 @tex
21849 \bigskip
21850 @end tex
21852 As well as the simplifications described here, if you have stored
21853 any rewrite rules in the variable @code{EvalRules} then these rules
21854 will also be applied before any built-in default simplifications.
21855 @xref{Automatic Rewrites}, for details.
21857 @tex
21858 \bigskip
21859 @end tex
21861 And now, on with the default simplifications:
21863 Arithmetic operators like @kbd{+} and @kbd{*} always take two
21864 arguments in Calc's internal form.  Sums and products of three or
21865 more terms are arranged by the associative law of algebra into
21866 a left-associative form for sums, @cite{((a + b) + c) + d}, and
21867 a right-associative form for products, @cite{a * (b * (c * d))}.
21868 Formulas like @cite{(a + b) + (c + d)} are rearranged to
21869 left-associative form, though this rarely matters since Calc's
21870 algebra commands are designed to hide the inner structure of
21871 sums and products as much as possible.  Sums and products in
21872 their proper associative form will be written without parentheses
21873 in the examples below.
21875 Sums and products are @emph{not} rearranged according to the
21876 commutative law (@cite{a + b} to @cite{b + a}) except in a few
21877 special cases described below.  Some algebra programs always
21878 rearrange terms into a canonical order, which enables them to
21879 see that @cite{a b + b a} can be simplified to @cite{2 a b}.
21880 Calc assumes you have put the terms into the order you want
21881 and generally leaves that order alone, with the consequence
21882 that formulas like the above will only be simplified if you
21883 explicitly give the @kbd{a s} command.  @xref{Algebraic
21884 Simplifications}.
21886 Differences @cite{a - b} are treated like sums @cite{a + (-b)}
21887 for purposes of simplification; one of the default simplifications
21888 is to rewrite @cite{a + (-b)} or @cite{(-b) + a}, where @cite{-b}
21889 represents a ``negative-looking'' term, into @cite{a - b} form.
21890 ``Negative-looking'' means negative numbers, negated formulas like
21891 @cite{-x}, and products or quotients in which either term is
21892 negative-looking.
21894 Other simplifications involving negation are @cite{-(-x)} to @cite{x};
21895 @cite{-(a b)} or @cite{-(a/b)} where either @cite{a} or @cite{b} is
21896 negative-looking, simplified by negating that term, or else where
21897 @cite{a} or @cite{b} is any number, by negating that number;
21898 @cite{-(a + b)} to @cite{-a - b}, and @cite{-(b - a)} to @cite{a - b}.
21899 (This, and rewriting @cite{(-b) + a} to @cite{a - b}, are the only
21900 cases where the order of terms in a sum is changed by the default
21901 simplifications.)
21903 The distributive law is used to simplify sums in some cases:
21904 @cite{a x + b x} to @cite{(a + b) x}, where @cite{a} represents
21905 a number or an implicit 1 or @i{-1} (as in @cite{x} or @cite{-x})
21906 and similarly for @cite{b}.  Use the @kbd{a c}, @w{@kbd{a f}}, or
21907 @kbd{j M} commands to merge sums with non-numeric coefficients
21908 using the distributive law.
21910 The distributive law is only used for sums of two terms, or
21911 for adjacent terms in a larger sum.  Thus @cite{a + b + b + c}
21912 is simplified to @cite{a + 2 b + c}, but @cite{a + b + c + b}
21913 is not simplified.  The reason is that comparing all terms of a
21914 sum with one another would require time proportional to the
21915 square of the number of terms; Calc relegates potentially slow
21916 operations like this to commands that have to be invoked
21917 explicitly, like @kbd{a s}.
21919 Finally, @cite{a + 0} and @cite{0 + a} are simplified to @cite{a}.
21920 A consequence of the above rules is that @cite{0 - a} is simplified
21921 to @cite{-a}.
21923 @tex
21924 \bigskip
21925 @end tex
21927 The products @cite{1 a} and @cite{a 1} are simplified to @cite{a};
21928 @cite{(-1) a} and @cite{a (-1)} are simplified to @cite{-a};
21929 @cite{0 a} and @cite{a 0} are simplified to @cite{0}, except that
21930 in matrix mode where @cite{a} is not provably scalar the result
21931 is the generic zero matrix @samp{idn(0)}, and that if @cite{a} is
21932 infinite the result is @samp{nan}.
21934 Also, @cite{(-a) b} and @cite{a (-b)} are simplified to @cite{-(a b)},
21935 where this occurs for negated formulas but not for regular negative
21936 numbers.
21938 Products are commuted only to move numbers to the front:
21939 @cite{a b 2} is commuted to @cite{2 a b}.
21941 The product @cite{a (b + c)} is distributed over the sum only if
21942 @cite{a} and at least one of @cite{b} and @cite{c} are numbers:
21943 @cite{2 (x + 3)} goes to @cite{2 x + 6}.  The formula
21944 @cite{(-a) (b - c)}, where @cite{-a} is a negative number, is
21945 rewritten to @cite{a (c - b)}.
21947 The distributive law of products and powers is used for adjacent
21948 terms of the product: @cite{x^a x^b} goes to @c{$x^{a+b}$}
21949 @cite{x^(a+b)}
21950 where @cite{a} is a number, or an implicit 1 (as in @cite{x}),
21951 or the implicit one-half of @cite{@t{sqrt}(x)}, and similarly for
21952 @cite{b}.  The result is written using @samp{sqrt} or @samp{1/sqrt}
21953 if the sum of the powers is @cite{1/2} or @cite{-1/2}, respectively.
21954 If the sum of the powers is zero, the product is simplified to
21955 @cite{1} or to @samp{idn(1)} if matrix mode is enabled.
21957 The product of a negative power times anything but another negative
21958 power is changed to use division:  @c{$x^{-2} y$}
21959 @cite{x^(-2) y} goes to @cite{y / x^2} unless matrix mode is
21960 in effect and neither @cite{x} nor @cite{y} are scalar (in which
21961 case it is considered unsafe to rearrange the order of the terms).
21963 Finally, @cite{a (b/c)} is rewritten to @cite{(a b)/c}, and also
21964 @cite{(a/b) c} is changed to @cite{(a c)/b} unless in matrix mode.
21966 @tex
21967 \bigskip
21968 @end tex
21970 Simplifications for quotients are analogous to those for products.
21971 The quotient @cite{0 / x} is simplified to @cite{0}, with the same
21972 exceptions that were noted for @cite{0 x}.  Likewise, @cite{x / 1}
21973 and @cite{x / (-1)} are simplified to @cite{x} and @cite{-x},
21974 respectively.
21976 The quotient @cite{x / 0} is left unsimplified or changed to an
21977 infinite quantity, as directed by the current infinite mode.
21978 @xref{Infinite Mode}.
21980 The expression @c{$a / b^{-c}$}
21981 @cite{a / b^(-c)} is changed to @cite{a b^c},
21982 where @cite{-c} is any negative-looking power.  Also, @cite{1 / b^c}
21983 is changed to @c{$b^{-c}$}
21984 @cite{b^(-c)} for any power @cite{c}.
21986 Also, @cite{(-a) / b} and @cite{a / (-b)} go to @cite{-(a/b)};
21987 @cite{(a/b) / c} goes to @cite{a / (b c)}; and @cite{a / (b/c)}
21988 goes to @cite{(a c) / b} unless matrix mode prevents this
21989 rearrangement.  Similarly, @cite{a / (b:c)} is simplified to
21990 @cite{(c:b) a} for any fraction @cite{b:c}.
21992 The distributive law is applied to @cite{(a + b) / c} only if
21993 @cite{c} and at least one of @cite{a} and @cite{b} are numbers.
21994 Quotients of powers and square roots are distributed just as
21995 described for multiplication.
21997 Quotients of products cancel only in the leading terms of the
21998 numerator and denominator.  In other words, @cite{a x b / a y b}
21999 is cancelled to @cite{x b / y b} but not to @cite{x / y}.  Once
22000 again this is because full cancellation can be slow; use @kbd{a s}
22001 to cancel all terms of the quotient.
22003 Quotients of negative-looking values are simplified according
22004 to @cite{(-a) / (-b)} to @cite{a / b}, @cite{(-a) / (b - c)}
22005 to @cite{a / (c - b)}, and @cite{(a - b) / (-c)} to @cite{(b - a) / c}.
22007 @tex
22008 \bigskip
22009 @end tex
22011 The formula @cite{x^0} is simplified to @cite{1}, or to @samp{idn(1)}
22012 in matrix mode.  The formula @cite{0^x} is simplified to @cite{0}
22013 unless @cite{x} is a negative number or complex number, in which
22014 case the result is an infinity or an unsimplified formula according
22015 to the current infinite mode.  Note that @cite{0^0} is an
22016 indeterminate form, as evidenced by the fact that the simplifications
22017 for @cite{x^0} and @cite{0^x} conflict when @cite{x=0}.
22019 Powers of products or quotients @cite{(a b)^c}, @cite{(a/b)^c}
22020 are distributed to @cite{a^c b^c}, @cite{a^c / b^c} only if @cite{c}
22021 is an integer, or if either @cite{a} or @cite{b} are nonnegative
22022 real numbers.  Powers of powers @cite{(a^b)^c} are simplified to
22023 @c{$a^{b c}$}
22024 @cite{a^(b c)} only when @cite{c} is an integer and @cite{b c} also
22025 evaluates to an integer.  Without these restrictions these simplifications
22026 would not be safe because of problems with principal values.
22027 (In other words, @c{$((-3)^{1/2})^2$}
22028 @cite{((-3)^1:2)^2} is safe to simplify, but
22029 @c{$((-3)^2)^{1/2}$}
22030 @cite{((-3)^2)^1:2} is not.)  @xref{Declarations}, for ways to inform
22031 Calc that your variables satisfy these requirements.
22033 As a special case of this rule, @cite{@t{sqrt}(x)^n} is simplified to
22034 @c{$x^{n/2}$}
22035 @cite{x^(n/2)} only for even integers @cite{n}.
22037 If @cite{a} is known to be real, @cite{b} is an even integer, and
22038 @cite{c} is a half- or quarter-integer, then @cite{(a^b)^c} is
22039 simplified to @c{$@t{abs}(a^{b c})$}
22040 @cite{@t{abs}(a^(b c))}.
22042 Also, @cite{(-a)^b} is simplified to @cite{a^b} if @cite{b} is an
22043 even integer, or to @cite{-(a^b)} if @cite{b} is an odd integer,
22044 for any negative-looking expression @cite{-a}.
22046 Square roots @cite{@t{sqrt}(x)} generally act like one-half powers
22047 @c{$x^{1:2}$}
22048 @cite{x^1:2} for the purposes of the above-listed simplifications.
22050 Also, note that @c{$1 / x^{1:2}$}
22051 @cite{1 / x^1:2} is changed to @c{$x^{-1:2}$}
22052 @cite{x^(-1:2)},
22053 but @cite{1 / @t{sqrt}(x)} is left alone.
22055 @tex
22056 \bigskip
22057 @end tex
22059 Generic identity matrices (@pxref{Matrix Mode}) are simplified by the
22060 following rules:  @cite{@t{idn}(a) + b} to @cite{a + b} if @cite{b}
22061 is provably scalar, or expanded out if @cite{b} is a matrix;
22062 @cite{@t{idn}(a) + @t{idn}(b)} to @cite{@t{idn}(a + b)};
22063 @cite{-@t{idn}(a)} to @cite{@t{idn}(-a)}; @cite{a @t{idn}(b)} to
22064 @cite{@t{idn}(a b)} if @cite{a} is provably scalar, or to @cite{a b}
22065 if @cite{a} is provably non-scalar; @cite{@t{idn}(a) @t{idn}(b)}
22066 to @cite{@t{idn}(a b)}; analogous simplifications for quotients
22067 involving @code{idn}; and @cite{@t{idn}(a)^n} to @cite{@t{idn}(a^n)}
22068 where @cite{n} is an integer.
22070 @tex
22071 \bigskip
22072 @end tex
22074 The @code{floor} function and other integer truncation functions
22075 vanish if the argument is provably integer-valued, so that
22076 @cite{@t{floor}(@t{round}(x))} simplifies to @cite{@t{round}(x)}.
22077 Also, combinations of @code{float}, @code{floor} and its friends,
22078 and @code{ffloor} and its friends, are simplified in appropriate
22079 ways.  @xref{Integer Truncation}.
22081 The expression @cite{@t{abs}(-x)} changes to @cite{@t{abs}(x)}.
22082 The expression @cite{@t{abs}(@t{abs}(x))} changes to @cite{@t{abs}(x)};
22083 in fact, @cite{@t{abs}(x)} changes to @cite{x} or @cite{-x} if @cite{x}
22084 is provably nonnegative or nonpositive (@pxref{Declarations}).
22086 While most functions do not recognize the variable @code{i} as an
22087 imaginary number, the @code{arg} function does handle the two cases
22088 @cite{@t{arg}(@t{i})} and @cite{@t{arg}(-@t{i})} just for convenience.
22090 The expression @cite{@t{conj}(@t{conj}(x))} simplifies to @cite{x}.
22091 Various other expressions involving @code{conj}, @code{re}, and
22092 @code{im} are simplified, especially if some of the arguments are
22093 provably real or involve the constant @code{i}.  For example,
22094 @cite{@t{conj}(a + b i)} is changed to @cite{@t{conj}(a) - @t{conj}(b) i},
22095 or to @cite{a - b i} if @cite{a} and @cite{b} are known to be real.
22097 Functions like @code{sin} and @code{arctan} generally don't have
22098 any default simplifications beyond simply evaluating the functions
22099 for suitable numeric arguments and infinity.  The @kbd{a s} command
22100 described in the next section does provide some simplifications for
22101 these functions, though.
22103 One important simplification that does occur is that @cite{@t{ln}(@t{e})}
22104 is simplified to 1, and @cite{@t{ln}(@t{e}^x)} is simplified to @cite{x}
22105 for any @cite{x}.  This occurs even if you have stored a different
22106 value in the Calc variable @samp{e}; but this would be a bad idea
22107 in any case if you were also using natural logarithms!
22109 Among the logical functions, @t{!}@i{(a} @t{<=} @i{b)} changes to
22110 @cite{a > b} and so on.  Equations and inequalities where both sides
22111 are either negative-looking or zero are simplified by negating both sides
22112 and reversing the inequality.  While it might seem reasonable to simplify
22113 @cite{!!x} to @cite{x}, this would not be valid in general because
22114 @cite{!!2} is 1, not 2.
22116 Most other Calc functions have few if any default simplifications
22117 defined, aside of course from evaluation when the arguments are
22118 suitable numbers.
22120 @node Algebraic Simplifications, Unsafe Simplifications, Default Simplifications, Simplifying Formulas
22121 @subsection Algebraic Simplifications
22123 @noindent
22124 @cindex Algebraic simplifications
22125 The @kbd{a s} command makes simplifications that may be too slow to
22126 do all the time, or that may not be desirable all of the time.
22127 If you find these simplifications are worthwhile, you can type
22128 @kbd{m A} to have Calc apply them automatically.
22130 This section describes all simplifications that are performed by
22131 the @kbd{a s} command.  Note that these occur in addition to the
22132 default simplifications; even if the default simplifications have
22133 been turned off by an @kbd{m O} command, @kbd{a s} will turn them
22134 back on temporarily while it simplifies the formula.
22136 There is a variable, @code{AlgSimpRules}, in which you can put rewrites
22137 to be applied by @kbd{a s}.  Its use is analogous to @code{EvalRules},
22138 but without the special restrictions.  Basically, the simplifier does
22139 @samp{@w{a r} AlgSimpRules} with an infinite repeat count on the whole
22140 expression being simplified, then it traverses the expression applying
22141 the built-in rules described below.  If the result is different from
22142 the original expression, the process repeats with the default
22143 simplifications (including @code{EvalRules}), then @code{AlgSimpRules},
22144 then the built-in simplifications, and so on.
22146 @tex
22147 \bigskip
22148 @end tex
22150 Sums are simplified in two ways.  Constant terms are commuted to the
22151 end of the sum, so that @cite{a + 2 + b} changes to @cite{a + b + 2}.
22152 The only exception is that a constant will not be commuted away
22153 from the first position of a difference, i.e., @cite{2 - x} is not
22154 commuted to @cite{-x + 2}.
22156 Also, terms of sums are combined by the distributive law, as in
22157 @cite{x + y + 2 x} to @cite{y + 3 x}.  This always occurs for
22158 adjacent terms, but @kbd{a s} compares all pairs of terms including
22159 non-adjacent ones.
22161 @tex
22162 \bigskip
22163 @end tex
22165 Products are sorted into a canonical order using the commutative
22166 law.  For example, @cite{b c a} is commuted to @cite{a b c}.
22167 This allows easier comparison of products; for example, the default
22168 simplifications will not change @cite{x y + y x} to @cite{2 x y},
22169 but @kbd{a s} will; it first rewrites the sum to @cite{x y + x y},
22170 and then the default simplifications are able to recognize a sum
22171 of identical terms.
22173 The canonical ordering used to sort terms of products has the
22174 property that real-valued numbers, interval forms and infinities
22175 come first, and are sorted into increasing order.  The @kbd{V S}
22176 command uses the same ordering when sorting a vector.
22178 Sorting of terms of products is inhibited when matrix mode is
22179 turned on; in this case, Calc will never exchange the order of
22180 two terms unless it knows at least one of the terms is a scalar.
22182 Products of powers are distributed by comparing all pairs of
22183 terms, using the same method that the default simplifications
22184 use for adjacent terms of products.
22186 Even though sums are not sorted, the commutative law is still
22187 taken into account when terms of a product are being compared.
22188 Thus @cite{(x + y) (y + x)} will be simplified to @cite{(x + y)^2}.
22189 A subtle point is that @cite{(x - y) (y - x)} will @emph{not}
22190 be simplified to @cite{-(x - y)^2}; Calc does not notice that
22191 one term can be written as a constant times the other, even if
22192 that constant is @i{-1}.
22194 A fraction times any expression, @cite{(a:b) x}, is changed to
22195 a quotient involving integers:  @cite{a x / b}.  This is not
22196 done for floating-point numbers like @cite{0.5}, however.  This
22197 is one reason why you may find it convenient to turn Fraction mode
22198 on while doing algebra; @pxref{Fraction Mode}.
22200 @tex
22201 \bigskip
22202 @end tex
22204 Quotients are simplified by comparing all terms in the numerator
22205 with all terms in the denominator for possible cancellation using
22206 the distributive law.  For example, @cite{a x^2 b / c x^3 d} will
22207 cancel @cite{x^2} from both sides to get @cite{a b / c x d}.
22208 (The terms in the denominator will then be rearranged to @cite{c d x}
22209 as described above.)  If there is any common integer or fractional
22210 factor in the numerator and denominator, it is cancelled out;
22211 for example, @cite{(4 x + 6) / 8 x} simplifies to @cite{(2 x + 3) / 4 x}.
22213 Non-constant common factors are not found even by @kbd{a s}.  To
22214 cancel the factor @cite{a} in @cite{(a x + a) / a^2} you could first
22215 use @kbd{j M} on the product @cite{a x} to Merge the numerator to
22216 @cite{a (1+x)}, which can then be simplified successfully.
22218 @tex
22219 \bigskip
22220 @end tex
22222 Integer powers of the variable @code{i} are simplified according
22223 to the identity @cite{i^2 = -1}.  If you store a new value other
22224 than the complex number @cite{(0,1)} in @code{i}, this simplification
22225 will no longer occur.  This is done by @kbd{a s} instead of by default
22226 in case someone (unwisely) uses the name @code{i} for a variable
22227 unrelated to complex numbers; it would be unfortunate if Calc
22228 quietly and automatically changed this formula for reasons the
22229 user might not have been thinking of.
22231 Square roots of integer or rational arguments are simplified in
22232 several ways.  (Note that these will be left unevaluated only in
22233 Symbolic mode.)  First, square integer or rational factors are
22234 pulled out so that @cite{@t{sqrt}(8)} is rewritten as
22235 @c{$2\,\t{sqrt}(2)$}
22236 @cite{2 sqrt(2)}.  Conceptually speaking this implies factoring
22237 the argument into primes and moving pairs of primes out of the
22238 square root, but for reasons of efficiency Calc only looks for
22239 primes up to 29.
22241 Square roots in the denominator of a quotient are moved to the
22242 numerator:  @cite{1 / @t{sqrt}(3)} changes to @cite{@t{sqrt}(3) / 3}.
22243 The same effect occurs for the square root of a fraction:
22244 @cite{@t{sqrt}(2:3)} changes to @cite{@t{sqrt}(6) / 3}.
22246 @tex
22247 \bigskip
22248 @end tex
22250 The @code{%} (modulo) operator is simplified in several ways
22251 when the modulus @cite{M} is a positive real number.  First, if
22252 the argument is of the form @cite{x + n} for some real number
22253 @cite{n}, then @cite{n} is itself reduced modulo @cite{M}.  For
22254 example, @samp{(x - 23) % 10} is simplified to @samp{(x + 7) % 10}.
22256 If the argument is multiplied by a constant, and this constant
22257 has a common integer divisor with the modulus, then this factor is
22258 cancelled out.  For example, @samp{12 x % 15} is changed to
22259 @samp{3 (4 x % 5)} by factoring out 3.  Also, @samp{(12 x + 1) % 15}
22260 is changed to @samp{3 ((4 x + 1:3) % 5)}.  While these forms may
22261 not seem ``simpler,'' they allow Calc to discover useful information
22262 about modulo forms in the presence of declarations.
22264 If the modulus is 1, then Calc can use @code{int} declarations to
22265 evaluate the expression.  For example, the idiom @samp{x % 2} is
22266 often used to check whether a number is odd or even.  As described
22267 above, @w{@samp{2 n % 2}} and @samp{(2 n + 1) % 2} are simplified to
22268 @samp{2 (n % 1)} and @samp{2 ((n + 1:2) % 1)}, respectively; Calc
22269 can simplify these to 0 and 1 (respectively) if @code{n} has been
22270 declared to be an integer.
22272 @tex
22273 \bigskip
22274 @end tex
22276 Trigonometric functions are simplified in several ways.  First,
22277 @cite{@t{sin}(@t{arcsin}(x))} is simplified to @cite{x}, and
22278 similarly for @code{cos} and @code{tan}.  If the argument to
22279 @code{sin} is negative-looking, it is simplified to @cite{-@t{sin}(x)},
22280 and similarly for @code{cos} and @code{tan}.  Finally, certain
22281 special values of the argument are recognized;
22282 @pxref{Trigonometric and Hyperbolic Functions}.
22284 Trigonometric functions of inverses of different trigonometric
22285 functions can also be simplified, as in @cite{@t{sin}(@t{arccos}(x))}
22286 to @cite{@t{sqrt}(1 - x^2)}.
22288 Hyperbolic functions of their inverses and of negative-looking
22289 arguments are also handled, as are exponentials of inverse
22290 hyperbolic functions.
22292 No simplifications for inverse trigonometric and hyperbolic
22293 functions are known, except for negative arguments of @code{arcsin},
22294 @code{arctan}, @code{arcsinh}, and @code{arctanh}.  Note that
22295 @cite{@t{arcsin}(@t{sin}(x))} can @emph{not} safely change to
22296 @cite{x}, since this only correct within an integer multiple
22297 of @c{$2 \pi$}
22298 @cite{2 pi} radians or 360 degrees.  However,
22299 @cite{@t{arcsinh}(@t{sinh}(x))} is simplified to @cite{x} if
22300 @cite{x} is known to be real.
22302 Several simplifications that apply to logarithms and exponentials
22303 are that @cite{@t{exp}(@t{ln}(x))}, @c{$@t{e}^{\ln(x)}$}
22304 @cite{e^@t{ln}(x)}, and
22305 @c{$10^{{\rm log10}(x)}$}
22306 @cite{10^@t{log10}(x)} all reduce to @cite{x}.
22307 Also, @cite{@t{ln}(@t{exp}(x))}, etc., can reduce to @cite{x} if
22308 @cite{x} is provably real.  The form @cite{@t{exp}(x)^y} is simplified
22309 to @cite{@t{exp}(x y)}.  If @cite{x} is a suitable multiple of @c{$\pi i$}
22310 @cite{pi i}
22311 (as described above for the trigonometric functions), then @cite{@t{exp}(x)}
22312 or @cite{e^x} will be expanded.  Finally, @cite{@t{ln}(x)} is simplified
22313 to a form involving @code{pi} and @code{i} where @cite{x} is provably
22314 negative, positive imaginary, or negative imaginary.
22316 The error functions @code{erf} and @code{erfc} are simplified when
22317 their arguments are negative-looking or are calls to the @code{conj}
22318 function.
22320 @tex
22321 \bigskip
22322 @end tex
22324 Equations and inequalities are simplified by cancelling factors
22325 of products, quotients, or sums on both sides.  Inequalities
22326 change sign if a negative multiplicative factor is cancelled.
22327 Non-constant multiplicative factors as in @cite{a b = a c} are
22328 cancelled from equations only if they are provably nonzero (generally
22329 because they were declared so; @pxref{Declarations}).  Factors
22330 are cancelled from inequalities only if they are nonzero and their
22331 sign is known.
22333 Simplification also replaces an equation or inequality with
22334 1 or 0 (``true'' or ``false'') if it can through the use of
22335 declarations.  If @cite{x} is declared to be an integer greater
22336 than 5, then @cite{x < 3}, @cite{x = 3}, and @cite{x = 7.5} are
22337 all simplified to 0, but @cite{x > 3} is simplified to 1.
22338 By a similar analysis, @cite{abs(x) >= 0} is simplified to 1,
22339 as is @cite{x^2 >= 0} if @cite{x} is known to be real.
22341 @node Unsafe Simplifications, Simplification of Units, Algebraic Simplifications, Simplifying Formulas
22342 @subsection ``Unsafe'' Simplifications
22344 @noindent
22345 @cindex Unsafe simplifications
22346 @cindex Extended simplification
22347 @kindex a e
22348 @pindex calc-simplify-extended
22349 @c @mindex esimpl@idots
22350 @tindex esimplify
22351 The @kbd{a e} (@code{calc-simplify-extended}) [@code{esimplify}] command
22352 is like @kbd{a s}
22353 except that it applies some additional simplifications which are not
22354 ``safe'' in all cases.  Use this only if you know the values in your
22355 formula lie in the restricted ranges for which these simplifications
22356 are valid.  The symbolic integrator uses @kbd{a e};
22357 one effect of this is that the integrator's results must be used with
22358 caution.  Where an integral table will often attach conditions like
22359 ``for positive @cite{a} only,'' Calc (like most other symbolic
22360 integration programs) will simply produce an unqualified result.@refill
22362 Because @kbd{a e}'s simplifications are unsafe, it is sometimes better
22363 to type @kbd{C-u -3 a v}, which does extended simplification only
22364 on the top level of the formula without affecting the sub-formulas.
22365 In fact, @kbd{C-u -3 j v} allows you to target extended simplification
22366 to any specific part of a formula.
22368 The variable @code{ExtSimpRules} contains rewrites to be applied by
22369 the @kbd{a e} command.  These are applied in addition to
22370 @code{EvalRules} and @code{AlgSimpRules}.  (The @kbd{a r AlgSimpRules}
22371 step described above is simply followed by an @kbd{a r ExtSimpRules} step.)
22373 Following is a complete list of ``unsafe'' simplifications performed
22374 by @kbd{a e}.
22376 @tex
22377 \bigskip
22378 @end tex
22380 Inverse trigonometric or hyperbolic functions, called with their
22381 corresponding non-inverse functions as arguments, are simplified
22382 by @kbd{a e}.  For example, @cite{@t{arcsin}(@t{sin}(x))} changes
22383 to @cite{x}.  Also, @cite{@t{arcsin}(@t{cos}(x))} and
22384 @cite{@t{arccos}(@t{sin}(x))} both change to @cite{@t{pi}/2 - x}.
22385 These simplifications are unsafe because they are valid only for
22386 values of @cite{x} in a certain range; outside that range, values
22387 are folded down to the 360-degree range that the inverse trigonometric
22388 functions always produce.
22390 Powers of powers @cite{(x^a)^b} are simplified to @c{$x^{a b}$}
22391 @cite{x^(a b)}
22392 for all @cite{a} and @cite{b}.  These results will be valid only
22393 in a restricted range of @cite{x}; for example, in @c{$(x^2)^{1:2}$}
22394 @cite{(x^2)^1:2}
22395 the powers cancel to get @cite{x}, which is valid for positive values
22396 of @cite{x} but not for negative or complex values.
22398 Similarly, @cite{@t{sqrt}(x^a)} and @cite{@t{sqrt}(x)^a} are both
22399 simplified (possibly unsafely) to @c{$x^{a/2}$}
22400 @cite{x^(a/2)}.
22402 Forms like @cite{@t{sqrt}(1 - @t{sin}(x)^2)} are simplified to, e.g.,
22403 @cite{@t{cos}(x)}.  Calc has identities of this sort for @code{sin},
22404 @code{cos}, @code{tan}, @code{sinh}, and @code{cosh}.
22406 Arguments of square roots are partially factored to look for
22407 squared terms that can be extracted.  For example,
22408 @cite{@t{sqrt}(a^2 b^3 + a^3 b^2)} simplifies to @cite{a b @t{sqrt}(a+b)}.
22410 The simplifications of @cite{@t{ln}(@t{exp}(x))}, @cite{@t{ln}(@t{e}^x)},
22411 and @cite{@t{log10}(10^x)} to @cite{x} are also unsafe because
22412 of problems with principal values (although these simplifications
22413 are safe if @cite{x} is known to be real).
22415 Common factors are cancelled from products on both sides of an
22416 equation, even if those factors may be zero:  @cite{a x / b x}
22417 to @cite{a / b}.  Such factors are never cancelled from
22418 inequalities:  Even @kbd{a e} is not bold enough to reduce
22419 @cite{a x < b x} to @cite{a < b} (or @cite{a > b}, depending
22420 on whether you believe @cite{x} is positive or negative).
22421 The @kbd{a M /} command can be used to divide a factor out of
22422 both sides of an inequality.
22424 @node Simplification of Units, , Unsafe Simplifications, Simplifying Formulas
22425 @subsection Simplification of Units
22427 @noindent
22428 The simplifications described in this section are applied by the
22429 @kbd{u s} (@code{calc-simplify-units}) command.  These are in addition
22430 to the regular @kbd{a s} (but not @kbd{a e}) simplifications described
22431 earlier.  @xref{Basic Operations on Units}.
22433 The variable @code{UnitSimpRules} contains rewrites to be applied by
22434 the @kbd{u s} command.  These are applied in addition to @code{EvalRules}
22435 and @code{AlgSimpRules}.
22437 Scalar mode is automatically put into effect when simplifying units.
22438 @xref{Matrix Mode}.
22440 Sums @cite{a + b} involving units are simplified by extracting the
22441 units of @cite{a} as if by the @kbd{u x} command (call the result
22442 @cite{u_a}), then simplifying the expression @cite{b / u_a}
22443 using @kbd{u b} and @kbd{u s}.  If the result has units then the sum
22444 is inconsistent and is left alone.  Otherwise, it is rewritten
22445 in terms of the units @cite{u_a}.
22447 If units auto-ranging mode is enabled, products or quotients in
22448 which the first argument is a number which is out of range for the
22449 leading unit are modified accordingly.
22451 When cancelling and combining units in products and quotients,
22452 Calc accounts for unit names that differ only in the prefix letter.
22453 For example, @samp{2 km m} is simplified to @samp{2000 m^2}.
22454 However, compatible but different units like @code{ft} and @code{in}
22455 are not combined in this way.
22457 Quotients @cite{a / b} are simplified in three additional ways.  First,
22458 if @cite{b} is a number or a product beginning with a number, Calc
22459 computes the reciprocal of this number and moves it to the numerator.
22461 Second, for each pair of unit names from the numerator and denominator
22462 of a quotient, if the units are compatible (e.g., they are both
22463 units of area) then they are replaced by the ratio between those
22464 units.  For example, in @samp{3 s in N / kg cm} the units
22465 @samp{in / cm} will be replaced by @cite{2.54}.
22467 Third, if the units in the quotient exactly cancel out, so that
22468 a @kbd{u b} command on the quotient would produce a dimensionless
22469 number for an answer, then the quotient simplifies to that number.
22471 For powers and square roots, the ``unsafe'' simplifications
22472 @cite{(a b)^c} to @cite{a^c b^c}, @cite{(a/b)^c} to @cite{a^c / b^c},
22473 and @cite{(a^b)^c} to @c{$a^{b c}$}
22474 @cite{a^(b c)} are done if the powers are
22475 real numbers.  (These are safe in the context of units because
22476 all numbers involved can reasonably be assumed to be real.)
22478 Also, if a unit name is raised to a fractional power, and the
22479 base units in that unit name all occur to powers which are a
22480 multiple of the denominator of the power, then the unit name
22481 is expanded out into its base units, which can then be simplified
22482 according to the previous paragraph.  For example, @samp{acre^1.5}
22483 is simplified by noting that @cite{1.5 = 3:2}, that @samp{acre}
22484 is defined in terms of @samp{m^2}, and that the 2 in the power of
22485 @code{m} is a multiple of 2 in @cite{3:2}.  Thus, @code{acre^1.5} is
22486 replaced by approximately @c{$(4046 m^2)^{1.5}$}
22487 @cite{(4046 m^2)^1.5}, which is then
22488 changed to @c{$4046^{1.5} \, (m^2)^{1.5}$}
22489 @cite{4046^1.5 (m^2)^1.5}, then to @cite{257440 m^3}.
22491 The functions @code{float}, @code{frac}, @code{clean}, @code{abs},
22492 as well as @code{floor} and the other integer truncation functions,
22493 applied to unit names or products or quotients involving units, are
22494 simplified.  For example, @samp{round(1.6 in)} is changed to
22495 @samp{round(1.6) round(in)}; the lefthand term evaluates to 2,
22496 and the righthand term simplifies to @code{in}.
22498 The functions @code{sin}, @code{cos}, and @code{tan} with arguments
22499 that have angular units like @code{rad} or @code{arcmin} are
22500 simplified by converting to base units (radians), then evaluating
22501 with the angular mode temporarily set to radians.
22503 @node Polynomials, Calculus, Simplifying Formulas, Algebra
22504 @section Polynomials
22506 A @dfn{polynomial} is a sum of terms which are coefficients times
22507 various powers of a ``base'' variable.  For example, @cite{2 x^2 + 3 x - 4}
22508 is a polynomial in @cite{x}.  Some formulas can be considered
22509 polynomials in several different variables:  @cite{1 + 2 x + 3 y + 4 x y^2}
22510 is a polynomial in both @cite{x} and @cite{y}.  Polynomial coefficients
22511 are often numbers, but they may in general be any formulas not
22512 involving the base variable.
22514 @kindex a f
22515 @pindex calc-factor
22516 @tindex factor
22517 The @kbd{a f} (@code{calc-factor}) [@code{factor}] command factors a
22518 polynomial into a product of terms.  For example, the polynomial
22519 @cite{x^3 + 2 x^2 + x} is factored into @samp{x*(x+1)^2}.  As another
22520 example, @cite{a c + b d + b c + a d} is factored into the product
22521 @cite{(a + b) (c + d)}.
22523 Calc currently has three algorithms for factoring.  Formulas which are
22524 linear in several variables, such as the second example above, are
22525 merged according to the distributive law.  Formulas which are
22526 polynomials in a single variable, with constant integer or fractional
22527 coefficients, are factored into irreducible linear and/or quadratic
22528 terms.  The first example above factors into three linear terms
22529 (@cite{x}, @cite{x+1}, and @cite{x+1} again).  Finally, formulas
22530 which do not fit the above criteria are handled by the algebraic
22531 rewrite mechanism.
22533 Calc's polynomial factorization algorithm works by using the general
22534 root-finding command (@w{@kbd{a P}}) to solve for the roots of the
22535 polynomial.  It then looks for roots which are rational numbers
22536 or complex-conjugate pairs, and converts these into linear and
22537 quadratic terms, respectively.  Because it uses floating-point
22538 arithmetic, it may be unable to find terms that involve large
22539 integers (whose number of digits approaches the current precision).
22540 Also, irreducible factors of degree higher than quadratic are not
22541 found, and polynomials in more than one variable are not treated.
22542 (A more robust factorization algorithm may be included in a future
22543 version of Calc.)
22545 @vindex FactorRules
22546 @c @starindex
22547 @tindex thecoefs
22548 @c @starindex
22549 @c @mindex @idots
22550 @tindex thefactors
22551 The rewrite-based factorization method uses rules stored in the variable
22552 @code{FactorRules}.  @xref{Rewrite Rules}, for a discussion of the
22553 operation of rewrite rules.  The default @code{FactorRules} are able
22554 to factor quadratic forms symbolically into two linear terms,
22555 @cite{(a x + b) (c x + d)}.  You can edit these rules to include other
22556 cases if you wish.  To use the rules, Calc builds the formula
22557 @samp{thecoefs(x, [a, b, c, ...])} where @code{x} is the polynomial
22558 base variable and @code{a}, @code{b}, etc., are polynomial coefficients
22559 (which may be numbers or formulas).  The constant term is written first,
22560 i.e., in the @code{a} position.  When the rules complete, they should have
22561 changed the formula into the form @samp{thefactors(x, [f1, f2, f3, ...])}
22562 where each @code{fi} should be a factored term, e.g., @samp{x - ai}.
22563 Calc then multiplies these terms together to get the complete
22564 factored form of the polynomial.  If the rules do not change the
22565 @code{thecoefs} call to a @code{thefactors} call, @kbd{a f} leaves the
22566 polynomial alone on the assumption that it is unfactorable.  (Note that
22567 the function names @code{thecoefs} and @code{thefactors} are used only
22568 as placeholders; there are no actual Calc functions by those names.)
22570 @kindex H a f
22571 @tindex factors
22572 The @kbd{H a f} [@code{factors}] command also factors a polynomial,
22573 but it returns a list of factors instead of an expression which is the
22574 product of the factors.  Each factor is represented by a sub-vector
22575 of the factor, and the power with which it appears.  For example,
22576 @cite{x^5 + x^4 - 33 x^3 + 63 x^2} factors to @cite{(x + 7) x^2 (x - 3)^2}
22577 in @kbd{a f}, or to @cite{[ [x, 2], [x+7, 1], [x-3, 2] ]} in @kbd{H a f}.
22578 If there is an overall numeric factor, it always comes first in the list.
22579 The functions @code{factor} and @code{factors} allow a second argument
22580 when written in algebraic form; @samp{factor(x,v)} factors @cite{x} with
22581 respect to the specific variable @cite{v}.  The default is to factor with
22582 respect to all the variables that appear in @cite{x}.
22584 @kindex a c
22585 @pindex calc-collect
22586 @tindex collect
22587 The @kbd{a c} (@code{calc-collect}) [@code{collect}] command rearranges a
22588 formula as a
22589 polynomial in a given variable, ordered in decreasing powers of that
22590 variable.  For example, given @cite{1 + 2 x + 3 y + 4 x y^2} on
22591 the stack, @kbd{a c x} would produce @cite{(2 + 4 y^2) x + (1 + 3 y)},
22592 and @kbd{a c y} would produce @cite{(4 x) y^2 + 3 y + (1 + 2 x)}.
22593 The polynomial will be expanded out using the distributive law as
22594 necessary:  Collecting @cite{x} in @cite{(x - 1)^3} produces
22595 @cite{x^3 - 3 x^2 + 3 x - 1}.  Terms not involving @cite{x} will
22596 not be expanded.
22598 The ``variable'' you specify at the prompt can actually be any
22599 expression: @kbd{a c ln(x+1)} will collect together all terms multiplied
22600 by @samp{ln(x+1)} or integer powers thereof.  If @samp{x} also appears
22601 in the formula in a context other than @samp{ln(x+1)}, @kbd{a c} will
22602 treat those occurrences as unrelated to @samp{ln(x+1)}, i.e., as constants.
22604 @kindex a x
22605 @pindex calc-expand
22606 @tindex expand
22607 The @kbd{a x} (@code{calc-expand}) [@code{expand}] command expands an
22608 expression by applying the distributive law everywhere.  It applies to
22609 products, quotients, and powers involving sums.  By default, it fully
22610 distributes all parts of the expression.  With a numeric prefix argument,
22611 the distributive law is applied only the specified number of times, then
22612 the partially expanded expression is left on the stack.
22614 The @kbd{a x} and @kbd{j D} commands are somewhat redundant.  Use
22615 @kbd{a x} if you want to expand all products of sums in your formula.
22616 Use @kbd{j D} if you want to expand a particular specified term of
22617 the formula.  There is an exactly analogous correspondence between
22618 @kbd{a f} and @kbd{j M}.  (The @kbd{j D} and @kbd{j M} commands
22619 also know many other kinds of expansions, such as
22620 @samp{exp(a + b) = exp(a) exp(b)}, which @kbd{a x} and @kbd{a f}
22621 do not do.)
22623 Calc's automatic simplifications will sometimes reverse a partial
22624 expansion.  For example, the first step in expanding @cite{(x+1)^3} is
22625 to write @cite{(x+1) (x+1)^2}.  If @kbd{a x} stops there and tries
22626 to put this formula onto the stack, though, Calc will automatically
22627 simplify it back to @cite{(x+1)^3} form.  The solution is to turn
22628 simplification off first (@pxref{Simplification Modes}), or to run
22629 @kbd{a x} without a numeric prefix argument so that it expands all
22630 the way in one step.
22632 @kindex a a
22633 @pindex calc-apart
22634 @tindex apart
22635 The @kbd{a a} (@code{calc-apart}) [@code{apart}] command expands a
22636 rational function by partial fractions.  A rational function is the
22637 quotient of two polynomials; @code{apart} pulls this apart into a
22638 sum of rational functions with simple denominators.  In algebraic
22639 notation, the @code{apart} function allows a second argument that
22640 specifies which variable to use as the ``base''; by default, Calc
22641 chooses the base variable automatically.
22643 @kindex a n
22644 @pindex calc-normalize-rat
22645 @tindex nrat
22646 The @kbd{a n} (@code{calc-normalize-rat}) [@code{nrat}] command
22647 attempts to arrange a formula into a quotient of two polynomials.
22648 For example, given @cite{1 + (a + b/c) / d}, the result would be
22649 @cite{(b + a c + c d) / c d}.  The quotient is reduced, so that
22650 @kbd{a n} will simplify @cite{(x^2 + 2x + 1) / (x^2 - 1)} by dividing
22651 out the common factor @cite{x + 1}, yielding @cite{(x + 1) / (x - 1)}.
22653 @kindex a \
22654 @pindex calc-poly-div
22655 @tindex pdiv
22656 The @kbd{a \} (@code{calc-poly-div}) [@code{pdiv}] command divides
22657 two polynomials @cite{u} and @cite{v}, yielding a new polynomial
22658 @cite{q}.  If several variables occur in the inputs, the inputs are
22659 considered multivariate polynomials.  (Calc divides by the variable
22660 with the largest power in @cite{u} first, or, in the case of equal
22661 powers, chooses the variables in alphabetical order.)  For example,
22662 dividing @cite{x^2 + 3 x + 2} by @cite{x + 2} yields @cite{x + 1}.
22663 The remainder from the division, if any, is reported at the bottom
22664 of the screen and is also placed in the Trail along with the quotient.
22666 Using @code{pdiv} in algebraic notation, you can specify the particular
22667 variable to be used as the base:  `@t{pdiv(}@i{a}@t{,}@i{b}@t{,}@i{x}@t{)}'.
22668 If @code{pdiv} is given only two arguments (as is always the case with
22669 the @kbd{a \} command), then it does a multivariate division as outlined
22670 above.
22672 @kindex a %
22673 @pindex calc-poly-rem
22674 @tindex prem
22675 The @kbd{a %} (@code{calc-poly-rem}) [@code{prem}] command divides
22676 two polynomials and keeps the remainder @cite{r}.  The quotient
22677 @cite{q} is discarded.  For any formulas @cite{a} and @cite{b}, the
22678 results of @kbd{a \} and @kbd{a %} satisfy @cite{a = q b + r}.
22679 (This is analogous to plain @kbd{\} and @kbd{%}, which compute the
22680 integer quotient and remainder from dividing two numbers.)
22682 @kindex a /
22683 @kindex H a /
22684 @pindex calc-poly-div-rem
22685 @tindex pdivrem
22686 @tindex pdivide
22687 The @kbd{a /} (@code{calc-poly-div-rem}) [@code{pdivrem}] command
22688 divides two polynomials and reports both the quotient and the
22689 remainder as a vector @cite{[q, r]}.  The @kbd{H a /} [@code{pdivide}]
22690 command divides two polynomials and constructs the formula
22691 @cite{q + r/b} on the stack.  (Naturally if the remainder is zero,
22692 this will immediately simplify to @cite{q}.)
22694 @kindex a g
22695 @pindex calc-poly-gcd
22696 @tindex pgcd
22697 The @kbd{a g} (@code{calc-poly-gcd}) [@code{pgcd}] command computes
22698 the greatest common divisor of two polynomials.  (The GCD actually
22699 is unique only to within a constant multiplier; Calc attempts to
22700 choose a GCD which will be unsurprising.)  For example, the @kbd{a n}
22701 command uses @kbd{a g} to take the GCD of the numerator and denominator
22702 of a quotient, then divides each by the result using @kbd{a \}.  (The
22703 definition of GCD ensures that this division can take place without
22704 leaving a remainder.)
22706 While the polynomials used in operations like @kbd{a /} and @kbd{a g}
22707 often have integer coefficients, this is not required.  Calc can also
22708 deal with polynomials over the rationals or floating-point reals.
22709 Polynomials with modulo-form coefficients are also useful in many
22710 applications; if you enter @samp{(x^2 + 3 x - 1) mod 5}, Calc
22711 automatically transforms this into a polynomial over the field of
22712 integers mod 5:  @samp{(1 mod 5) x^2 + (3 mod 5) x + (4 mod 5)}.
22714 Congratulations and thanks go to Ove Ewerlid
22715 (@code{ewerlid@@mizar.DoCS.UU.SE}), who contributed many of the
22716 polynomial routines used in the above commands.
22718 @xref{Decomposing Polynomials}, for several useful functions for
22719 extracting the individual coefficients of a polynomial.
22721 @node Calculus, Solving Equations, Polynomials, Algebra
22722 @section Calculus
22724 @noindent
22725 The following calculus commands do not automatically simplify their
22726 inputs or outputs using @code{calc-simplify}.  You may find it helps
22727 to do this by hand by typing @kbd{a s} or @kbd{a e}.  It may also help
22728 to use @kbd{a x} and/or @kbd{a c} to arrange a result in the most
22729 readable way.
22731 @menu
22732 * Differentiation::
22733 * Integration::
22734 * Customizing the Integrator::
22735 * Numerical Integration::
22736 * Taylor Series::
22737 @end menu
22739 @node Differentiation, Integration, Calculus, Calculus
22740 @subsection Differentiation
22742 @noindent
22743 @kindex a d
22744 @kindex H a d
22745 @pindex calc-derivative
22746 @tindex deriv
22747 @tindex tderiv
22748 The @kbd{a d} (@code{calc-derivative}) [@code{deriv}] command computes
22749 the derivative of the expression on the top of the stack with respect to
22750 some variable, which it will prompt you to enter.  Normally, variables
22751 in the formula other than the specified differentiation variable are
22752 considered constant, i.e., @samp{deriv(y,x)} is reduced to zero.  With
22753 the Hyperbolic flag, the @code{tderiv} (total derivative) operation is used
22754 instead, in which derivatives of variables are not reduced to zero
22755 unless those variables are known to be ``constant,'' i.e., independent
22756 of any other variables.  (The built-in special variables like @code{pi}
22757 are considered constant, as are variables that have been declared
22758 @code{const}; @pxref{Declarations}.)
22760 With a numeric prefix argument @var{n}, this command computes the
22761 @var{n}th derivative.
22763 When working with trigonometric functions, it is best to switch to
22764 radians mode first (with @w{@kbd{m r}}).  The derivative of @samp{sin(x)}
22765 in degrees is @samp{(pi/180) cos(x)}, probably not the expected
22766 answer!
22768 If you use the @code{deriv} function directly in an algebraic formula,
22769 you can write @samp{deriv(f,x,x0)} which represents the derivative
22770 of @cite{f} with respect to @cite{x}, evaluated at the point @c{$x=x_0$}
22771 @cite{x=x0}.
22773 If the formula being differentiated contains functions which Calc does
22774 not know, the derivatives of those functions are produced by adding
22775 primes (apostrophe characters).  For example, @samp{deriv(f(2x), x)}
22776 produces @samp{2 f'(2 x)}, where the function @code{f'} represents the
22777 derivative of @code{f}.
22779 For functions you have defined with the @kbd{Z F} command, Calc expands
22780 the functions according to their defining formulas unless you have
22781 also defined @code{f'} suitably.  For example, suppose we define
22782 @samp{sinc(x) = sin(x)/x} using @kbd{Z F}.  If we then differentiate
22783 the formula @samp{sinc(2 x)}, the formula will be expanded to
22784 @samp{sin(2 x) / (2 x)} and differentiated.  However, if we also
22785 define @samp{sinc'(x) = dsinc(x)}, say, then Calc will write the
22786 result as @samp{2 dsinc(2 x)}.  @xref{Algebraic Definitions}.
22788 For multi-argument functions @samp{f(x,y,z)}, the derivative with respect
22789 to the first argument is written @samp{f'(x,y,z)}; derivatives with
22790 respect to the other arguments are @samp{f'2(x,y,z)} and @samp{f'3(x,y,z)}.
22791 Various higher-order derivatives can be formed in the obvious way, e.g.,
22792 @samp{f'@var{}'(x)} (the second derivative of @code{f}) or
22793 @samp{f'@var{}'2'3(x,y,z)} (@code{f} differentiated with respect to each
22794 argument once).@refill
22796 @node Integration, Customizing the Integrator, Differentiation, Calculus
22797 @subsection Integration
22799 @noindent
22800 @kindex a i
22801 @pindex calc-integral
22802 @tindex integ
22803 The @kbd{a i} (@code{calc-integral}) [@code{integ}] command computes the
22804 indefinite integral of the expression on the top of the stack with
22805 respect to a variable.  The integrator is not guaranteed to work for
22806 all integrable functions, but it is able to integrate several large
22807 classes of formulas.  In particular, any polynomial or rational function
22808 (a polynomial divided by a polynomial) is acceptable.  (Rational functions
22809 don't have to be in explicit quotient form, however; @c{$x/(1+x^{-2})$}
22810 @cite{x/(1+x^-2)}
22811 is not strictly a quotient of polynomials, but it is equivalent to
22812 @cite{x^3/(x^2+1)}, which is.)  Also, square roots of terms involving
22813 @cite{x} and @cite{x^2} may appear in rational functions being
22814 integrated.  Finally, rational functions involving trigonometric or
22815 hyperbolic functions can be integrated.
22817 @ifinfo
22818 If you use the @code{integ} function directly in an algebraic formula,
22819 you can also write @samp{integ(f,x,v)} which expresses the resulting
22820 indefinite integral in terms of variable @code{v} instead of @code{x}.
22821 With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
22822 integral from @code{a} to @code{b}.
22823 @end ifinfo
22824 @tex  
22825 If you use the @code{integ} function directly in an algebraic formula,
22826 you can also write @samp{integ(f,x,v)} which expresses the resulting
22827 indefinite integral in terms of variable @code{v} instead of @code{x}.
22828 With four arguments, @samp{integ(f(x),x,a,b)} represents a definite
22829 integral $\int_a^b f(x) \, dx$.
22830 @end tex
22832 Please note that the current implementation of Calc's integrator sometimes
22833 produces results that are significantly more complex than they need to
22834 be.  For example, the integral Calc finds for @c{$1/(x+\sqrt{x^2+1})$}
22835 @cite{1/(x+sqrt(x^2+1))}
22836 is several times more complicated than the answer Mathematica
22837 returns for the same input, although the two forms are numerically
22838 equivalent.  Also, any indefinite integral should be considered to have
22839 an arbitrary constant of integration added to it, although Calc does not
22840 write an explicit constant of integration in its result.  For example,
22841 Calc's solution for @c{$1/(1+\tan x)$}
22842 @cite{1/(1+tan(x))} differs from the solution given
22843 in the @emph{CRC Math Tables} by a constant factor of @c{$\pi i / 2$}
22844 @cite{pi i / 2},
22845 due to a different choice of constant of integration.
22847 The Calculator remembers all the integrals it has done.  If conditions
22848 change in a way that would invalidate the old integrals, say, a switch
22849 from degrees to radians mode, then they will be thrown out.  If you
22850 suspect this is not happening when it should, use the
22851 @code{calc-flush-caches} command; @pxref{Caches}.
22853 @vindex IntegLimit
22854 Calc normally will pursue integration by substitution or integration by
22855 parts up to 3 nested times before abandoning an approach as fruitless.
22856 If the integrator is taking too long, you can lower this limit by storing
22857 a number (like 2) in the variable @code{IntegLimit}.  (The @kbd{s I}
22858 command is a convenient way to edit @code{IntegLimit}.)  If this variable
22859 has no stored value or does not contain a nonnegative integer, a limit
22860 of 3 is used.  The lower this limit is, the greater the chance that Calc
22861 will be unable to integrate a function it could otherwise handle.  Raising
22862 this limit allows the Calculator to solve more integrals, though the time
22863 it takes may grow exponentially.  You can monitor the integrator's actions
22864 by creating an Emacs buffer called @code{*Trace*}.  If such a buffer
22865 exists, the @kbd{a i} command will write a log of its actions there.
22867 If you want to manipulate integrals in a purely symbolic way, you can
22868 set the integration nesting limit to 0 to prevent all but fast
22869 table-lookup solutions of integrals.  You might then wish to define
22870 rewrite rules for integration by parts, various kinds of substitutions,
22871 and so on.  @xref{Rewrite Rules}.
22873 @node Customizing the Integrator, Numerical Integration, Integration, Calculus
22874 @subsection Customizing the Integrator
22876 @noindent
22877 @vindex IntegRules
22878 Calc has two built-in rewrite rules called @code{IntegRules} and
22879 @code{IntegAfterRules} which you can edit to define new integration
22880 methods.  @xref{Rewrite Rules}.  At each step of the integration process,
22881 Calc wraps the current integrand in a call to the fictitious function
22882 @samp{integtry(@var{expr},@var{var})}, where @var{expr} is the
22883 integrand and @var{var} is the integration variable.  If your rules
22884 rewrite this to be a plain formula (not a call to @code{integtry}), then
22885 Calc will use this formula as the integral of @var{expr}.  For example,
22886 the rule @samp{integtry(mysin(x),x) := -mycos(x)} would define a rule to
22887 integrate a function @code{mysin} that acts like the sine function.
22888 Then, putting @samp{4 mysin(2y+1)} on the stack and typing @kbd{a i y}
22889 will produce the integral @samp{-2 mycos(2y+1)}.  Note that Calc has
22890 automatically made various transformations on the integral to allow it
22891 to use your rule; integral tables generally give rules for
22892 @samp{mysin(a x + b)}, but you don't need to use this much generality
22893 in your @code{IntegRules}.
22895 @cindex Exponential integral Ei(x)
22896 @c @starindex
22897 @tindex Ei
22898 As a more serious example, the expression @samp{exp(x)/x} cannot be
22899 integrated in terms of the standard functions, so the ``exponential
22900 integral'' function @c{${\rm Ei}(x)$}
22901 @cite{Ei(x)} was invented to describe it.
22902 We can get Calc to do this integral in terms of a made-up @code{Ei}
22903 function by adding the rule @samp{[integtry(exp(x)/x, x) := Ei(x)]}
22904 to @code{IntegRules}.  Now entering @samp{exp(2x)/x} on the stack
22905 and typing @kbd{a i x} yields @samp{Ei(2 x)}.  This new rule will
22906 work with Calc's various built-in integration methods (such as
22907 integration by substitution) to solve a variety of other problems
22908 involving @code{Ei}:  For example, now Calc will also be able to
22909 integrate @samp{exp(exp(x))} and @samp{ln(ln(x))} (to get @samp{Ei(exp(x))}
22910 and @samp{x ln(ln(x)) - Ei(ln(x))}, respectively).
22912 Your rule may do further integration by calling @code{integ}.  For
22913 example, @samp{integtry(twice(u),x) := twice(integ(u))} allows Calc
22914 to integrate @samp{twice(sin(x))} to get @samp{twice(-cos(x))}.
22915 Note that @code{integ} was called with only one argument.  This notation
22916 is allowed only within @code{IntegRules}; it means ``integrate this
22917 with respect to the same integration variable.''  If Calc is unable
22918 to integrate @code{u}, the integration that invoked @code{IntegRules}
22919 also fails.  Thus integrating @samp{twice(f(x))} fails, returning the
22920 unevaluated integral @samp{integ(twice(f(x)), x)}.  It is still legal
22921 to call @code{integ} with two or more arguments, however; in this case,
22922 if @code{u} is not integrable, @code{twice} itself will still be
22923 integrated:  If the above rule is changed to @samp{... := twice(integ(u,x))},
22924 then integrating @samp{twice(f(x))} will yield @samp{twice(integ(f(x),x))}.
22926 If a rule instead produces the formula @samp{integsubst(@var{sexpr},
22927 @var{svar})}, either replacing the top-level @code{integtry} call or
22928 nested anywhere inside the expression, then Calc will apply the
22929 substitution @samp{@var{u} = @var{sexpr}(@var{svar})} to try to
22930 integrate the original @var{expr}.  For example, the rule
22931 @samp{sqrt(a) := integsubst(sqrt(x),x)} says that if Calc ever finds
22932 a square root in the integrand, it should attempt the substitution
22933 @samp{u = sqrt(x)}.  (This particular rule is unnecessary because
22934 Calc always tries ``obvious'' substitutions where @var{sexpr} actually
22935 appears in the integrand.)  The variable @var{svar} may be the same
22936 as the @var{var} that appeared in the call to @code{integtry}, but
22937 it need not be.
22939 When integrating according to an @code{integsubst}, Calc uses the
22940 equation solver to find the inverse of @var{sexpr} (if the integrand
22941 refers to @var{var} anywhere except in subexpressions that exactly
22942 match @var{sexpr}).  It uses the differentiator to find the derivative
22943 of @var{sexpr} and/or its inverse (it has two methods that use one
22944 derivative or the other).  You can also specify these items by adding
22945 extra arguments to the @code{integsubst} your rules construct; the
22946 general form is @samp{integsubst(@var{sexpr}, @var{svar}, @var{sinv},
22947 @var{sprime})}, where @var{sinv} is the inverse of @var{sexpr} (still
22948 written as a function of @var{svar}), and @var{sprime} is the
22949 derivative of @var{sexpr} with respect to @var{svar}.  If you don't
22950 specify these things, and Calc is not able to work them out on its
22951 own with the information it knows, then your substitution rule will
22952 work only in very specific, simple cases.
22954 Calc applies @code{IntegRules} as if by @kbd{C-u 1 a r IntegRules};
22955 in other words, Calc stops rewriting as soon as any rule in your rule
22956 set succeeds.  (If it weren't for this, the @samp{integsubst(sqrt(x),x)}
22957 example above would keep on adding layers of @code{integsubst} calls
22958 forever!)
22960 @vindex IntegSimpRules
22961 Another set of rules, stored in @code{IntegSimpRules}, are applied
22962 every time the integrator uses @kbd{a s} to simplify an intermediate
22963 result.  For example, putting the rule @samp{twice(x) := 2 x} into
22964 @code{IntegSimpRules} would tell Calc to convert the @code{twice}
22965 function into a form it knows whenever integration is attempted.
22967 One more way to influence the integrator is to define a function with
22968 the @kbd{Z F} command (@pxref{Algebraic Definitions}).  Calc's
22969 integrator automatically expands such functions according to their
22970 defining formulas, even if you originally asked for the function to
22971 be left unevaluated for symbolic arguments.  (Certain other Calc
22972 systems, such as the differentiator and the equation solver, also
22973 do this.)
22975 @vindex IntegAfterRules
22976 Sometimes Calc is able to find a solution to your integral, but it
22977 expresses the result in a way that is unnecessarily complicated.  If
22978 this happens, you can either use @code{integsubst} as described
22979 above to try to hint at a more direct path to the desired result, or
22980 you can use @code{IntegAfterRules}.  This is an extra rule set that
22981 runs after the main integrator returns its result; basically, Calc does
22982 an @kbd{a r IntegAfterRules} on the result before showing it to you.
22983 (It also does an @kbd{a s}, without @code{IntegSimpRules}, after that
22984 to further simplify the result.)  For example, Calc's integrator
22985 sometimes produces expressions of the form @samp{ln(1+x) - ln(1-x)};
22986 the default @code{IntegAfterRules} rewrite this into the more readable
22987 form @samp{2 arctanh(x)}.  Note that, unlike @code{IntegRules},
22988 @code{IntegSimpRules} and @code{IntegAfterRules} are applied any number
22989 of times until no further changes are possible.  Rewriting by
22990 @code{IntegAfterRules} occurs only after the main integrator has
22991 finished, not at every step as for @code{IntegRules} and
22992 @code{IntegSimpRules}.
22994 @node Numerical Integration, Taylor Series, Customizing the Integrator, Calculus
22995 @subsection Numerical Integration
22997 @noindent
22998 @kindex a I
22999 @pindex calc-num-integral
23000 @tindex ninteg
23001 If you want a purely numerical answer to an integration problem, you can
23002 use the @kbd{a I} (@code{calc-num-integral}) [@code{ninteg}] command.  This
23003 command prompts for an integration variable, a lower limit, and an
23004 upper limit.  Except for the integration variable, all other variables
23005 that appear in the integrand formula must have stored values.  (A stored
23006 value, if any, for the integration variable itself is ignored.)
23008 Numerical integration works by evaluating your formula at many points in
23009 the specified interval.  Calc uses an ``open Romberg'' method; this means
23010 that it does not evaluate the formula actually at the endpoints (so that
23011 it is safe to integrate @samp{sin(x)/x} from zero, for example).  Also,
23012 the Romberg method works especially well when the function being
23013 integrated is fairly smooth.  If the function is not smooth, Calc will
23014 have to evaluate it at quite a few points before it can accurately
23015 determine the value of the integral.
23017 Integration is much faster when the current precision is small.  It is
23018 best to set the precision to the smallest acceptable number of digits
23019 before you use @kbd{a I}.  If Calc appears to be taking too long, press
23020 @kbd{C-g} to halt it and try a lower precision.  If Calc still appears
23021 to need hundreds of evaluations, check to make sure your function is
23022 well-behaved in the specified interval.
23024 It is possible for the lower integration limit to be @samp{-inf} (minus
23025 infinity).  Likewise, the upper limit may be plus infinity.  Calc
23026 internally transforms the integral into an equivalent one with finite
23027 limits.  However, integration to or across singularities is not supported:
23028 The integral of @samp{1/sqrt(x)} from 0 to 1 exists (it can be found
23029 by Calc's symbolic integrator, for example), but @kbd{a I} will fail
23030 because the integrand goes to infinity at one of the endpoints.
23032 @node Taylor Series, , Numerical Integration, Calculus
23033 @subsection Taylor Series
23035 @noindent
23036 @kindex a t
23037 @pindex calc-taylor
23038 @tindex taylor
23039 The @kbd{a t} (@code{calc-taylor}) [@code{taylor}] command computes a
23040 power series expansion or Taylor series of a function.  You specify the
23041 variable and the desired number of terms.  You may give an expression of
23042 the form @samp{@var{var} = @var{a}} or @samp{@var{var} - @var{a}} instead
23043 of just a variable to produce a Taylor expansion about the point @var{a}.
23044 You may specify the number of terms with a numeric prefix argument;
23045 otherwise the command will prompt you for the number of terms.  Note that
23046 many series expansions have coefficients of zero for some terms, so you
23047 may appear to get fewer terms than you asked for.@refill
23049 If the @kbd{a i} command is unable to find a symbolic integral for a
23050 function, you can get an approximation by integrating the function's
23051 Taylor series.
23053 @node Solving Equations, Numerical Solutions, Calculus, Algebra
23054 @section Solving Equations
23056 @noindent
23057 @kindex a S
23058 @pindex calc-solve-for
23059 @tindex solve
23060 @cindex Equations, solving
23061 @cindex Solving equations
23062 The @kbd{a S} (@code{calc-solve-for}) [@code{solve}] command rearranges
23063 an equation to solve for a specific variable.  An equation is an
23064 expression of the form @cite{L = R}.  For example, the command @kbd{a S x}
23065 will rearrange @cite{y = 3x + 6} to the form, @cite{x = y/3 - 2}.  If the
23066 input is not an equation, it is treated like an equation of the
23067 form @cite{X = 0}.
23069 This command also works for inequalities, as in @cite{y < 3x + 6}.
23070 Some inequalities cannot be solved where the analogous equation could
23071 be; for example, solving @c{$a < b \, c$}
23072 @cite{a < b c} for @cite{b} is impossible
23073 without knowing the sign of @cite{c}.  In this case, @kbd{a S} will
23074 produce the result @c{$b \mathbin{\hbox{\code{!=}}} a/c$}
23075 @cite{b != a/c} (using the not-equal-to operator)
23076 to signify that the direction of the inequality is now unknown.  The
23077 inequality @c{$a \le b \, c$}
23078 @cite{a <= b c} is not even partially solved.
23079 @xref{Declarations}, for a way to tell Calc that the signs of the
23080 variables in a formula are in fact known.
23082 Two useful commands for working with the result of @kbd{a S} are
23083 @kbd{a .} (@pxref{Logical Operations}), which converts @cite{x = y/3 - 2}
23084 to @cite{y/3 - 2}, and @kbd{s l} (@pxref{Let Command}) which evaluates
23085 another formula with @cite{x} set equal to @cite{y/3 - 2}.
23087 @menu 
23088 * Multiple Solutions::
23089 * Solving Systems of Equations::
23090 * Decomposing Polynomials::
23091 @end menu
23093 @node Multiple Solutions, Solving Systems of Equations, Solving Equations, Solving Equations
23094 @subsection Multiple Solutions
23096 @noindent
23097 @kindex H a S
23098 @tindex fsolve
23099 Some equations have more than one solution.  The Hyperbolic flag
23100 (@code{H a S}) [@code{fsolve}] tells the solver to report the fully
23101 general family of solutions.  It will invent variables @code{n1},
23102 @code{n2}, @dots{}, which represent independent arbitrary integers, and
23103 @code{s1}, @code{s2}, @dots{}, which represent independent arbitrary
23104 signs (either @i{+1} or @i{-1}).  If you don't use the Hyperbolic
23105 flag, Calc will use zero in place of all arbitrary integers, and plus
23106 one in place of all arbitrary signs.  Note that variables like @code{n1}
23107 and @code{s1} are not given any special interpretation in Calc except by
23108 the equation solver itself.  As usual, you can use the @w{@kbd{s l}}
23109 (@code{calc-let}) command to obtain solutions for various actual values
23110 of these variables.
23112 For example, @kbd{' x^2 = y @key{RET} H a S x @key{RET}} solves to
23113 get @samp{x = s1 sqrt(y)}, indicating that the two solutions to the
23114 equation are @samp{sqrt(y)} and @samp{-sqrt(y)}.  Another way to
23115 think about it is that the square-root operation is really a
23116 two-valued function; since every Calc function must return a
23117 single result, @code{sqrt} chooses to return the positive result.
23118 Then @kbd{H a S} doctors this result using @code{s1} to indicate
23119 the full set of possible values of the mathematical square-root.
23121 There is a similar phenomenon going the other direction:  Suppose
23122 we solve @samp{sqrt(y) = x} for @code{y}.  Calc squares both sides
23123 to get @samp{y = x^2}.  This is correct, except that it introduces
23124 some dubious solutions.  Consider solving @samp{sqrt(y) = -3}:
23125 Calc will report @cite{y = 9} as a valid solution, which is true
23126 in the mathematical sense of square-root, but false (there is no
23127 solution) for the actual Calc positive-valued @code{sqrt}.  This
23128 happens for both @kbd{a S} and @kbd{H a S}.
23130 @cindex @code{GenCount} variable
23131 @vindex GenCount
23132 @c @starindex
23133 @tindex an
23134 @c @starindex
23135 @tindex as
23136 If you store a positive integer in the Calc variable @code{GenCount},
23137 then Calc will generate formulas of the form @samp{as(@var{n})} for
23138 arbitrary signs, and @samp{an(@var{n})} for arbitrary integers,
23139 where @var{n} represents successive values taken by incrementing
23140 @code{GenCount} by one.  While the normal arbitrary sign and
23141 integer symbols start over at @code{s1} and @code{n1} with each
23142 new Calc command, the @code{GenCount} approach will give each
23143 arbitrary value a name that is unique throughout the entire Calc
23144 session.  Also, the arbitrary values are function calls instead
23145 of variables, which is advantageous in some cases.  For example,
23146 you can make a rewrite rule that recognizes all arbitrary signs
23147 using a pattern like @samp{as(n)}.  The @kbd{s l} command only works
23148 on variables, but you can use the @kbd{a b} (@code{calc-substitute})
23149 command to substitute actual values for function calls like @samp{as(3)}.
23151 The @kbd{s G} (@code{calc-edit-GenCount}) command is a convenient
23152 way to create or edit this variable.  Press @kbd{M-# M-#} to finish.
23154 If you have not stored a value in @code{GenCount}, or if the value
23155 in that variable is not a positive integer, the regular
23156 @code{s1}/@code{n1} notation is used.
23158 @kindex I a S
23159 @kindex H I a S
23160 @tindex finv
23161 @tindex ffinv
23162 With the Inverse flag, @kbd{I a S} [@code{finv}] treats the expression
23163 on top of the stack as a function of the specified variable and solves
23164 to find the inverse function, written in terms of the same variable.
23165 For example, @kbd{I a S x} inverts @cite{2x + 6} to @cite{x/2 - 3}.
23166 You can use both Inverse and Hyperbolic [@code{ffinv}] to obtain a
23167 fully general inverse, as described above.
23169 @kindex a P
23170 @pindex calc-poly-roots
23171 @tindex roots
23172 Some equations, specifically polynomials, have a known, finite number
23173 of solutions.  The @kbd{a P} (@code{calc-poly-roots}) [@code{roots}]
23174 command uses @kbd{H a S} to solve an equation in general form, then, for
23175 all arbitrary-sign variables like @code{s1}, and all arbitrary-integer
23176 variables like @code{n1} for which @code{n1} only usefully varies over
23177 a finite range, it expands these variables out to all their possible
23178 values.  The results are collected into a vector, which is returned.
23179 For example, @samp{roots(x^4 = 1, x)} returns the four solutions
23180 @samp{[1, -1, (0, 1), (0, -1)]}.  Generally an @var{n}th degree
23181 polynomial will always have @var{n} roots on the complex plane.
23182 (If you have given a @code{real} declaration for the solution
23183 variable, then only the real-valued solutions, if any, will be
23184 reported; @pxref{Declarations}.)
23186 Note that because @kbd{a P} uses @kbd{H a S}, it is able to deliver
23187 symbolic solutions if the polynomial has symbolic coefficients.  Also
23188 note that Calc's solver is not able to get exact symbolic solutions
23189 to all polynomials.  Polynomials containing powers up to @cite{x^4}
23190 can always be solved exactly; polynomials of higher degree sometimes
23191 can be:  @cite{x^6 + x^3 + 1} is converted to @cite{(x^3)^2 + (x^3) + 1},
23192 which can be solved for @cite{x^3} using the quadratic equation, and then
23193 for @cite{x} by taking cube roots.  But in many cases, like
23194 @cite{x^6 + x + 1}, Calc does not know how to rewrite the polynomial
23195 into a form it can solve.  The @kbd{a P} command can still deliver a
23196 list of numerical roots, however, provided that symbolic mode (@kbd{m s})
23197 is not turned on.  (If you work with symbolic mode on, recall that the
23198 @kbd{N} (@code{calc-eval-num}) key is a handy way to reevaluate the
23199 formula on the stack with symbolic mode temporarily off.)  Naturally,
23200 @kbd{a P} can only provide numerical roots if the polynomial coefficents
23201 are all numbers (real or complex).
23203 @node Solving Systems of Equations, Decomposing Polynomials, Multiple Solutions, Solving Equations
23204 @subsection Solving Systems of Equations
23206 @noindent
23207 @cindex Systems of equations, symbolic
23208 You can also use the commands described above to solve systems of
23209 simultaneous equations.  Just create a vector of equations, then
23210 specify a vector of variables for which to solve.  (You can omit
23211 the surrounding brackets when entering the vector of variables
23212 at the prompt.)
23214 For example, putting @samp{[x + y = a, x - y = b]} on the stack
23215 and typing @kbd{a S x,y @key{RET}} produces the vector of solutions
23216 @samp{[x = a - (a-b)/2, y = (a-b)/2]}.  The result vector will
23217 have the same length as the variables vector, and the variables
23218 will be listed in the same order there.  Note that the solutions
23219 are not always simplified as far as possible; the solution for
23220 @cite{x} here could be improved by an application of the @kbd{a n}
23221 command.
23223 Calc's algorithm works by trying to eliminate one variable at a
23224 time by solving one of the equations for that variable and then
23225 substituting into the other equations.  Calc will try all the
23226 possibilities, but you can speed things up by noting that Calc
23227 first tries to eliminate the first variable with the first
23228 equation, then the second variable with the second equation,
23229 and so on.  It also helps to put the simpler (e.g., more linear)
23230 equations toward the front of the list.  Calc's algorithm will
23231 solve any system of linear equations, and also many kinds of
23232 nonlinear systems.
23234 @c @starindex
23235 @tindex elim
23236 Normally there will be as many variables as equations.  If you
23237 give fewer variables than equations (an ``over-determined'' system
23238 of equations), Calc will find a partial solution.  For example,
23239 typing @kbd{a S y @key{RET}} with the above system of equations
23240 would produce @samp{[y = a - x]}.  There are now several ways to
23241 express this solution in terms of the original variables; Calc uses
23242 the first one that it finds.  You can control the choice by adding
23243 variable specifiers of the form @samp{elim(@var{v})} to the
23244 variables list.  This says that @var{v} should be eliminated from
23245 the equations; the variable will not appear at all in the solution.
23246 For example, typing @kbd{a S y,elim(x)} would yield
23247 @samp{[y = a - (b+a)/2]}.
23249 If the variables list contains only @code{elim} specifiers,
23250 Calc simply eliminates those variables from the equations
23251 and then returns the resulting set of equations.  For example,
23252 @kbd{a S elim(x)} produces @samp{[a - 2 y = b]}.  Every variable
23253 eliminated will reduce the number of equations in the system
23254 by one.
23256 Again, @kbd{a S} gives you one solution to the system of
23257 equations.  If there are several solutions, you can use @kbd{H a S}
23258 to get a general family of solutions, or, if there is a finite
23259 number of solutions, you can use @kbd{a P} to get a list.  (In
23260 the latter case, the result will take the form of a matrix where
23261 the rows are different solutions and the columns correspond to the
23262 variables you requested.)
23264 Another way to deal with certain kinds of overdetermined systems of
23265 equations is the @kbd{a F} command, which does least-squares fitting
23266 to satisfy the equations.  @xref{Curve Fitting}.
23268 @node Decomposing Polynomials, , Solving Systems of Equations, Solving Equations
23269 @subsection Decomposing Polynomials
23271 @noindent
23272 @c @starindex
23273 @tindex poly
23274 The @code{poly} function takes a polynomial and a variable as
23275 arguments, and returns a vector of polynomial coefficients (constant
23276 coefficient first).  For example, @samp{poly(x^3 + 2 x, x)} returns
23277 @cite{[0, 2, 0, 1]}.  If the input is not a polynomial in @cite{x},
23278 the call to @code{poly} is left in symbolic form.  If the input does
23279 not involve the variable @cite{x}, the input is returned in a list
23280 of length one, representing a polynomial with only a constant
23281 coefficient.  The call @samp{poly(x, x)} returns the vector @cite{[0, 1]}.
23282 The last element of the returned vector is guaranteed to be nonzero;
23283 note that @samp{poly(0, x)} returns the empty vector @cite{[]}.
23284 Note also that @cite{x} may actually be any formula; for example,
23285 @samp{poly(sin(x)^2 - sin(x) + 3, sin(x))} returns @cite{[3, -1, 1]}.
23287 @cindex Coefficients of polynomial
23288 @cindex Degree of polynomial
23289 To get the @cite{x^k} coefficient of polynomial @cite{p}, use
23290 @samp{poly(p, x)_(k+1)}.  To get the degree of polynomial @cite{p},
23291 use @samp{vlen(poly(p, x)) - 1}.  For example, @samp{poly((x+1)^4, x)}
23292 returns @samp{[1, 4, 6, 4, 1]}, so @samp{poly((x+1)^4, x)_(2+1)}
23293 gives the @cite{x^2} coefficient of this polynomial, 6.
23295 @c @starindex
23296 @tindex gpoly
23297 One important feature of the solver is its ability to recognize
23298 formulas which are ``essentially'' polynomials.  This ability is
23299 made available to the user through the @code{gpoly} function, which
23300 is used just like @code{poly}:  @samp{gpoly(@var{expr}, @var{var})}.
23301 If @var{expr} is a polynomial in some term which includes @var{var}, then
23302 this function will return a vector @samp{[@var{x}, @var{c}, @var{a}]}
23303 where @var{x} is the term that depends on @var{var}, @var{c} is a
23304 vector of polynomial coefficients (like the one returned by @code{poly}),
23305 and @var{a} is a multiplier which is usually 1.  Basically,
23306 @samp{@var{expr} = @var{a}*(@var{c}_1 + @var{c}_2 @var{x} +
23307 @var{c}_3 @var{x}^2 + ...)}.  The last element of @var{c} is
23308 guaranteed to be non-zero, and @var{c} will not equal @samp{[1]}
23309 (i.e., the trivial decomposition @var{expr} = @var{x} is not
23310 considered a polynomial).  One side effect is that @samp{gpoly(x, x)}
23311 and @samp{gpoly(6, x)}, both of which might be expected to recognize
23312 their arguments as polynomials, will not because the decomposition
23313 is considered trivial.
23315 For example, @samp{gpoly((x-2)^2, x)} returns @samp{[x, [4, -4, 1], 1]},
23316 since the expanded form of this polynomial is @cite{4 - 4 x + x^2}.
23318 The term @var{x} may itself be a polynomial in @var{var}.  This is
23319 done to reduce the size of the @var{c} vector.  For example,
23320 @samp{gpoly(x^4 + x^2 - 1, x)} returns @samp{[x^2, [-1, 1, 1], 1]},
23321 since a quadratic polynomial in @cite{x^2} is easier to solve than
23322 a quartic polynomial in @cite{x}.
23324 A few more examples of the kinds of polynomials @code{gpoly} can
23325 discover:
23327 @smallexample
23328 sin(x) - 1               [sin(x), [-1, 1], 1]
23329 x + 1/x - 1              [x, [1, -1, 1], 1/x]
23330 x + 1/x                  [x^2, [1, 1], 1/x]
23331 x^3 + 2 x                [x^2, [2, 1], x]
23332 x + x^2:3 + sqrt(x)      [x^1:6, [1, 1, 0, 1], x^1:2]
23333 x^(2a) + 2 x^a + 5       [x^a, [5, 2, 1], 1]
23334 (exp(-x) + exp(x)) / 2   [e^(2 x), [0.5, 0.5], e^-x]
23335 @end smallexample
23337 The @code{poly} and @code{gpoly} functions accept a third integer argument
23338 which specifies the largest degree of polynomial that is acceptable.
23339 If this is @cite{n}, then only @var{c} vectors of length @cite{n+1}
23340 or less will be returned.  Otherwise, the @code{poly} or @code{gpoly}
23341 call will remain in symbolic form.  For example, the equation solver
23342 can handle quartics and smaller polynomials, so it calls
23343 @samp{gpoly(@var{expr}, @var{var}, 4)} to discover whether @var{expr}
23344 can be treated by its linear, quadratic, cubic, or quartic formulas.
23346 @c @starindex
23347 @tindex pdeg
23348 The @code{pdeg} function computes the degree of a polynomial;
23349 @samp{pdeg(p,x)} is the highest power of @code{x} that appears in
23350 @code{p}.  This is the same as @samp{vlen(poly(p,x))-1}, but is
23351 much more efficient.  If @code{p} is constant with respect to @code{x},
23352 then @samp{pdeg(p,x) = 0}.  If @code{p} is not a polynomial in @code{x}
23353 (e.g., @samp{pdeg(2 cos(x), x)}, the function remains unevaluated.
23354 It is possible to omit the second argument @code{x}, in which case
23355 @samp{pdeg(p)} returns the highest total degree of any term of the
23356 polynomial, counting all variables that appear in @code{p}.  Note
23357 that @code{pdeg(c) = pdeg(c,x) = 0} for any nonzero constant @code{c};
23358 the degree of the constant zero is considered to be @code{-inf}
23359 (minus infinity).
23361 @c @starindex
23362 @tindex plead
23363 The @code{plead} function finds the leading term of a polynomial.
23364 Thus @samp{plead(p,x)} is equivalent to @samp{poly(p,x)_vlen(poly(p,x))},
23365 though again more efficient.  In particular, @samp{plead((2x+1)^10, x)}
23366 returns 1024 without expanding out the list of coefficients.  The
23367 value of @code{plead(p,x)} will be zero only if @cite{p = 0}.
23369 @c @starindex
23370 @tindex pcont
23371 The @code{pcont} function finds the @dfn{content} of a polynomial.  This
23372 is the greatest common divisor of all the coefficients of the polynomial.
23373 With two arguments, @code{pcont(p,x)} effectively uses @samp{poly(p,x)}
23374 to get a list of coefficients, then uses @code{pgcd} (the polynomial
23375 GCD function) to combine these into an answer.  For example,
23376 @samp{pcont(4 x y^2 + 6 x^2 y, x)} is @samp{2 y}.  The content is
23377 basically the ``biggest'' polynomial that can be divided into @code{p}
23378 exactly.  The sign of the content is the same as the sign of the leading
23379 coefficient.
23381 With only one argument, @samp{pcont(p)} computes the numerical
23382 content of the polynomial, i.e., the @code{gcd} of the numerical
23383 coefficients of all the terms in the formula.  Note that @code{gcd}
23384 is defined on rational numbers as well as integers; it computes
23385 the @code{gcd} of the numerators and the @code{lcm} of the
23386 denominators.  Thus @samp{pcont(4:3 x y^2 + 6 x^2 y)} returns 2:3.
23387 Dividing the polynomial by this number will clear all the
23388 denominators, as well as dividing by any common content in the
23389 numerators.  The numerical content of a polynomial is negative only
23390 if all the coefficients in the polynomial are negative.
23392 @c @starindex
23393 @tindex pprim
23394 The @code{pprim} function finds the @dfn{primitive part} of a
23395 polynomial, which is simply the polynomial divided (using @code{pdiv}
23396 if necessary) by its content.  If the input polynomial has rational
23397 coefficients, the result will have integer coefficients in simplest
23398 terms.
23400 @node Numerical Solutions, Curve Fitting, Solving Equations, Algebra
23401 @section Numerical Solutions
23403 @noindent
23404 Not all equations can be solved symbolically.  The commands in this
23405 section use numerical algorithms that can find a solution to a specific
23406 instance of an equation to any desired accuracy.  Note that the
23407 numerical commands are slower than their algebraic cousins; it is a
23408 good idea to try @kbd{a S} before resorting to these commands.
23410 (@xref{Curve Fitting}, for some other, more specialized, operations
23411 on numerical data.)
23413 @menu
23414 * Root Finding::
23415 * Minimization::
23416 * Numerical Systems of Equations::
23417 @end menu
23419 @node Root Finding, Minimization, Numerical Solutions, Numerical Solutions
23420 @subsection Root Finding
23422 @noindent
23423 @kindex a R
23424 @pindex calc-find-root
23425 @tindex root
23426 @cindex Newton's method
23427 @cindex Roots of equations
23428 @cindex Numerical root-finding
23429 The @kbd{a R} (@code{calc-find-root}) [@code{root}] command finds a
23430 numerical solution (or @dfn{root}) of an equation.  (This command treats
23431 inequalities the same as equations.  If the input is any other kind
23432 of formula, it is interpreted as an equation of the form @cite{X = 0}.)
23434 The @kbd{a R} command requires an initial guess on the top of the
23435 stack, and a formula in the second-to-top position.  It prompts for a
23436 solution variable, which must appear in the formula.  All other variables
23437 that appear in the formula must have assigned values, i.e., when
23438 a value is assigned to the solution variable and the formula is
23439 evaluated with @kbd{=}, it should evaluate to a number.  Any assigned
23440 value for the solution variable itself is ignored and unaffected by
23441 this command.
23443 When the command completes, the initial guess is replaced on the stack
23444 by a vector of two numbers:  The value of the solution variable that
23445 solves the equation, and the difference between the lefthand and
23446 righthand sides of the equation at that value.  Ordinarily, the second
23447 number will be zero or very nearly zero.  (Note that Calc uses a
23448 slightly higher precision while finding the root, and thus the second
23449 number may be slightly different from the value you would compute from
23450 the equation yourself.)
23452 The @kbd{v h} (@code{calc-head}) command is a handy way to extract
23453 the first element of the result vector, discarding the error term.
23455 The initial guess can be a real number, in which case Calc searches
23456 for a real solution near that number, or a complex number, in which
23457 case Calc searches the whole complex plane near that number for a
23458 solution, or it can be an interval form which restricts the search
23459 to real numbers inside that interval.
23461 Calc tries to use @kbd{a d} to take the derivative of the equation.
23462 If this succeeds, it uses Newton's method.  If the equation is not
23463 differentiable Calc uses a bisection method.  (If Newton's method
23464 appears to be going astray, Calc switches over to bisection if it
23465 can, or otherwise gives up.  In this case it may help to try again
23466 with a slightly different initial guess.)  If the initial guess is a
23467 complex number, the function must be differentiable.
23469 If the formula (or the difference between the sides of an equation)
23470 is negative at one end of the interval you specify and positive at
23471 the other end, the root finder is guaranteed to find a root.
23472 Otherwise, Calc subdivides the interval into small parts looking for
23473 positive and negative values to bracket the root.  When your guess is
23474 an interval, Calc will not look outside that interval for a root.
23476 @kindex H a R
23477 @tindex wroot
23478 The @kbd{H a R} [@code{wroot}] command is similar to @kbd{a R}, except
23479 that if the initial guess is an interval for which the function has
23480 the same sign at both ends, then rather than subdividing the interval
23481 Calc attempts to widen it to enclose a root.  Use this mode if
23482 you are not sure if the function has a root in your interval.
23484 If the function is not differentiable, and you give a simple number
23485 instead of an interval as your initial guess, Calc uses this widening
23486 process even if you did not type the Hyperbolic flag.  (If the function
23487 @emph{is} differentiable, Calc uses Newton's method which does not
23488 require a bounding interval in order to work.)
23490 If Calc leaves the @code{root} or @code{wroot} function in symbolic
23491 form on the stack, it will normally display an explanation for why
23492 no root was found.  If you miss this explanation, press @kbd{w}
23493 (@code{calc-why}) to get it back.
23495 @node Minimization, Numerical Systems of Equations, Root Finding, Numerical Solutions
23496 @subsection Minimization
23498 @noindent
23499 @kindex a N
23500 @kindex H a N
23501 @kindex a X
23502 @kindex H a X
23503 @pindex calc-find-minimum
23504 @pindex calc-find-maximum
23505 @tindex minimize
23506 @tindex maximize
23507 @cindex Minimization, numerical
23508 The @kbd{a N} (@code{calc-find-minimum}) [@code{minimize}] command
23509 finds a minimum value for a formula.  It is very similar in operation
23510 to @kbd{a R} (@code{calc-find-root}):  You give the formula and an initial
23511 guess on the stack, and are prompted for the name of a variable.  The guess
23512 may be either a number near the desired minimum, or an interval enclosing
23513 the desired minimum.  The function returns a vector containing the
23514 value of the the variable which minimizes the formula's value, along
23515 with the minimum value itself.
23517 Note that this command looks for a @emph{local} minimum.  Many functions
23518 have more than one minimum; some, like @c{$x \sin x$}
23519 @cite{x sin(x)}, have infinitely
23520 many.  In fact, there is no easy way to define the ``global'' minimum
23521 of @c{$x \sin x$}
23522 @cite{x sin(x)} but Calc can still locate any particular local minimum
23523 for you.  Calc basically goes downhill from the initial guess until it
23524 finds a point at which the function's value is greater both to the left
23525 and to the right.  Calc does not use derivatives when minimizing a function.
23527 If your initial guess is an interval and it looks like the minimum
23528 occurs at one or the other endpoint of the interval, Calc will return
23529 that endpoint only if that endpoint is closed; thus, minimizing @cite{17 x}
23530 over @cite{[2..3]} will return @cite{[2, 38]}, but minimizing over
23531 @cite{(2..3]} would report no minimum found.  In general, you should
23532 use closed intervals to find literally the minimum value in that
23533 range of @cite{x}, or open intervals to find the local minimum, if
23534 any, that happens to lie in that range.
23536 Most functions are smooth and flat near their minimum values.  Because
23537 of this flatness, if the current precision is, say, 12 digits, the
23538 variable can only be determined meaningfully to about six digits.  Thus
23539 you should set the precision to twice as many digits as you need in your
23540 answer.
23542 @c @mindex wmin@idots
23543 @tindex wminimize
23544 @c @mindex wmax@idots
23545 @tindex wmaximize
23546 The @kbd{H a N} [@code{wminimize}] command, analogously to @kbd{H a R},
23547 expands the guess interval to enclose a minimum rather than requiring
23548 that the minimum lie inside the interval you supply.
23550 The @kbd{a X} (@code{calc-find-maximum}) [@code{maximize}] and
23551 @kbd{H a X} [@code{wmaximize}] commands effectively minimize the
23552 negative of the formula you supply.
23554 The formula must evaluate to a real number at all points inside the
23555 interval (or near the initial guess if the guess is a number).  If
23556 the initial guess is a complex number the variable will be minimized
23557 over the complex numbers; if it is real or an interval it will
23558 be minimized over the reals.
23560 @node Numerical Systems of Equations, , Minimization, Numerical Solutions
23561 @subsection Systems of Equations
23563 @noindent
23564 @cindex Systems of equations, numerical
23565 The @kbd{a R} command can also solve systems of equations.  In this
23566 case, the equation should instead be a vector of equations, the
23567 guess should instead be a vector of numbers (intervals are not
23568 supported), and the variable should be a vector of variables.  You
23569 can omit the brackets while entering the list of variables.  Each
23570 equation must be differentiable by each variable for this mode to
23571 work.  The result will be a vector of two vectors:  The variable
23572 values that solved the system of equations, and the differences
23573 between the sides of the equations with those variable values.
23574 There must be the same number of equations as variables.  Since
23575 only plain numbers are allowed as guesses, the Hyperbolic flag has
23576 no effect when solving a system of equations.
23578 It is also possible to minimize over many variables with @kbd{a N}
23579 (or maximize with @kbd{a X}).  Once again the variable name should
23580 be replaced by a vector of variables, and the initial guess should
23581 be an equal-sized vector of initial guesses.  But, unlike the case of
23582 multidimensional @kbd{a R}, the formula being minimized should
23583 still be a single formula, @emph{not} a vector.  Beware that
23584 multidimensional minimization is currently @emph{very} slow.
23586 @node Curve Fitting, Summations, Numerical Solutions, Algebra
23587 @section Curve Fitting
23589 @noindent
23590 The @kbd{a F} command fits a set of data to a @dfn{model formula},
23591 such as @cite{y = m x + b} where @cite{m} and @cite{b} are parameters
23592 to be determined.  For a typical set of measured data there will be
23593 no single @cite{m} and @cite{b} that exactly fit the data; in this
23594 case, Calc chooses values of the parameters that provide the closest
23595 possible fit.
23597 @menu
23598 * Linear Fits::
23599 * Polynomial and Multilinear Fits::
23600 * Error Estimates for Fits::
23601 * Standard Nonlinear Models::
23602 * Curve Fitting Details::
23603 * Interpolation::
23604 @end menu
23606 @node Linear Fits, Polynomial and Multilinear Fits, Curve Fitting, Curve Fitting
23607 @subsection Linear Fits
23609 @noindent
23610 @kindex a F
23611 @pindex calc-curve-fit
23612 @tindex fit
23613 @cindex Linear regression
23614 @cindex Least-squares fits
23615 The @kbd{a F} (@code{calc-curve-fit}) [@code{fit}] command attempts
23616 to fit a set of data (@cite{x} and @cite{y} vectors of numbers) to a
23617 straight line, polynomial, or other function of @cite{x}.  For the
23618 moment we will consider only the case of fitting to a line, and we
23619 will ignore the issue of whether or not the model was in fact a good
23620 fit for the data.
23622 In a standard linear least-squares fit, we have a set of @cite{(x,y)}
23623 data points that we wish to fit to the model @cite{y = m x + b}
23624 by adjusting the parameters @cite{m} and @cite{b} to make the @cite{y}
23625 values calculated from the formula be as close as possible to the actual
23626 @cite{y} values in the data set.  (In a polynomial fit, the model is
23627 instead, say, @cite{y = a x^3 + b x^2 + c x + d}.  In a multilinear fit,
23628 we have data points of the form @cite{(x_1,x_2,x_3,y)} and our model is
23629 @cite{y = a x_1 + b x_2 + c x_3 + d}.  These will be discussed later.)
23631 In the model formula, variables like @cite{x} and @cite{x_2} are called
23632 the @dfn{independent variables}, and @cite{y} is the @dfn{dependent
23633 variable}.  Variables like @cite{m}, @cite{a}, and @cite{b} are called
23634 the @dfn{parameters} of the model.
23636 The @kbd{a F} command takes the data set to be fitted from the stack.
23637 By default, it expects the data in the form of a matrix.  For example,
23638 for a linear or polynomial fit, this would be a @c{$2\times N$}
23639 @asis{2xN} matrix where
23640 the first row is a list of @cite{x} values and the second row has the
23641 corresponding @cite{y} values.  For the multilinear fit shown above,
23642 the matrix would have four rows (@cite{x_1}, @cite{x_2}, @cite{x_3}, and
23643 @cite{y}, respectively).
23645 If you happen to have an @c{$N\times2$}
23646 @asis{Nx2} matrix instead of a @c{$2\times N$}
23647 @asis{2xN} matrix,
23648 just press @kbd{v t} first to transpose the matrix.
23650 After you type @kbd{a F}, Calc prompts you to select a model.  For a
23651 linear fit, press the digit @kbd{1}.
23653 Calc then prompts for you to name the variables.  By default it chooses
23654 high letters like @cite{x} and @cite{y} for independent variables and
23655 low letters like @cite{a} and @cite{b} for parameters.  (The dependent
23656 variable doesn't need a name.)  The two kinds of variables are separated
23657 by a semicolon.  Since you generally care more about the names of the
23658 independent variables than of the parameters, Calc also allows you to
23659 name only those and let the parameters use default names.
23661 For example, suppose the data matrix
23663 @ifinfo
23664 @group
23665 @example
23666 [ [ 1, 2, 3, 4,  5  ]
23667   [ 5, 7, 9, 11, 13 ] ]
23668 @end example
23669 @end group
23670 @end ifinfo
23671 @tex
23672 \turnoffactive
23673 \turnoffactive
23674 \beforedisplay
23675 $$ \pmatrix{ 1 & 2 & 3 & 4  & 5  \cr
23676              5 & 7 & 9 & 11 & 13 }
23678 \afterdisplay
23679 @end tex
23681 @noindent
23682 is on the stack and we wish to do a simple linear fit.  Type
23683 @kbd{a F}, then @kbd{1} for the model, then @kbd{RET} to use
23684 the default names.  The result will be the formula @cite{3 + 2 x}
23685 on the stack.  Calc has created the model expression @kbd{a + b x},
23686 then found the optimal values of @cite{a} and @cite{b} to fit the
23687 data.  (In this case, it was able to find an exact fit.)  Calc then
23688 substituted those values for @cite{a} and @cite{b} in the model
23689 formula.
23691 The @kbd{a F} command puts two entries in the trail.  One is, as
23692 always, a copy of the result that went to the stack; the other is
23693 a vector of the actual parameter values, written as equations:
23694 @cite{[a = 3, b = 2]}, in case you'd rather read them in a list
23695 than pick them out of the formula.  (You can type @kbd{t y}
23696 to move this vector to the stack; see @ref{Trail Commands}.
23698 Specifying a different independent variable name will affect the
23699 resulting formula: @kbd{a F 1 k RET} produces @kbd{3 + 2 k}.
23700 Changing the parameter names (say, @kbd{a F 1 k;b,m RET}) will affect
23701 the equations that go into the trail.
23703 @tex
23704 \bigskip
23705 @end tex
23707 To see what happens when the fit is not exact, we could change
23708 the number 13 in the data matrix to 14 and try the fit again.
23709 The result is:
23711 @example
23712 2.6 + 2.2 x
23713 @end example
23715 Evaluating this formula, say with @kbd{v x 5 RET TAB V M $ RET}, shows
23716 a reasonably close match to the y-values in the data.
23718 @example
23719 [4.8, 7., 9.2, 11.4, 13.6]
23720 @end example
23722 Since there is no line which passes through all the @i{N} data points,
23723 Calc has chosen a line that best approximates the data points using
23724 the method of least squares.  The idea is to define the @dfn{chi-square}
23725 error measure
23727 @ifinfo
23728 @example
23729 chi^2 = sum((y_i - (a + b x_i))^2, i, 1, N)
23730 @end example
23731 @end ifinfo
23732 @tex
23733 \turnoffactive
23734 \beforedisplay
23735 $$ \chi^2 = \sum_{i=1}^N (y_i - (a + b x_i))^2 $$
23736 \afterdisplay
23737 @end tex
23739 @noindent
23740 which is clearly zero if @cite{a + b x} exactly fits all data points,
23741 and increases as various @cite{a + b x_i} values fail to match the
23742 corresponding @cite{y_i} values.  There are several reasons why the
23743 summand is squared, one of them being to ensure that @c{$\chi^2 \ge 0$}
23744 @cite{chi^2 >= 0}.
23745 Least-squares fitting simply chooses the values of @cite{a} and @cite{b}
23746 for which the error @c{$\chi^2$}
23747 @cite{chi^2} is as small as possible.
23749 Other kinds of models do the same thing but with a different model
23750 formula in place of @cite{a + b x_i}.
23752 @tex
23753 \bigskip
23754 @end tex
23756 A numeric prefix argument causes the @kbd{a F} command to take the
23757 data in some other form than one big matrix.  A positive argument @i{N}
23758 will take @i{N} items from the stack, corresponding to the @i{N} rows
23759 of a data matrix.  In the linear case, @i{N} must be 2 since there
23760 is always one independent variable and one dependent variable.
23762 A prefix of zero or plain @kbd{C-u} is a compromise; Calc takes two
23763 items from the stack, an @i{N}-row matrix of @cite{x} values, and a
23764 vector of @cite{y} values.  If there is only one independent variable,
23765 the @cite{x} values can be either a one-row matrix or a plain vector,
23766 in which case the @kbd{C-u} prefix is the same as a @w{@kbd{C-u 2}} prefix.
23768 @node Polynomial and Multilinear Fits, Error Estimates for Fits, Linear Fits, Curve Fitting
23769 @subsection Polynomial and Multilinear Fits
23771 @noindent
23772 To fit the data to higher-order polynomials, just type one of the
23773 digits @kbd{2} through @kbd{9} when prompted for a model.  For example,
23774 we could fit the original data matrix from the previous section
23775 (with 13, not 14) to a parabola instead of a line by typing
23776 @kbd{a F 2 RET}.
23778 @example
23779 2.00000000001 x - 1.5e-12 x^2 + 2.99999999999
23780 @end example
23782 Note that since the constant and linear terms are enough to fit the
23783 data exactly, it's no surprise that Calc chose a tiny contribution
23784 for @cite{x^2}.  (The fact that it's not exactly zero is due only
23785 to roundoff error.  Since our data are exact integers, we could get
23786 an exact answer by typing @kbd{m f} first to get fraction mode.
23787 Then the @cite{x^2} term would vanish altogether.  Usually, though,
23788 the data being fitted will be approximate floats so fraction mode
23789 won't help.)
23791 Doing the @kbd{a F 2} fit on the data set with 14 instead of 13
23792 gives a much larger @cite{x^2} contribution, as Calc bends the
23793 line slightly to improve the fit.
23795 @example
23796 0.142857142855 x^2 + 1.34285714287 x + 3.59999999998
23797 @end example
23799 An important result from the theory of polynomial fitting is that it
23800 is always possible to fit @i{N} data points exactly using a polynomial
23801 of degree @i{N-1}, sometimes called an @dfn{interpolating polynomial}.
23802 Using the modified (14) data matrix, a model number of 4 gives
23803 a polynomial that exactly matches all five data points:
23805 @example
23806 0.04167 x^4 - 0.4167 x^3 + 1.458 x^2 - 0.08333 x + 4.
23807 @end example
23809 The actual coefficients we get with a precision of 12, like
23810 @cite{0.0416666663588}, clearly suffer from loss of precision.
23811 It is a good idea to increase the working precision to several
23812 digits beyond what you need when you do a fitting operation.
23813 Or, if your data are exact, use fraction mode to get exact
23814 results.
23816 You can type @kbd{i} instead of a digit at the model prompt to fit
23817 the data exactly to a polynomial.  This just counts the number of
23818 columns of the data matrix to choose the degree of the polynomial
23819 automatically.
23821 Fitting data ``exactly'' to high-degree polynomials is not always
23822 a good idea, though.  High-degree polynomials have a tendency to
23823 wiggle uncontrollably in between the fitting data points.  Also,
23824 if the exact-fit polynomial is going to be used to interpolate or
23825 extrapolate the data, it is numerically better to use the @kbd{a p}
23826 command described below.  @xref{Interpolation}.
23828 @tex
23829 \bigskip
23830 @end tex
23832 Another generalization of the linear model is to assume the
23833 @cite{y} values are a sum of linear contributions from several
23834 @cite{x} values.  This is a @dfn{multilinear} fit, and it is also
23835 selected by the @kbd{1} digit key.  (Calc decides whether the fit
23836 is linear or multilinear by counting the rows in the data matrix.)
23838 Given the data matrix,
23840 @group
23841 @example
23842 [ [  1,   2,   3,    4,   5  ]
23843   [  7,   2,   3,    5,   2  ]
23844   [ 14.5, 15, 18.5, 22.5, 24 ] ]
23845 @end example
23846 @end group
23848 @noindent
23849 the command @kbd{a F 1 RET} will call the first row @cite{x} and the
23850 second row @cite{y}, and will fit the values in the third row to the
23851 model @cite{a + b x + c y}.
23853 @example
23854 8. + 3. x + 0.5 y
23855 @end example
23857 Calc can do multilinear fits with any number of independent variables
23858 (i.e., with any number of data rows).
23860 @tex
23861 \bigskip
23862 @end tex
23864 Yet another variation is @dfn{homogeneous} linear models, in which
23865 the constant term is known to be zero.  In the linear case, this
23866 means the model formula is simply @cite{a x}; in the multilinear
23867 case, the model might be @cite{a x + b y + c z}; and in the polynomial
23868 case, the model could be @cite{a x + b x^2 + c x^3}.  You can get
23869 a homogeneous linear or multilinear model by pressing the letter
23870 @kbd{h} followed by a regular model key, like @kbd{1} or @kbd{2}.
23872 It is certainly possible to have other constrained linear models,
23873 like @cite{2.3 + a x} or @cite{a - 4 x}.  While there is no single
23874 key to select models like these, a later section shows how to enter
23875 any desired model by hand.  In the first case, for example, you
23876 would enter @kbd{a F ' 2.3 + a x}.
23878 Another class of models that will work but must be entered by hand
23879 are multinomial fits, e.g., @cite{a + b x + c y + d x^2 + e y^2 + f x y}.
23881 @node Error Estimates for Fits, Standard Nonlinear Models, Polynomial and Multilinear Fits, Curve Fitting
23882 @subsection Error Estimates for Fits
23884 @noindent
23885 @kindex H a F
23886 @tindex efit
23887 With the Hyperbolic flag, @kbd{H a F} [@code{efit}] performs the same
23888 fitting operation as @kbd{a F}, but reports the coefficients as error
23889 forms instead of plain numbers.  Fitting our two data matrices (first
23890 with 13, then with 14) to a line with @kbd{H a F} gives the results,
23892 @example
23893 3. + 2. x
23894 2.6 +/- 0.382970843103 + 2.2 +/- 0.115470053838 x
23895 @end example
23897 In the first case the estimated errors are zero because the linear
23898 fit is perfect.  In the second case, the errors are nonzero but
23899 moderately small, because the data are still very close to linear.
23901 It is also possible for the @emph{input} to a fitting operation to
23902 contain error forms.  The data values must either all include errors
23903 or all be plain numbers.  Error forms can go anywhere but generally
23904 go on the numbers in the last row of the data matrix.  If the last
23905 row contains error forms
23906 `@i{y_i}@w{ @t{+/-} }@c{$\sigma_i$}
23907 @i{sigma_i}', then the @c{$\chi^2$}
23908 @cite{chi^2}
23909 statistic is now,
23911 @ifinfo
23912 @example
23913 chi^2 = sum(((y_i - (a + b x_i)) / sigma_i)^2, i, 1, N)
23914 @end example
23915 @end ifinfo
23916 @tex
23917 \turnoffactive
23918 \beforedisplay
23919 $$ \chi^2 = \sum_{i=1}^N \left(y_i - (a + b x_i) \over \sigma_i\right)^2 $$
23920 \afterdisplay
23921 @end tex
23923 @noindent
23924 so that data points with larger error estimates contribute less to
23925 the fitting operation.
23927 If there are error forms on other rows of the data matrix, all the
23928 errors for a given data point are combined; the square root of the
23929 sum of the squares of the errors forms the @c{$\sigma_i$}
23930 @cite{sigma_i} used for
23931 the data point.
23933 Both @kbd{a F} and @kbd{H a F} can accept error forms in the input
23934 matrix, although if you are concerned about error analysis you will
23935 probably use @kbd{H a F} so that the output also contains error
23936 estimates.
23938 If the input contains error forms but all the @c{$\sigma_i$}
23939 @cite{sigma_i} values are
23940 the same, it is easy to see that the resulting fitted model will be
23941 the same as if the input did not have error forms at all (@c{$\chi^2$}
23942 @cite{chi^2}
23943 is simply scaled uniformly by @c{$1 / \sigma^2$}
23944 @cite{1 / sigma^2}, which doesn't affect
23945 where it has a minimum).  But there @emph{will} be a difference
23946 in the estimated errors of the coefficients reported by @kbd{H a F}.
23948 Consult any text on statistical modelling of data for a discussion
23949 of where these error estimates come from and how they should be
23950 interpreted.
23952 @tex
23953 \bigskip
23954 @end tex
23956 @kindex I a F
23957 @tindex xfit
23958 With the Inverse flag, @kbd{I a F} [@code{xfit}] produces even more
23959 information.  The result is a vector of six items:
23961 @enumerate
23962 @item
23963 The model formula with error forms for its coefficients or
23964 parameters.  This is the result that @kbd{H a F} would have
23965 produced.
23967 @item
23968 A vector of ``raw'' parameter values for the model.  These are the
23969 polynomial coefficients or other parameters as plain numbers, in the
23970 same order as the parameters appeared in the final prompt of the
23971 @kbd{I a F} command.  For polynomials of degree @cite{d}, this vector
23972 will have length @cite{M = d+1} with the constant term first.
23974 @item
23975 The covariance matrix @cite{C} computed from the fit.  This is
23976 an @i{M}x@i{M} symmetric matrix; the diagonal elements
23977 @c{$C_{jj}$}
23978 @cite{C_j_j} are the variances @c{$\sigma_j^2$}
23979 @cite{sigma_j^2} of the parameters.
23980 The other elements are covariances @c{$\sigma_{ij}^2$}
23981 @cite{sigma_i_j^2} that describe the
23982 correlation between pairs of parameters.  (A related set of
23983 numbers, the @dfn{linear correlation coefficients} @c{$r_{ij}$}
23984 @cite{r_i_j},
23985 are defined as @c{$\sigma_{ij}^2 / \sigma_i \, \sigma_j$}
23986 @cite{sigma_i_j^2 / sigma_i sigma_j}.)
23988 @item
23989 A vector of @cite{M} ``parameter filter'' functions whose
23990 meanings are described below.  If no filters are necessary this
23991 will instead be an empty vector; this is always the case for the
23992 polynomial and multilinear fits described so far.
23994 @item
23995 The value of @c{$\chi^2$}
23996 @cite{chi^2} for the fit, calculated by the formulas
23997 shown above.  This gives a measure of the quality of the fit;
23998 statisticians consider @c{$\chi^2 \approx N - M$}
23999 @cite{chi^2 = N - M} to indicate a moderately good fit
24000 (where again @cite{N} is the number of data points and @cite{M}
24001 is the number of parameters).
24003 @item
24004 A measure of goodness of fit expressed as a probability @cite{Q}.
24005 This is computed from the @code{utpc} probability distribution
24006 function using @c{$\chi^2$}
24007 @cite{chi^2} with @cite{N - M} degrees of freedom.  A
24008 value of 0.5 implies a good fit; some texts recommend that often
24009 @cite{Q = 0.1} or even 0.001 can signify an acceptable fit.  In
24010 particular, @c{$\chi^2$}
24011 @cite{chi^2} statistics assume the errors in your inputs
24012 follow a normal (Gaussian) distribution; if they don't, you may
24013 have to accept smaller values of @cite{Q}.
24015 The @cite{Q} value is computed only if the input included error
24016 estimates.  Otherwise, Calc will report the symbol @code{nan}
24017 for @cite{Q}.  The reason is that in this case the @c{$\chi^2$}
24018 @cite{chi^2}
24019 value has effectively been used to estimate the original errors
24020 in the input, and thus there is no redundant information left
24021 over to use for a confidence test.
24022 @end enumerate
24024 @node Standard Nonlinear Models, Curve Fitting Details, Error Estimates for Fits, Curve Fitting
24025 @subsection Standard Nonlinear Models
24027 @noindent
24028 The @kbd{a F} command also accepts other kinds of models besides
24029 lines and polynomials.  Some common models have quick single-key
24030 abbreviations; others must be entered by hand as algebraic formulas.
24032 Here is a complete list of the standard models recognized by @kbd{a F}:
24034 @table @kbd
24035 @item 1
24036 Linear or multilinear.  @i{a + b x + c y + d z}.
24037 @item 2-9
24038 Polynomials.  @i{a + b x + c x^2 + d x^3}.
24039 @item e
24040 Exponential.  @i{a} @t{exp}@i{(b x)} @t{exp}@i{(c y)}.
24041 @item E
24042 Base-10 exponential.  @i{a} @t{10^}@i{(b x)} @t{10^}@i{(c y)}.
24043 @item x
24044 Exponential (alternate notation).  @t{exp}@i{(a + b x + c y)}.
24045 @item X
24046 Base-10 exponential (alternate).  @t{10^}@i{(a + b x + c y)}.
24047 @item l
24048 Logarithmic.  @i{a + b} @t{ln}@i{(x) + c} @t{ln}@i{(y)}.
24049 @item L
24050 Base-10 logarithmic.  @i{a + b} @t{log10}@i{(x) + c} @t{log10}@i{(y)}.
24051 @item ^
24052 General exponential.  @i{a b^x c^y}.
24053 @item p
24054 Power law.  @i{a x^b y^c}.
24055 @item q
24056 Quadratic.  @i{a + b (x-c)^2 + d (x-e)^2}.
24057 @item g
24058 Gaussian.  @c{${a \over b \sqrt{2 \pi}} \exp\left( -{1 \over 2} \left( x - c \over b \right)^2 \right)$}
24059 @i{(a / b sqrt(2 pi)) exp(-0.5*((x-c)/b)^2)}.
24060 @end table
24062 All of these models are used in the usual way; just press the appropriate
24063 letter at the model prompt, and choose variable names if you wish.  The
24064 result will be a formula as shown in the above table, with the best-fit
24065 values of the parameters substituted.  (You may find it easier to read
24066 the parameter values from the vector that is placed in the trail.)
24068 All models except Gaussian and polynomials can generalize as shown to any
24069 number of independent variables.  Also, all the built-in models have an
24070 additive or multiplicative parameter shown as @cite{a} in the above table
24071 which can be replaced by zero or one, as appropriate, by typing @kbd{h}
24072 before the model key.
24074 Note that many of these models are essentially equivalent, but express
24075 the parameters slightly differently.  For example, @cite{a b^x} and
24076 the other two exponential models are all algebraic rearrangements of
24077 each other.  Also, the ``quadratic'' model is just a degree-2 polynomial
24078 with the parameters expressed differently.  Use whichever form best
24079 matches the problem.
24081 The HP-28/48 calculators support four different models for curve
24082 fitting, called @code{LIN}, @code{LOG}, @code{EXP}, and @code{PWR}.
24083 These correspond to Calc models @samp{a + b x}, @samp{a + b ln(x)},
24084 @samp{a exp(b x)}, and @samp{a x^b}, respectively.  In each case,
24085 @cite{a} is what the HP-48 identifies as the ``intercept,'' and
24086 @cite{b} is what it calls the ``slope.''
24088 @tex
24089 \bigskip
24090 @end tex
24092 If the model you want doesn't appear on this list, press @kbd{'}
24093 (the apostrophe key) at the model prompt to enter any algebraic
24094 formula, such as @kbd{m x - b}, as the model.  (Not all models
24095 will work, though---see the next section for details.)
24097 The model can also be an equation like @cite{y = m x + b}.
24098 In this case, Calc thinks of all the rows of the data matrix on
24099 equal terms; this model effectively has two parameters
24100 (@cite{m} and @cite{b}) and two independent variables (@cite{x}
24101 and @cite{y}), with no ``dependent'' variables.  Model equations
24102 do not need to take this @cite{y =} form.  For example, the
24103 implicit line equation @cite{a x + b y = 1} works fine as a
24104 model.
24106 When you enter a model, Calc makes an alphabetical list of all
24107 the variables that appear in the model.  These are used for the
24108 default parameters, independent variables, and dependent variable
24109 (in that order).  If you enter a plain formula (not an equation),
24110 Calc assumes the dependent variable does not appear in the formula
24111 and thus does not need a name.
24113 For example, if the model formula has the variables @cite{a,mu,sigma,t,x},
24114 and the data matrix has three rows (meaning two independent variables),
24115 Calc will use @cite{a,mu,sigma} as the default parameters, and the
24116 data rows will be named @cite{t} and @cite{x}, respectively.  If you
24117 enter an equation instead of a plain formula, Calc will use @cite{a,mu}
24118 as the parameters, and @cite{sigma,t,x} as the three independent
24119 variables.
24121 You can, of course, override these choices by entering something
24122 different at the prompt.  If you leave some variables out of the list,
24123 those variables must have stored values and those stored values will
24124 be used as constants in the model.  (Stored values for the parameters
24125 and independent variables are ignored by the @kbd{a F} command.)
24126 If you list only independent variables, all the remaining variables
24127 in the model formula will become parameters.
24129 If there are @kbd{$} signs in the model you type, they will stand
24130 for parameters and all other variables (in alphabetical order)
24131 will be independent.  Use @kbd{$} for one parameter, @kbd{$$} for
24132 another, and so on.  Thus @kbd{$ x + $$} is another way to describe
24133 a linear model.
24135 If you type a @kbd{$} instead of @kbd{'} at the model prompt itself,
24136 Calc will take the model formula from the stack.  (The data must then
24137 appear at the second stack level.)  The same conventions are used to
24138 choose which variables in the formula are independent by default and
24139 which are parameters.
24141 Models taken from the stack can also be expressed as vectors of
24142 two or three elements, @cite{[@var{model}, @var{vars}]} or
24143 @cite{[@var{model}, @var{vars}, @var{params}]}.  Each of @var{vars}
24144 and @var{params} may be either a variable or a vector of variables.
24145 (If @var{params} is omitted, all variables in @var{model} except
24146 those listed as @var{vars} are parameters.)@refill
24148 When you enter a model manually with @kbd{'}, Calc puts a 3-vector
24149 describing the model in the trail so you can get it back if you wish.
24151 @tex
24152 \bigskip
24153 @end tex
24155 @vindex Model1
24156 @vindex Model2
24157 Finally, you can store a model in one of the Calc variables
24158 @code{Model1} or @code{Model2}, then use this model by typing
24159 @kbd{a F u} or @kbd{a F U} (respectively).  The value stored in
24160 the variable can be any of the formats that @kbd{a F $} would
24161 accept for a model on the stack.
24163 @tex
24164 \bigskip
24165 @end tex
24167 Calc uses the principal values of inverse functions like @code{ln}
24168 and @code{arcsin} when doing fits.  For example, when you enter
24169 the model @samp{y = sin(a t + b)} Calc actually uses the easier
24170 form @samp{arcsin(y) = a t + b}.  The @code{arcsin} function always
24171 returns results in the range from @i{-90} to 90 degrees (or the
24172 equivalent range in radians).  Suppose you had data that you
24173 believed to represent roughly three oscillations of a sine wave,
24174 so that the argument of the sine might go from zero to @c{$3\times360$}
24175 @i{3*360} degrees.
24176 The above model would appear to be a good way to determine the
24177 true frequency and phase of the sine wave, but in practice it
24178 would fail utterly.  The righthand side of the actual model
24179 @samp{arcsin(y) = a t + b} will grow smoothly with @cite{t}, but
24180 the lefthand side will bounce back and forth between @i{-90} and 90.
24181 No values of @cite{a} and @cite{b} can make the two sides match,
24182 even approximately.
24184 There is no good solution to this problem at present.  You could
24185 restrict your data to small enough ranges so that the above problem
24186 doesn't occur (i.e., not straddling any peaks in the sine wave).
24187 Or, in this case, you could use a totally different method such as
24188 Fourier analysis, which is beyond the scope of the @kbd{a F} command.
24189 (Unfortunately, Calc does not currently have any facilities for
24190 taking Fourier and related transforms.)
24192 @node Curve Fitting Details, Interpolation, Standard Nonlinear Models, Curve Fitting
24193 @subsection Curve Fitting Details
24195 @noindent
24196 Calc's internal least-squares fitter can only handle multilinear
24197 models.  More precisely, it can handle any model of the form
24198 @cite{a f(x,y,z) + b g(x,y,z) + c h(x,y,z)}, where @cite{a,b,c}
24199 are the parameters and @cite{x,y,z} are the independent variables
24200 (of course there can be any number of each, not just three).
24202 In a simple multilinear or polynomial fit, it is easy to see how
24203 to convert the model into this form.  For example, if the model
24204 is @cite{a + b x + c x^2}, then @cite{f(x) = 1}, @cite{g(x) = x},
24205 and @cite{h(x) = x^2} are suitable functions.
24207 For other models, Calc uses a variety of algebraic manipulations
24208 to try to put the problem into the form
24210 @smallexample
24211 Y(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)
24212 @end smallexample
24214 @noindent
24215 where @cite{Y,A,B,C,F,G,H} are arbitrary functions.  It computes
24216 @cite{Y}, @cite{F}, @cite{G}, and @cite{H} for all the data points,
24217 does a standard linear fit to find the values of @cite{A}, @cite{B},
24218 and @cite{C}, then uses the equation solver to solve for @cite{a,b,c}
24219 in terms of @cite{A,B,C}.
24221 A remarkable number of models can be cast into this general form.
24222 We'll look at two examples here to see how it works.  The power-law
24223 model @cite{y = a x^b} with two independent variables and two parameters
24224 can be rewritten as follows:
24226 @example
24227 y = a x^b
24228 y = a exp(b ln(x))
24229 y = exp(ln(a) + b ln(x))
24230 ln(y) = ln(a) + b ln(x)
24231 @end example
24233 @noindent
24234 which matches the desired form with @c{$Y = \ln(y)$}
24235 @cite{Y = ln(y)}, @c{$A = \ln(a)$}
24236 @cite{A = ln(a)},
24237 @cite{F = 1}, @cite{B = b}, and @c{$G = \ln(x)$}
24238 @cite{G = ln(x)}.  Calc thus computes
24239 the logarithms of your @cite{y} and @cite{x} values, does a linear fit
24240 for @cite{A} and @cite{B}, then solves to get @c{$a = \exp(A)$}
24241 @cite{a = exp(A)} and
24242 @cite{b = B}.
24244 Another interesting example is the ``quadratic'' model, which can
24245 be handled by expanding according to the distributive law.
24247 @example
24248 y = a + b*(x - c)^2
24249 y = a + b c^2 - 2 b c x + b x^2
24250 @end example
24252 @noindent
24253 which matches with @cite{Y = y}, @cite{A = a + b c^2}, @cite{F = 1},
24254 @cite{B = -2 b c}, @cite{G = x} (the @i{-2} factor could just as easily
24255 have been put into @cite{G} instead of @cite{B}), @cite{C = b}, and
24256 @cite{H = x^2}.
24258 The Gaussian model looks quite complicated, but a closer examination
24259 shows that it's actually similar to the quadratic model but with an
24260 exponential that can be brought to the top and moved into @cite{Y}.
24262 An example of a model that cannot be put into general linear
24263 form is a Gaussian with a constant background added on, i.e.,
24264 @cite{d} + the regular Gaussian formula.  If you have a model like
24265 this, your best bet is to replace enough of your parameters with
24266 constants to make the model linearizable, then adjust the constants
24267 manually by doing a series of fits.  You can compare the fits by
24268 graphing them, by examining the goodness-of-fit measures returned by
24269 @kbd{I a F}, or by some other method suitable to your application.
24270 Note that some models can be linearized in several ways.  The
24271 Gaussian-plus-@i{d} model can be linearized by setting @cite{d}
24272 (the background) to a constant, or by setting @cite{b} (the standard
24273 deviation) and @cite{c} (the mean) to constants.
24275 To fit a model with constants substituted for some parameters, just
24276 store suitable values in those parameter variables, then omit them
24277 from the list of parameters when you answer the variables prompt.
24279 @tex
24280 \bigskip
24281 @end tex
24283 A last desperate step would be to use the general-purpose
24284 @code{minimize} function rather than @code{fit}.  After all, both
24285 functions solve the problem of minimizing an expression (the @c{$\chi^2$}
24286 @cite{chi^2}
24287 sum) by adjusting certain parameters in the expression.  The @kbd{a F}
24288 command is able to use a vastly more efficient algorithm due to its
24289 special knowledge about linear chi-square sums, but the @kbd{a N}
24290 command can do the same thing by brute force.
24292 A compromise would be to pick out a few parameters without which the
24293 fit is linearizable, and use @code{minimize} on a call to @code{fit}
24294 which efficiently takes care of the rest of the parameters.  The thing
24295 to be minimized would be the value of @c{$\chi^2$}
24296 @cite{chi^2} returned as
24297 the fifth result of the @code{xfit} function:
24299 @smallexample
24300 minimize(xfit(gaus(a,b,c,d,x), x, [a,b,c], data)_5, d, guess)
24301 @end smallexample
24303 @noindent
24304 where @code{gaus} represents the Gaussian model with background,
24305 @code{data} represents the data matrix, and @code{guess} represents
24306 the initial guess for @cite{d} that @code{minimize} requires.
24307 This operation will only be, shall we say, extraordinarily slow
24308 rather than astronomically slow (as would be the case if @code{minimize}
24309 were used by itself to solve the problem).
24311 @tex
24312 \bigskip
24313 @end tex
24315 The @kbd{I a F} [@code{xfit}] command is somewhat trickier when
24316 nonlinear models are used.  The second item in the result is the
24317 vector of ``raw'' parameters @cite{A}, @cite{B}, @cite{C}.  The
24318 covariance matrix is written in terms of those raw parameters.
24319 The fifth item is a vector of @dfn{filter} expressions.  This
24320 is the empty vector @samp{[]} if the raw parameters were the same
24321 as the requested parameters, i.e., if @cite{A = a}, @cite{B = b},
24322 and so on (which is always true if the model is already linear
24323 in the parameters as written, e.g., for polynomial fits).  If the
24324 parameters had to be rearranged, the fifth item is instead a vector
24325 of one formula per parameter in the original model.  The raw
24326 parameters are expressed in these ``filter'' formulas as
24327 @samp{fitdummy(1)} for @cite{A}, @samp{fitdummy(2)} for @cite{B},
24328 and so on.
24330 When Calc needs to modify the model to return the result, it replaces
24331 @samp{fitdummy(1)} in all the filters with the first item in the raw
24332 parameters list, and so on for the other raw parameters, then
24333 evaluates the resulting filter formulas to get the actual parameter
24334 values to be substituted into the original model.  In the case of
24335 @kbd{H a F} and @kbd{I a F} where the parameters must be error forms,
24336 Calc uses the square roots of the diagonal entries of the covariance
24337 matrix as error values for the raw parameters, then lets Calc's
24338 standard error-form arithmetic take it from there.
24340 If you use @kbd{I a F} with a nonlinear model, be sure to remember
24341 that the covariance matrix is in terms of the raw parameters,
24342 @emph{not} the actual requested parameters.  It's up to you to
24343 figure out how to interpret the covariances in the presence of
24344 nontrivial filter functions.
24346 Things are also complicated when the input contains error forms.
24347 Suppose there are three independent and dependent variables, @cite{x},
24348 @cite{y}, and @cite{z}, one or more of which are error forms in the
24349 data.  Calc combines all the error values by taking the square root
24350 of the sum of the squares of the errors.  It then changes @cite{x}
24351 and @cite{y} to be plain numbers, and makes @cite{z} into an error
24352 form with this combined error.  The @cite{Y(x,y,z)} part of the
24353 linearized model is evaluated, and the result should be an error
24354 form.  The error part of that result is used for @c{$\sigma_i$}
24355 @cite{sigma_i} for
24356 the data point.  If for some reason @cite{Y(x,y,z)} does not return
24357 an error form, the combined error from @cite{z} is used directly
24358 for @c{$\sigma_i$}
24359 @cite{sigma_i}.  Finally, @cite{z} is also stripped of its error
24360 for use in computing @cite{F(x,y,z)}, @cite{G(x,y,z)} and so on;
24361 the righthand side of the linearized model is computed in regular
24362 arithmetic with no error forms.
24364 (While these rules may seem complicated, they are designed to do
24365 the most reasonable thing in the typical case that @cite{Y(x,y,z)}
24366 depends only on the dependent variable @cite{z}, and in fact is
24367 often simply equal to @cite{z}.  For common cases like polynomials
24368 and multilinear models, the combined error is simply used as the
24369 @c{$\sigma$}
24370 @cite{sigma} for the data point with no further ado.)
24372 @tex
24373 \bigskip
24374 @end tex
24376 @vindex FitRules
24377 It may be the case that the model you wish to use is linearizable,
24378 but Calc's built-in rules are unable to figure it out.  Calc uses
24379 its algebraic rewrite mechanism to linearize a model.  The rewrite
24380 rules are kept in the variable @code{FitRules}.  You can edit this
24381 variable using the @kbd{s e FitRules} command; in fact, there is
24382 a special @kbd{s F} command just for editing @code{FitRules}.
24383 @xref{Operations on Variables}.
24385 @xref{Rewrite Rules}, for a discussion of rewrite rules.
24387 @c @starindex
24388 @tindex fitvar
24389 @c @starindex
24390 @c @mindex @idots
24391 @tindex fitparam
24392 @c @starindex
24393 @c @mindex @null
24394 @tindex fitmodel
24395 @c @starindex
24396 @c @mindex @null
24397 @tindex fitsystem
24398 @c @starindex
24399 @c @mindex @null
24400 @tindex fitdummy
24401 Calc uses @code{FitRules} as follows.  First, it converts the model
24402 to an equation if necessary and encloses the model equation in a
24403 call to the function @code{fitmodel} (which is not actually a defined
24404 function in Calc; it is only used as a placeholder by the rewrite rules).
24405 Parameter variables are renamed to function calls @samp{fitparam(1)},
24406 @samp{fitparam(2)}, and so on, and independent variables are renamed
24407 to @samp{fitvar(1)}, @samp{fitvar(2)}, etc.  The dependent variable
24408 is the highest-numbered @code{fitvar}.  For example, the power law
24409 model @cite{a x^b} is converted to @cite{y = a x^b}, then to
24411 @group
24412 @smallexample
24413 fitmodel(fitvar(2) = fitparam(1) fitvar(1)^fitparam(2))
24414 @end smallexample
24415 @end group
24417 Calc then applies the rewrites as if by @samp{C-u 0 a r FitRules}.
24418 (The zero prefix means that rewriting should continue until no further
24419 changes are possible.)
24421 When rewriting is complete, the @code{fitmodel} call should have
24422 been replaced by a @code{fitsystem} call that looks like this:
24424 @example
24425 fitsystem(@var{Y}, @var{FGH}, @var{abc})
24426 @end example
24428 @noindent
24429 where @var{Y} is a formula that describes the function @cite{Y(x,y,z)},
24430 @var{FGH} is the vector of formulas @cite{[F(x,y,z), G(x,y,z), H(x,y,z)]},
24431 and @var{abc} is the vector of parameter filters which refer to the
24432 raw parameters as @samp{fitdummy(1)} for @cite{A}, @samp{fitdummy(2)}
24433 for @cite{B}, etc.  While the number of raw parameters (the length of
24434 the @var{FGH} vector) is usually the same as the number of original
24435 parameters (the length of the @var{abc} vector), this is not required.
24437 The power law model eventually boils down to
24439 @group
24440 @smallexample
24441 fitsystem(ln(fitvar(2)),
24442           [1, ln(fitvar(1))],
24443           [exp(fitdummy(1)), fitdummy(2)])
24444 @end smallexample
24445 @end group
24447 The actual implementation of @code{FitRules} is complicated; it
24448 proceeds in four phases.  First, common rearrangements are done
24449 to try to bring linear terms together and to isolate functions like
24450 @code{exp} and @code{ln} either all the way ``out'' (so that they
24451 can be put into @var{Y}) or all the way ``in'' (so that they can
24452 be put into @var{abc} or @var{FGH}).  In particular, all
24453 non-constant powers are converted to logs-and-exponentials form,
24454 and the distributive law is used to expand products of sums.
24455 Quotients are rewritten to use the @samp{fitinv} function, where
24456 @samp{fitinv(x)} represents @cite{1/x} while the @code{FitRules}
24457 are operating.  (The use of @code{fitinv} makes recognition of
24458 linear-looking forms easier.)  If you modify @code{FitRules}, you
24459 will probably only need to modify the rules for this phase.
24461 Phase two, whose rules can actually also apply during phases one
24462 and three, first rewrites @code{fitmodel} to a two-argument
24463 form @samp{fitmodel(@var{Y}, @var{model})}, where @var{Y} is
24464 initially zero and @var{model} has been changed from @cite{a=b}
24465 to @cite{a-b} form.  It then tries to peel off invertible functions
24466 from the outside of @var{model} and put them into @var{Y} instead,
24467 calling the equation solver to invert the functions.  Finally, when
24468 this is no longer possible, the @code{fitmodel} is changed to a
24469 four-argument @code{fitsystem}, where the fourth argument is
24470 @var{model} and the @var{FGH} and @var{abc} vectors are initially
24471 empty.  (The last vector is really @var{ABC}, corresponding to
24472 raw parameters, for now.)
24474 Phase three converts a sum of items in the @var{model} to a sum
24475 of @samp{fitpart(@var{a}, @var{b}, @var{c})} terms which represent
24476 terms @samp{@var{a}*@var{b}*@var{c}} of the sum, where @var{a}
24477 is all factors that do not involve any variables, @var{b} is all
24478 factors that involve only parameters, and @var{c} is the factors
24479 that involve only independent variables.  (If this decomposition
24480 is not possible, the rule set will not complete and Calc will
24481 complain that the model is too complex.)  Then @code{fitpart}s
24482 with equal @var{b} or @var{c} components are merged back together
24483 using the distributive law in order to minimize the number of
24484 raw parameters needed.
24486 Phase four moves the @code{fitpart} terms into the @var{FGH} and
24487 @var{ABC} vectors.  Also, some of the algebraic expansions that
24488 were done in phase 1 are undone now to make the formulas more
24489 computationally efficient.  Finally, it calls the solver one more
24490 time to convert the @var{ABC} vector to an @var{abc} vector, and
24491 removes the fourth @var{model} argument (which by now will be zero)
24492 to obtain the three-argument @code{fitsystem} that the linear
24493 least-squares solver wants to see.
24495 @c @starindex
24496 @c @mindex hasfit@idots
24497 @tindex hasfitparams
24498 @c @starindex
24499 @c @mindex @null
24500 @tindex hasfitvars
24501 Two functions which are useful in connection with @code{FitRules}
24502 are @samp{hasfitparams(x)} and @samp{hasfitvars(x)}, which check
24503 whether @cite{x} refers to any parameters or independent variables,
24504 respectively.  Specifically, these functions return ``true'' if the
24505 argument contains any @code{fitparam} (or @code{fitvar}) function
24506 calls, and ``false'' otherwise.  (Recall that ``true'' means a
24507 nonzero number, and ``false'' means zero.  The actual nonzero number
24508 returned is the largest @var{n} from all the @samp{fitparam(@var{n})}s
24509 or @samp{fitvar(@var{n})}s, respectively, that appear in the formula.)
24511 @tex
24512 \bigskip
24513 @end tex
24515 The @code{fit} function in algebraic notation normally takes four
24516 arguments, @samp{fit(@var{model}, @var{vars}, @var{params}, @var{data})},
24517 where @var{model} is the model formula as it would be typed after
24518 @kbd{a F '}, @var{vars} is the independent variable or a vector of
24519 independent variables, @var{params} likewise gives the parameter(s),
24520 and @var{data} is the data matrix.  Note that the length of @var{vars}
24521 must be equal to the number of rows in @var{data} if @var{model} is
24522 an equation, or one less than the number of rows if @var{model} is
24523 a plain formula.  (Actually, a name for the dependent variable is
24524 allowed but will be ignored in the plain-formula case.)
24526 If @var{params} is omitted, the parameters are all variables in
24527 @var{model} except those that appear in @var{vars}.  If @var{vars}
24528 is also omitted, Calc sorts all the variables that appear in
24529 @var{model} alphabetically and uses the higher ones for @var{vars}
24530 and the lower ones for @var{params}.
24532 Alternatively, @samp{fit(@var{modelvec}, @var{data})} is allowed
24533 where @var{modelvec} is a 2- or 3-vector describing the model
24534 and variables, as discussed previously.
24536 If Calc is unable to do the fit, the @code{fit} function is left
24537 in symbolic form, ordinarily with an explanatory message.  The
24538 message will be ``Model expression is too complex'' if the
24539 linearizer was unable to put the model into the required form.
24541 The @code{efit} (corresponding to @kbd{H a F}) and @code{xfit}
24542 (for @kbd{I a F}) functions are completely analogous.
24544 @node Interpolation, ,  Curve Fitting Details, Curve Fitting
24545 @subsection Polynomial Interpolation
24547 @kindex a p
24548 @pindex calc-poly-interp
24549 @tindex polint
24550 The @kbd{a p} (@code{calc-poly-interp}) [@code{polint}] command does
24551 a polynomial interpolation at a particular @cite{x} value.  It takes
24552 two arguments from the stack:  A data matrix of the sort used by
24553 @kbd{a F}, and a single number which represents the desired @cite{x}
24554 value.  Calc effectively does an exact polynomial fit as if by @kbd{a F i},
24555 then substitutes the @cite{x} value into the result in order to get an
24556 approximate @cite{y} value based on the fit.  (Calc does not actually
24557 use @kbd{a F i}, however; it uses a direct method which is both more
24558 efficient and more numerically stable.)
24560 The result of @kbd{a p} is actually a vector of two values:  The @cite{y}
24561 value approximation, and an error measure @cite{dy} that reflects Calc's
24562 estimation of the probable error of the approximation at that value of
24563 @cite{x}.  If the input @cite{x} is equal to any of the @cite{x} values
24564 in the data matrix, the output @cite{y} will be the corresponding @cite{y}
24565 value from the matrix, and the output @cite{dy} will be exactly zero.
24567 A prefix argument of 2 causes @kbd{a p} to take separate x- and
24568 y-vectors from the stack instead of one data matrix.
24570 If @cite{x} is a vector of numbers, @kbd{a p} will return a matrix of
24571 interpolated results for each of those @cite{x} values.  (The matrix will
24572 have two columns, the @cite{y} values and the @cite{dy} values.)
24573 If @cite{x} is a formula instead of a number, the @code{polint} function
24574 remains in symbolic form; use the @kbd{a "} command to expand it out to
24575 a formula that describes the fit in symbolic terms.
24577 In all cases, the @kbd{a p} command leaves the data vectors or matrix
24578 on the stack.  Only the @cite{x} value is replaced by the result.
24580 @kindex H a p
24581 @tindex ratint
24582 The @kbd{H a p} [@code{ratint}] command does a rational function
24583 interpolation.  It is used exactly like @kbd{a p}, except that it
24584 uses as its model the quotient of two polynomials.  If there are
24585 @cite{N} data points, the numerator and denominator polynomials will
24586 each have degree @cite{N/2} (if @cite{N} is odd, the denominator will
24587 have degree one higher than the numerator).
24589 Rational approximations have the advantage that they can accurately
24590 describe functions that have poles (points at which the function's value
24591 goes to infinity, so that the denominator polynomial of the approximation
24592 goes to zero).  If @cite{x} corresponds to a pole of the fitted rational
24593 function, then the result will be a division by zero.  If Infinite mode
24594 is enabled, the result will be @samp{[uinf, uinf]}.
24596 There is no way to get the actual coefficients of the rational function
24597 used by @kbd{H a p}.  (The algorithm never generates these coefficients
24598 explicitly, and quotients of polynomials are beyond @w{@kbd{a F}}'s
24599 capabilities to fit.)
24601 @node Summations, Logical Operations, Curve Fitting, Algebra
24602 @section Summations
24604 @noindent
24605 @cindex Summation of a series
24606 @kindex a +
24607 @pindex calc-summation
24608 @tindex sum
24609 The @kbd{a +} (@code{calc-summation}) [@code{sum}] command computes
24610 the sum of a formula over a certain range of index values.  The formula
24611 is taken from the top of the stack; the command prompts for the
24612 name of the summation index variable, the lower limit of the
24613 sum (any formula), and the upper limit of the sum.  If you
24614 enter a blank line at any of these prompts, that prompt and
24615 any later ones are answered by reading additional elements from
24616 the stack.  Thus, @kbd{' k^2 RET ' k RET 1 RET 5 RET a + RET}
24617 produces the result 55.
24618 @tex
24619 \turnoffactive
24620 $$ \sum_{k=1}^5 k^2 = 55 $$
24621 @end tex
24623 The choice of index variable is arbitrary, but it's best not to
24624 use a variable with a stored value.  In particular, while
24625 @code{i} is often a favorite index variable, it should be avoided
24626 in Calc because @code{i} has the imaginary constant @cite{(0, 1)}
24627 as a value.  If you pressed @kbd{=} on a sum over @code{i}, it would
24628 be changed to a nonsensical sum over the ``variable'' @cite{(0, 1)}!
24629 If you really want to use @code{i} as an index variable, use
24630 @w{@kbd{s u i RET}} first to ``unstore'' this variable.
24631 (@xref{Storing Variables}.)
24633 A numeric prefix argument steps the index by that amount rather
24634 than by one.  Thus @kbd{' a_k RET C-u -2 a + k RET 10 RET 0 RET}
24635 yields @samp{a_10 + a_8 + a_6 + a_4 + a_2 + a_0}.  A prefix
24636 argument of plain @kbd{C-u} causes @kbd{a +} to prompt for the
24637 step value, in which case you can enter any formula or enter
24638 a blank line to take the step value from the stack.  With the
24639 @kbd{C-u} prefix, @kbd{a +} can take up to five arguments from
24640 the stack:  The formula, the variable, the lower limit, the
24641 upper limit, and (at the top of the stack), the step value.
24643 Calc knows how to do certain sums in closed form.  For example,
24644 @samp{sum(6 k^2, k, 1, n) = @w{2 n^3} + 3 n^2 + n}.  In particular,
24645 this is possible if the formula being summed is polynomial or
24646 exponential in the index variable.  Sums of logarithms are
24647 transformed into logarithms of products.  Sums of trigonometric
24648 and hyperbolic functions are transformed to sums of exponentials
24649 and then done in closed form.  Also, of course, sums in which the
24650 lower and upper limits are both numbers can always be evaluated
24651 just by grinding them out, although Calc will use closed forms
24652 whenever it can for the sake of efficiency.
24654 The notation for sums in algebraic formulas is
24655 @samp{sum(@var{expr}, @var{var}, @var{low}, @var{high}, @var{step})}.
24656 If @var{step} is omitted, it defaults to one.  If @var{high} is
24657 omitted, @var{low} is actually the upper limit and the lower limit
24658 is one.  If @var{low} is also omitted, the limits are @samp{-inf}
24659 and @samp{inf}, respectively.
24661 Infinite sums can sometimes be evaluated:  @samp{sum(.5^k, k, 1, inf)}
24662 returns @cite{1}.  This is done by evaluating the sum in closed
24663 form (to @samp{1. - 0.5^n} in this case), then evaluating this
24664 formula with @code{n} set to @code{inf}.  Calc's usual rules
24665 for ``infinite'' arithmetic can find the answer from there.  If
24666 infinite arithmetic yields a @samp{nan}, or if the sum cannot be
24667 solved in closed form, Calc leaves the @code{sum} function in
24668 symbolic form.  @xref{Infinities}.
24670 As a special feature, if the limits are infinite (or omitted, as
24671 described above) but the formula includes vectors subscripted by
24672 expressions that involve the iteration variable, Calc narrows
24673 the limits to include only the range of integers which result in
24674 legal subscripts for the vector.  For example, the sum
24675 @samp{sum(k [a,b,c,d,e,f,g]_(2k),k)} evaluates to @samp{b + 2 d + 3 f}.
24677 The limits of a sum do not need to be integers.  For example,
24678 @samp{sum(a_k, k, 0, 2 n, n)} produces @samp{a_0 + a_n + a_(2 n)}.
24679 Calc computes the number of iterations using the formula
24680 @samp{1 + (@var{high} - @var{low}) / @var{step}}, which must,
24681 after simplification as if by @kbd{a s}, evaluate to an integer.
24683 If the number of iterations according to the above formula does
24684 not come out to an integer, the sum is illegal and will be left
24685 in symbolic form.  However, closed forms are still supplied, and
24686 you are on your honor not to misuse the resulting formulas by
24687 substituting mismatched bounds into them.  For example,
24688 @samp{sum(k, k, 1, 10, 2)} is invalid, but Calc will go ahead and
24689 evaluate the closed form solution for the limits 1 and 10 to get
24690 the rather dubious answer, 29.25.
24692 If the lower limit is greater than the upper limit (assuming a
24693 positive step size), the result is generally zero.  However,
24694 Calc only guarantees a zero result when the upper limit is
24695 exactly one step less than the lower limit, i.e., if the number
24696 of iterations is @i{-1}.  Thus @samp{sum(f(k), k, n, n-1)} is zero
24697 but the sum from @samp{n} to @samp{n-2} may report a nonzero value
24698 if Calc used a closed form solution.
24700 Calc's logical predicates like @cite{a < b} return 1 for ``true''
24701 and 0 for ``false.''  @xref{Logical Operations}.  This can be
24702 used to advantage for building conditional sums.  For example,
24703 @samp{sum(prime(k)*k^2, k, 1, 20)} is the sum of the squares of all
24704 prime numbers from 1 to 20; the @code{prime} predicate returns 1 if
24705 its argument is prime and 0 otherwise.  You can read this expression
24706 as ``the sum of @cite{k^2}, where @cite{k} is prime.''  Indeed,
24707 @samp{sum(prime(k)*k^2, k)} would represent the sum of @emph{all} primes
24708 squared, since the limits default to plus and minus infinity, but
24709 there are no such sums that Calc's built-in rules can do in
24710 closed form.
24712 As another example, @samp{sum((k != k_0) * f(k), k, 1, n)} is the
24713 sum of @cite{f(k)} for all @cite{k} from 1 to @cite{n}, excluding
24714 one value @cite{k_0}.  Slightly more tricky is the summand
24715 @samp{(k != k_0) / (k - k_0)}, which is an attempt to describe
24716 the sum of all @cite{1/(k-k_0)} except at @cite{k = k_0}, where
24717 this would be a division by zero.  But at @cite{k = k_0}, this
24718 formula works out to the indeterminate form @cite{0 / 0}, which
24719 Calc will not assume is zero.  Better would be to use
24720 @samp{(k != k_0) ? 1/(k-k_0) : 0}; the @samp{? :} operator does
24721 an ``if-then-else'' test:  This expression says, ``if @c{$k \ne k_0$}
24722 @cite{k != k_0},
24723 then @cite{1/(k-k_0)}, else zero.''  Now the formula @cite{1/(k-k_0)}
24724 will not even be evaluated by Calc when @cite{k = k_0}.
24726 @cindex Alternating sums
24727 @kindex a -
24728 @pindex calc-alt-summation
24729 @tindex asum
24730 The @kbd{a -} (@code{calc-alt-summation}) [@code{asum}] command
24731 computes an alternating sum.  Successive terms of the sequence
24732 are given alternating signs, with the first term (corresponding
24733 to the lower index value) being positive.  Alternating sums
24734 are converted to normal sums with an extra term of the form
24735 @samp{(-1)^(k-@var{low})}.  This formula is adjusted appropriately
24736 if the step value is other than one.  For example, the Taylor
24737 series for the sine function is @samp{asum(x^k / k!, k, 1, inf, 2)}.
24738 (Calc cannot evaluate this infinite series, but it can approximate
24739 it if you replace @code{inf} with any particular odd number.)
24740 Calc converts this series to a regular sum with a step of one,
24741 namely @samp{sum((-1)^k x^(2k+1) / (2k+1)!, k, 0, inf)}.
24743 @cindex Product of a sequence
24744 @kindex a *
24745 @pindex calc-product
24746 @tindex prod
24747 The @kbd{a *} (@code{calc-product}) [@code{prod}] command is
24748 the analogous way to take a product of many terms.  Calc also knows
24749 some closed forms for products, such as @samp{prod(k, k, 1, n) = n!}.
24750 Conditional products can be written @samp{prod(k^prime(k), k, 1, n)}
24751 or @samp{prod(prime(k) ? k : 1, k, 1, n)}.
24753 @kindex a T
24754 @pindex calc-tabulate
24755 @tindex table
24756 The @kbd{a T} (@code{calc-tabulate}) [@code{table}] command
24757 evaluates a formula at a series of iterated index values, just
24758 like @code{sum} and @code{prod}, but its result is simply a
24759 vector of the results.  For example, @samp{table(a_i, i, 1, 7, 2)}
24760 produces @samp{[a_1, a_3, a_5, a_7]}.
24762 @node Logical Operations, Rewrite Rules, Summations, Algebra
24763 @section Logical Operations
24765 @noindent
24766 The following commands and algebraic functions return true/false values,
24767 where 1 represents ``true'' and 0 represents ``false.''  In cases where
24768 a truth value is required (such as for the condition part of a rewrite
24769 rule, or as the condition for a @w{@kbd{Z [ Z ]}} control structure), any
24770 nonzero value is accepted to mean ``true.''  (Specifically, anything
24771 for which @code{dnonzero} returns 1 is ``true,'' and anything for
24772 which @code{dnonzero} returns 0 or cannot decide is assumed ``false.''
24773 Note that this means that @w{@kbd{Z [ Z ]}} will execute the ``then''
24774 portion if its condition is provably true, but it will execute the
24775 ``else'' portion for any condition like @cite{a = b} that is not
24776 provably true, even if it might be true.  Algebraic functions that
24777 have conditions as arguments, like @code{? :} and @code{&&}, remain
24778 unevaluated if the condition is neither provably true nor provably
24779 false.  @xref{Declarations}.)
24781 @kindex a =
24782 @pindex calc-equal-to
24783 @tindex eq
24784 @tindex =
24785 @tindex ==
24786 The @kbd{a =} (@code{calc-equal-to}) command, or @samp{eq(a,b)} function
24787 (which can also be written @samp{a = b} or @samp{a == b} in an algebraic
24788 formula) is true if @cite{a} and @cite{b} are equal, either because they
24789 are identical expressions, or because they are numbers which are
24790 numerically equal.  (Thus the integer 1 is considered equal to the float
24791 1.0.)  If the equality of @cite{a} and @cite{b} cannot be determined,
24792 the comparison is left in symbolic form.  Note that as a command, this
24793 operation pops two values from the stack and pushes back either a 1 or
24794 a 0, or a formula @samp{a = b} if the values' equality cannot be determined.
24796 Many Calc commands use @samp{=} formulas to represent @dfn{equations}.
24797 For example, the @kbd{a S} (@code{calc-solve-for}) command rearranges
24798 an equation to solve for a given variable.  The @kbd{a M}
24799 (@code{calc-map-equation}) command can be used to apply any
24800 function to both sides of an equation; for example, @kbd{2 a M *}
24801 multiplies both sides of the equation by two.  Note that just
24802 @kbd{2 *} would not do the same thing; it would produce the formula
24803 @samp{2 (a = b)} which represents 2 if the equality is true or
24804 zero if not.
24806 The @code{eq} function with more than two arguments (e.g., @kbd{C-u 3 a =}
24807 or @samp{a = b = c}) tests if all of its arguments are equal.  In
24808 algebraic notation, the @samp{=} operator is unusual in that it is
24809 neither left- nor right-associative:  @samp{a = b = c} is not the
24810 same as @samp{(a = b) = c} or @samp{a = (b = c)} (which each compare
24811 one variable with the 1 or 0 that results from comparing two other
24812 variables).
24814 @kindex a #
24815 @pindex calc-not-equal-to
24816 @tindex neq
24817 @tindex !=
24818 The @kbd{a #} (@code{calc-not-equal-to}) command, or @samp{neq(a,b)} or
24819 @samp{a != b} function, is true if @cite{a} and @cite{b} are not equal.
24820 This also works with more than two arguments; @samp{a != b != c != d}
24821 tests that all four of @cite{a}, @cite{b}, @cite{c}, and @cite{d} are
24822 distinct numbers.
24824 @kindex a <
24825 @tindex lt
24826 @c @mindex @idots
24827 @kindex a >
24828 @c @mindex @null
24829 @kindex a [
24830 @c @mindex @null
24831 @kindex a ]
24832 @pindex calc-less-than
24833 @pindex calc-greater-than
24834 @pindex calc-less-equal
24835 @pindex calc-greater-equal
24836 @c @mindex @null
24837 @tindex gt
24838 @c @mindex @null
24839 @tindex leq
24840 @c @mindex @null
24841 @tindex geq
24842 @c @mindex @null
24843 @tindex <
24844 @c @mindex @null
24845 @tindex >
24846 @c @mindex @null
24847 @tindex <=
24848 @c @mindex @null
24849 @tindex >=
24850 The @kbd{a <} (@code{calc-less-than}) [@samp{lt(a,b)} or @samp{a < b}]
24851 operation is true if @cite{a} is less than @cite{b}.  Similar functions
24852 are @kbd{a >} (@code{calc-greater-than}) [@samp{gt(a,b)} or @samp{a > b}],
24853 @kbd{a [} (@code{calc-less-equal}) [@samp{leq(a,b)} or @samp{a <= b}], and
24854 @kbd{a ]} (@code{calc-greater-equal}) [@samp{geq(a,b)} or @samp{a >= b}].
24856 While the inequality functions like @code{lt} do not accept more
24857 than two arguments, the syntax @w{@samp{a <= b < c}} is translated to an
24858 equivalent expression involving intervals: @samp{b in [a .. c)}.
24859 (See the description of @code{in} below.)  All four combinations
24860 of @samp{<} and @samp{<=} are allowed, or any of the four combinations
24861 of @samp{>} and @samp{>=}.  Four-argument constructions like
24862 @samp{a < b < c < d}, and mixtures like @w{@samp{a < b = c}} that
24863 involve both equalities and inequalities, are not allowed.
24865 @kindex a .
24866 @pindex calc-remove-equal
24867 @tindex rmeq
24868 The @kbd{a .} (@code{calc-remove-equal}) [@code{rmeq}] command extracts
24869 the righthand side of the equation or inequality on the top of the
24870 stack.  It also works elementwise on vectors.  For example, if
24871 @samp{[x = 2.34, y = z / 2]} is on the stack, then @kbd{a .} produces
24872 @samp{[2.34, z / 2]}.  As a special case, if the righthand side is a
24873 variable and the lefthand side is a number (as in @samp{2.34 = x}), then
24874 Calc keeps the lefthand side instead.  Finally, this command works with
24875 assignments @samp{x := 2.34} as well as equations, always taking the
24876 the righthand side, and for @samp{=>} (evaluates-to) operators, always
24877 taking the lefthand side.
24879 @kindex a &
24880 @pindex calc-logical-and
24881 @tindex land
24882 @tindex &&
24883 The @kbd{a &} (@code{calc-logical-and}) [@samp{land(a,b)} or @samp{a && b}]
24884 function is true if both of its arguments are true, i.e., are
24885 non-zero numbers.  In this case, the result will be either @cite{a} or
24886 @cite{b}, chosen arbitrarily.  If either argument is zero, the result is
24887 zero.  Otherwise, the formula is left in symbolic form.
24889 @kindex a |
24890 @pindex calc-logical-or
24891 @tindex lor
24892 @tindex ||
24893 The @kbd{a |} (@code{calc-logical-or}) [@samp{lor(a,b)} or @samp{a || b}]
24894 function is true if either or both of its arguments are true (nonzero).
24895 The result is whichever argument was nonzero, choosing arbitrarily if both
24896 are nonzero.  If both @cite{a} and @cite{b} are zero, the result is
24897 zero.
24899 @kindex a !
24900 @pindex calc-logical-not
24901 @tindex lnot
24902 @tindex !
24903 The @kbd{a !} (@code{calc-logical-not}) [@samp{lnot(a)} or @samp{!@: a}]
24904 function is true if @cite{a} is false (zero), or false if @cite{a} is
24905 true (nonzero).  It is left in symbolic form if @cite{a} is not a
24906 number.
24908 @kindex a :
24909 @pindex calc-logical-if
24910 @tindex if
24911 @c @mindex ? :
24912 @tindex ?
24913 @c @mindex @null
24914 @tindex :
24915 @cindex Arguments, not evaluated
24916 The @kbd{a :} (@code{calc-logical-if}) [@samp{if(a,b,c)} or @samp{a ? b :@: c}]
24917 function is equal to either @cite{b} or @cite{c} if @cite{a} is a nonzero
24918 number or zero, respectively.  If @cite{a} is not a number, the test is
24919 left in symbolic form and neither @cite{b} nor @cite{c} is evaluated in
24920 any way.  In algebraic formulas, this is one of the few Calc functions
24921 whose arguments are not automatically evaluated when the function itself
24922 is evaluated.  The others are @code{lambda}, @code{quote}, and
24923 @code{condition}.
24925 One minor surprise to watch out for is that the formula @samp{a?3:4}
24926 will not work because the @samp{3:4} is parsed as a fraction instead of
24927 as three separate symbols.  Type something like @samp{a ? 3 : 4} or
24928 @samp{a?(3):4} instead.
24930 As a special case, if @cite{a} evaluates to a vector, then both @cite{b}
24931 and @cite{c} are evaluated; the result is a vector of the same length
24932 as @cite{a} whose elements are chosen from corresponding elements of
24933 @cite{b} and @cite{c} according to whether each element of @cite{a}
24934 is zero or nonzero.  Each of @cite{b} and @cite{c} must be either a
24935 vector of the same length as @cite{a}, or a non-vector which is matched
24936 with all elements of @cite{a}.
24938 @kindex a @{
24939 @pindex calc-in-set
24940 @tindex in
24941 The @kbd{a @{} (@code{calc-in-set}) [@samp{in(a,b)}] function is true if
24942 the number @cite{a} is in the set of numbers represented by @cite{b}.
24943 If @cite{b} is an interval form, @cite{a} must be one of the values
24944 encompassed by the interval.  If @cite{b} is a vector, @cite{a} must be
24945 equal to one of the elements of the vector.  (If any vector elements are
24946 intervals, @cite{a} must be in any of the intervals.)  If @cite{b} is a
24947 plain number, @cite{a} must be numerically equal to @cite{b}.
24948 @xref{Set Operations}, for a group of commands that manipulate sets
24949 of this sort.
24951 @c @starindex
24952 @tindex typeof
24953 The @samp{typeof(a)} function produces an integer or variable which
24954 characterizes @cite{a}.  If @cite{a} is a number, vector, or variable,
24955 the result will be one of the following numbers:
24957 @example
24958  1   Integer
24959  2   Fraction
24960  3   Floating-point number
24961  4   HMS form
24962  5   Rectangular complex number
24963  6   Polar complex number
24964  7   Error form
24965  8   Interval form
24966  9   Modulo form
24967 10   Date-only form
24968 11   Date/time form
24969 12   Infinity (inf, uinf, or nan)
24970 100  Variable
24971 101  Vector (but not a matrix)
24972 102  Matrix
24973 @end example
24975 Otherwise, @cite{a} is a formula, and the result is a variable which
24976 represents the name of the top-level function call.
24978 @c @starindex
24979 @tindex integer
24980 @c @starindex
24981 @tindex real
24982 @c @starindex
24983 @tindex constant
24984 The @samp{integer(a)} function returns true if @cite{a} is an integer.
24985 The @samp{real(a)} function
24986 is true if @cite{a} is a real number, either integer, fraction, or
24987 float.  The @samp{constant(a)} function returns true if @cite{a} is
24988 any of the objects for which @code{typeof} would produce an integer
24989 code result except for variables, and provided that the components of
24990 an object like a vector or error form are themselves constant.
24991 Note that infinities do not satisfy any of these tests, nor do
24992 special constants like @code{pi} and @code{e}.@refill
24994 @xref{Declarations}, for a set of similar functions that recognize
24995 formulas as well as actual numbers.  For example, @samp{dint(floor(x))}
24996 is true because @samp{floor(x)} is provably integer-valued, but
24997 @samp{integer(floor(x))} does not because @samp{floor(x)} is not
24998 literally an integer constant.
25000 @c @starindex
25001 @tindex refers
25002 The @samp{refers(a,b)} function is true if the variable (or sub-expression)
25003 @cite{b} appears in @cite{a}, or false otherwise.  Unlike the other
25004 tests described here, this function returns a definite ``no'' answer
25005 even if its arguments are still in symbolic form.  The only case where
25006 @code{refers} will be left unevaluated is if @cite{a} is a plain
25007 variable (different from @cite{b}).
25009 @c @starindex
25010 @tindex negative
25011 The @samp{negative(a)} function returns true if @cite{a} ``looks'' negative,
25012 because it is a negative number, because it is of the form @cite{-x},
25013 or because it is a product or quotient with a term that looks negative.
25014 This is most useful in rewrite rules.  Beware that @samp{negative(a)}
25015 evaluates to 1 or 0 for @emph{any} argument @cite{a}, so it can only
25016 be stored in a formula if the default simplifications are turned off
25017 first with @kbd{m O} (or if it appears in an unevaluated context such
25018 as a rewrite rule condition).
25020 @c @starindex
25021 @tindex variable
25022 The @samp{variable(a)} function is true if @cite{a} is a variable,
25023 or false if not.  If @cite{a} is a function call, this test is left
25024 in symbolic form.  Built-in variables like @code{pi} and @code{inf}
25025 are considered variables like any others by this test.
25027 @c @starindex
25028 @tindex nonvar
25029 The @samp{nonvar(a)} function is true if @cite{a} is a non-variable.
25030 If its argument is a variable it is left unsimplified; it never
25031 actually returns zero.  However, since Calc's condition-testing
25032 commands consider ``false'' anything not provably true, this is
25033 often good enough.
25035 @c @starindex
25036 @tindex lin
25037 @c @starindex
25038 @tindex linnt
25039 @c @starindex
25040 @tindex islin
25041 @c @starindex
25042 @tindex islinnt
25043 @cindex Linearity testing
25044 The functions @code{lin}, @code{linnt}, @code{islin}, and @code{islinnt}
25045 check if an expression is ``linear,'' i.e., can be written in the form
25046 @cite{a + b x} for some constants @cite{a} and @cite{b}, and some
25047 variable or subformula @cite{x}.  The function @samp{islin(f,x)} checks
25048 if formula @cite{f} is linear in @cite{x}, returning 1 if so.  For
25049 example, @samp{islin(x,x)}, @samp{islin(-x,x)}, @samp{islin(3,x)}, and
25050 @samp{islin(x y / 3 - 2, x)} all return 1.  The @samp{lin(f,x)} function
25051 is similar, except that instead of returning 1 it returns the vector
25052 @cite{[a, b, x]}.  For the above examples, this vector would be
25053 @cite{[0, 1, x]}, @cite{[0, -1, x]}, @cite{[3, 0, x]}, and
25054 @cite{[-2, y/3, x]}, respectively.  Both @code{lin} and @code{islin}
25055 generally remain unevaluated for expressions which are not linear,
25056 e.g., @samp{lin(2 x^2, x)} and @samp{lin(sin(x), x)}.  The second
25057 argument can also be a formula; @samp{islin(2 + 3 sin(x), sin(x))}
25058 returns true.
25060 The @code{linnt} and @code{islinnt} functions perform a similar check,
25061 but require a ``non-trivial'' linear form, which means that the
25062 @cite{b} coefficient must be non-zero.  For example, @samp{lin(2,x)}
25063 returns @cite{[2, 0, x]} and @samp{lin(y,x)} returns @cite{[y, 0, x]},
25064 but @samp{linnt(2,x)} and @samp{linnt(y,x)} are left unevaluated
25065 (in other words, these formulas are considered to be only ``trivially''
25066 linear in @cite{x}).
25068 All four linearity-testing functions allow you to omit the second
25069 argument, in which case the input may be linear in any non-constant
25070 formula.  Here, the @cite{a=0}, @cite{b=1} case is also considered
25071 trivial, and only constant values for @cite{a} and @cite{b} are
25072 recognized.  Thus, @samp{lin(2 x y)} returns @cite{[0, 2, x y]},
25073 @samp{lin(2 - x y)} returns @cite{[2, -1, x y]}, and @samp{lin(x y)}
25074 returns @cite{[0, 1, x y]}.  The @code{linnt} function would allow the
25075 first two cases but not the third.  Also, neither @code{lin} nor
25076 @code{linnt} accept plain constants as linear in the one-argument
25077 case: @samp{islin(2,x)} is true, but @samp{islin(2)} is false.
25079 @c @starindex
25080 @tindex istrue
25081 The @samp{istrue(a)} function returns 1 if @cite{a} is a nonzero
25082 number or provably nonzero formula, or 0 if @cite{a} is anything else.
25083 Calls to @code{istrue} can only be manipulated if @kbd{m O} mode is
25084 used to make sure they are not evaluated prematurely.  (Note that
25085 declarations are used when deciding whether a formula is true;
25086 @code{istrue} returns 1 when @code{dnonzero} would return 1, and
25087 it returns 0 when @code{dnonzero} would return 0 or leave itself
25088 in symbolic form.)
25090 @node Rewrite Rules, , Logical Operations, Algebra
25091 @section Rewrite Rules
25093 @noindent
25094 @cindex Rewrite rules
25095 @cindex Transformations
25096 @cindex Pattern matching
25097 @kindex a r
25098 @pindex calc-rewrite
25099 @tindex rewrite
25100 The @kbd{a r} (@code{calc-rewrite}) [@code{rewrite}] command makes
25101 substitutions in a formula according to a specified pattern or patterns
25102 known as @dfn{rewrite rules}.  Whereas @kbd{a b} (@code{calc-substitute})
25103 matches literally, so that substituting @samp{sin(x)} with @samp{cos(x)}
25104 matches only the @code{sin} function applied to the variable @code{x},
25105 rewrite rules match general kinds of formulas; rewriting using the rule
25106 @samp{sin(x) := cos(x)} matches @code{sin} of any argument and replaces
25107 it with @code{cos} of that same argument.  The only significance of the
25108 name @code{x} is that the same name is used on both sides of the rule.
25110 Rewrite rules rearrange formulas already in Calc's memory.
25111 @xref{Syntax Tables}, to read about @dfn{syntax rules}, which are
25112 similar to algebraic rewrite rules but operate when new algebraic
25113 entries are being parsed, converting strings of characters into
25114 Calc formulas.
25116 @menu
25117 * Entering Rewrite Rules::
25118 * Basic Rewrite Rules::
25119 * Conditional Rewrite Rules::
25120 * Algebraic Properties of Rewrite Rules::
25121 * Other Features of Rewrite Rules::
25122 * Composing Patterns in Rewrite Rules::
25123 * Nested Formulas with Rewrite Rules::
25124 * Multi-Phase Rewrite Rules::
25125 * Selections with Rewrite Rules::
25126 * Matching Commands::
25127 * Automatic Rewrites::
25128 * Debugging Rewrites::
25129 * Examples of Rewrite Rules::
25130 @end menu
25132 @node Entering Rewrite Rules, Basic Rewrite Rules, Rewrite Rules, Rewrite Rules
25133 @subsection Entering Rewrite Rules
25135 @noindent
25136 Rewrite rules normally use the ``assignment'' operator
25137 @samp{@var{old} := @var{new}}.
25138 This operator is equivalent to the function call @samp{assign(old, new)}.
25139 The @code{assign} function is undefined by itself in Calc, so an
25140 assignment formula such as a rewrite rule will be left alone by ordinary
25141 Calc commands.  But certain commands, like the rewrite system, interpret
25142 assignments in special ways.@refill
25144 For example, the rule @samp{sin(x)^2 := 1-cos(x)^2} says to replace
25145 every occurrence of the sine of something, squared, with one minus the
25146 square of the cosine of that same thing.  All by itself as a formula
25147 on the stack it does nothing, but when given to the @kbd{a r} command
25148 it turns that command into a sine-squared-to-cosine-squared converter.
25150 To specify a set of rules to be applied all at once, make a vector of
25151 rules.
25153 When @kbd{a r} prompts you to enter the rewrite rules, you can answer
25154 in several ways:
25156 @enumerate
25157 @item
25158 With a rule:  @kbd{f(x) := g(x) RET}.
25159 @item
25160 With a vector of rules:  @kbd{[f1(x) := g1(x), f2(x) := g2(x)] RET}.
25161 (You can omit the enclosing square brackets if you wish.)
25162 @item
25163 With the name of a variable that contains the rule or rules vector:
25164 @kbd{myrules RET}.
25165 @item
25166 With any formula except a rule, a vector, or a variable name; this
25167 will be interpreted as the @var{old} half of a rewrite rule,
25168 and you will be prompted a second time for the @var{new} half:
25169 @kbd{f(x) @key{RET} g(x) @key{RET}}.
25170 @item
25171 With a blank line, in which case the rule, rules vector, or variable
25172 will be taken from the top of the stack (and the formula to be
25173 rewritten will come from the second-to-top position).
25174 @end enumerate
25176 If you enter the rules directly (as opposed to using rules stored
25177 in a variable), those rules will be put into the Trail so that you
25178 can retrieve them later.  @xref{Trail Commands}.
25180 It is most convenient to store rules you use often in a variable and
25181 invoke them by giving the variable name.  The @kbd{s e}
25182 (@code{calc-edit-variable}) command is an easy way to create or edit a
25183 rule set stored in a variable.  You may also wish to use @kbd{s p}
25184 (@code{calc-permanent-variable}) to save your rules permanently;
25185 @pxref{Operations on Variables}.@refill
25187 Rewrite rules are compiled into a special internal form for faster
25188 matching.  If you enter a rule set directly it must be recompiled
25189 every time.  If you store the rules in a variable and refer to them
25190 through that variable, they will be compiled once and saved away
25191 along with the variable for later reference.  This is another good
25192 reason to store your rules in a variable.
25194 Calc also accepts an obsolete notation for rules, as vectors
25195 @samp{[@var{old}, @var{new}]}.  But because it is easily confused with a
25196 vector of two rules, the use of this notation is no longer recommended.
25198 @node Basic Rewrite Rules, Conditional Rewrite Rules, Entering Rewrite Rules, Rewrite Rules
25199 @subsection Basic Rewrite Rules
25201 @noindent
25202 To match a particular formula @cite{x} with a particular rewrite rule
25203 @samp{@var{old} := @var{new}}, Calc compares the structure of @cite{x} with
25204 the structure of @var{old}.  Variables that appear in @var{old} are
25205 treated as @dfn{meta-variables}; the corresponding positions in @cite{x}
25206 may contain any sub-formulas.  For example, the pattern @samp{f(x,y)}
25207 would match the expression @samp{f(12, a+1)} with the meta-variable
25208 @samp{x} corresponding to 12 and with @samp{y} corresponding to
25209 @samp{a+1}.  However, this pattern would not match @samp{f(12)} or
25210 @samp{g(12, a+1)}, since there is no assignment of the meta-variables
25211 that will make the pattern match these expressions.  Notice that if
25212 the pattern is a single meta-variable, it will match any expression.
25214 If a given meta-variable appears more than once in @var{old}, the
25215 corresponding sub-formulas of @cite{x} must be identical.  Thus
25216 the pattern @samp{f(x,x)} would match @samp{f(12, 12)} and
25217 @samp{f(a+1, a+1)} but not @samp{f(12, a+1)} or @samp{f(a+b, b+a)}.
25218 (@xref{Conditional Rewrite Rules}, for a way to match the latter.)
25220 Things other than variables must match exactly between the pattern
25221 and the target formula.  To match a particular variable exactly, use
25222 the pseudo-function @samp{quote(v)} in the pattern.  For example, the
25223 pattern @samp{x+quote(y)} matches @samp{x+y}, @samp{2+y}, or
25224 @samp{sin(a)+y}.
25226 The special variable names @samp{e}, @samp{pi}, @samp{i}, @samp{phi},
25227 @samp{gamma}, @samp{inf}, @samp{uinf}, and @samp{nan} always match
25228 literally.  Thus the pattern @samp{sin(d + e + f)} acts exactly like
25229 @samp{sin(d + quote(e) + f)}.
25231 If the @var{old} pattern is found to match a given formula, that
25232 formula is replaced by @var{new}, where any occurrences in @var{new}
25233 of meta-variables from the pattern are replaced with the sub-formulas
25234 that they matched.  Thus, applying the rule @samp{f(x,y) := g(y+x,x)}
25235 to @samp{f(12, a+1)} would produce @samp{g(a+13, 12)}.
25237 The normal @kbd{a r} command applies rewrite rules over and over
25238 throughout the target formula until no further changes are possible
25239 (up to a limit of 100 times).  Use @kbd{C-u 1 a r} to make only one
25240 change at a time.
25242 @node Conditional Rewrite Rules, Algebraic Properties of Rewrite Rules, Basic Rewrite Rules, Rewrite Rules
25243 @subsection Conditional Rewrite Rules
25245 @noindent
25246 A rewrite rule can also be @dfn{conditional}, written in the form
25247 @samp{@var{old} := @var{new} :: @var{cond}}.  (There is also the obsolete
25248 form @samp{[@var{old}, @var{new}, @var{cond}]}.)  If a @var{cond} part
25249 is present in the
25250 rule, this is an additional condition that must be satisfied before
25251 the rule is accepted.  Once @var{old} has been successfully matched
25252 to the target expression, @var{cond} is evaluated (with all the
25253 meta-variables substituted for the values they matched) and simplified
25254 with @kbd{a s} (@code{calc-simplify}).  If the result is a nonzero
25255 number or any other object known to be nonzero (@pxref{Declarations}),
25256 the rule is accepted.  If the result is zero or if it is a symbolic
25257 formula that is not known to be nonzero, the rule is rejected.
25258 @xref{Logical Operations}, for a number of functions that return
25259 1 or 0 according to the results of various tests.@refill
25261 For example, the formula @samp{n > 0} simplifies to 1 or 0 if @cite{n}
25262 is replaced by a positive or nonpositive number, respectively (or if
25263 @cite{n} has been declared to be positive or nonpositive).  Thus,
25264 the rule @samp{f(x,y) := g(y+x,x) :: x+y > 0} would apply to
25265 @samp{f(0, 4)} but not to @samp{f(-3, 2)} or @samp{f(12, a+1)}
25266 (assuming no outstanding declarations for @cite{a}).  In the case of
25267 @samp{f(-3, 2)}, the condition can be shown not to be satisfied; in
25268 the case of @samp{f(12, a+1)}, the condition merely cannot be shown
25269 to be satisfied, but that is enough to reject the rule.
25271 While Calc will use declarations to reason about variables in the
25272 formula being rewritten, declarations do not apply to meta-variables.
25273 For example, the rule @samp{f(a) := g(a+1)} will match for any values
25274 of @samp{a}, such as complex numbers, vectors, or formulas, even if
25275 @samp{a} has been declared to be real or scalar.  If you want the
25276 meta-variable @samp{a} to match only literal real numbers, use
25277 @samp{f(a) := g(a+1) :: real(a)}.  If you want @samp{a} to match only
25278 reals and formulas which are provably real, use @samp{dreal(a)} as
25279 the condition.
25281 The @samp{::} operator is a shorthand for the @code{condition}
25282 function; @samp{@var{old} := @var{new} :: @var{cond}} is equivalent to
25283 the formula @samp{condition(assign(@var{old}, @var{new}), @var{cond})}.
25285 If you have several conditions, you can use @samp{... :: c1 :: c2 :: c3}
25286 or @samp{... :: c1 && c2 && c3}.  The two are entirely equivalent.
25288 It is also possible to embed conditions inside the pattern:
25289 @samp{f(x :: x>0, y) := g(y+x, x)}.  This is purely a notational
25290 convenience, though; where a condition appears in a rule has no
25291 effect on when it is tested.  The rewrite-rule compiler automatically
25292 decides when it is best to test each condition while a rule is being
25293 matched.
25295 Certain conditions are handled as special cases by the rewrite rule
25296 system and are tested very efficiently:  Where @cite{x} is any
25297 meta-variable, these conditions are @samp{integer(x)}, @samp{real(x)},
25298 @samp{constant(x)}, @samp{negative(x)}, @samp{x >= y} where @cite{y}
25299 is either a constant or another meta-variable and @samp{>=} may be
25300 replaced by any of the six relational operators, and @samp{x % a = b}
25301 where @cite{a} and @cite{b} are constants.  Other conditions, like
25302 @samp{x >= y+1} or @samp{dreal(x)}, will be less efficient to check
25303 since Calc must bring the whole evaluator and simplifier into play.
25305 An interesting property of @samp{::} is that neither of its arguments
25306 will be touched by Calc's default simplifications.  This is important
25307 because conditions often are expressions that cannot safely be
25308 evaluated early.  For example, the @code{typeof} function never
25309 remains in symbolic form; entering @samp{typeof(a)} will put the
25310 number 100 (the type code for variables like @samp{a}) on the stack.
25311 But putting the condition @samp{... :: typeof(a) = 6} on the stack
25312 is safe since @samp{::} prevents the @code{typeof} from being
25313 evaluated until the condition is actually used by the rewrite system.
25315 Since @samp{::} protects its lefthand side, too, you can use a dummy
25316 condition to protect a rule that must itself not evaluate early.
25317 For example, it's not safe to put @samp{a(f,x) := apply(f, [x])} on
25318 the stack because it will immediately evaluate to @samp{a(f,x) := f(x)},
25319 where the meta-variable-ness of @code{f} on the righthand side has been
25320 lost.  But @samp{a(f,x) := apply(f, [x]) :: 1} is safe, and of course
25321 the condition @samp{1} is always true (nonzero) so it has no effect on
25322 the functioning of the rule.  (The rewrite compiler will ensure that
25323 it doesn't even impact the speed of matching the rule.)
25325 @node Algebraic Properties of Rewrite Rules, Other Features of Rewrite Rules, Conditional Rewrite Rules, Rewrite Rules
25326 @subsection Algebraic Properties of Rewrite Rules
25328 @noindent
25329 The rewrite mechanism understands the algebraic properties of functions
25330 like @samp{+} and @samp{*}.  In particular, pattern matching takes
25331 the associativity and commutativity of the following functions into
25332 account:
25334 @smallexample
25335 + - *  = !=  && ||  and or xor  vint vunion vxor  gcd lcm  max min  beta
25336 @end smallexample
25338 For example, the rewrite rule:
25340 @example
25341 a x + b x  :=  (a + b) x
25342 @end example
25344 @noindent
25345 will match formulas of the form,
25347 @example
25348 a x + b x,  x a + x b,  a x + x b,  x a + b x
25349 @end example
25351 Rewrites also understand the relationship between the @samp{+} and @samp{-}
25352 operators.  The above rewrite rule will also match the formulas,
25354 @example
25355 a x - b x,  x a - x b,  a x - x b,  x a - b x
25356 @end example
25358 @noindent
25359 by matching @samp{b} in the pattern to @samp{-b} from the formula.
25361 Applied to a sum of many terms like @samp{r + a x + s + b x + t}, this
25362 pattern will check all pairs of terms for possible matches.  The rewrite
25363 will take whichever suitable pair it discovers first.
25365 In general, a pattern using an associative operator like @samp{a + b}
25366 will try @i{2 n} different ways to match a sum of @i{n} terms
25367 like @samp{x + y + z - w}.  First, @samp{a} is matched against each
25368 of @samp{x}, @samp{y}, @samp{z}, and @samp{-w} in turn, with @samp{b}
25369 being matched to the remainders @samp{y + z - w}, @samp{x + z - w}, etc.
25370 If none of these succeed, then @samp{b} is matched against each of the
25371 four terms with @samp{a} matching the remainder.  Half-and-half matches,
25372 like @samp{(x + y) + (z - w)}, are not tried.
25374 Note that @samp{*} is not commutative when applied to matrices, but
25375 rewrite rules pretend that it is.  If you type @kbd{m v} to enable
25376 matrix mode (@pxref{Matrix Mode}), rewrite rules will match @samp{*}
25377 literally, ignoring its usual commutativity property.  (In the
25378 current implementation, the associativity also vanishes---it is as
25379 if the pattern had been enclosed in a @code{plain} marker; see below.)
25380 If you are applying rewrites to formulas with matrices, it's best to
25381 enable matrix mode first to prevent algebraically incorrect rewrites
25382 from occurring.
25384 The pattern @samp{-x} will actually match any expression.  For example,
25385 the rule
25387 @example
25388 f(-x)  :=  -f(x)
25389 @end example
25391 @noindent
25392 will rewrite @samp{f(a)} to @samp{-f(-a)}.  To avoid this, either use
25393 a @code{plain} marker as described below, or add a @samp{negative(x)}
25394 condition.  The @code{negative} function is true if its argument
25395 ``looks'' negative, for example, because it is a negative number or
25396 because it is a formula like @samp{-x}.  The new rule using this
25397 condition is:
25399 @example
25400 f(x)  :=  -f(-x)  :: negative(x)    @r{or, equivalently,}
25401 f(-x)  :=  -f(x)  :: negative(-x)
25402 @end example
25404 In the same way, the pattern @samp{x - y} will match the sum @samp{a + b}
25405 by matching @samp{y} to @samp{-b}.
25407 The pattern @samp{a b} will also match the formula @samp{x/y} if
25408 @samp{y} is a number.  Thus the rule @samp{a x + @w{b x} := (a+b) x}
25409 will also convert @samp{a x + x / 2} to @samp{(a + 0.5) x} (or
25410 @samp{(a + 1:2) x}, depending on the current fraction mode).
25412 Calc will @emph{not} take other liberties with @samp{*}, @samp{/}, and
25413 @samp{^}.  For example, the pattern @samp{f(a b)} will not match
25414 @samp{f(x^2)}, and @samp{f(a + b)} will not match @samp{f(2 x)}, even
25415 though conceivably these patterns could match with @samp{a = b = x}.
25416 Nor will @samp{f(a b)} match @samp{f(x / y)} if @samp{y} is not a
25417 constant, even though it could be considered to match with @samp{a = x}
25418 and @samp{b = 1/y}.  The reasons are partly for efficiency, and partly
25419 because while few mathematical operations are substantively different
25420 for addition and subtraction, often it is preferable to treat the cases
25421 of multiplication, division, and integer powers separately.
25423 Even more subtle is the rule set
25425 @example
25426 [ f(a) + f(b) := f(a + b),  -f(a) := f(-a) ]
25427 @end example
25429 @noindent
25430 attempting to match @samp{f(x) - f(y)}.  You might think that Calc
25431 will view this subtraction as @samp{f(x) + (-f(y))} and then apply
25432 the above two rules in turn, but actually this will not work because
25433 Calc only does this when considering rules for @samp{+} (like the
25434 first rule in this set).  So it will see first that @samp{f(x) + (-f(y))}
25435 does not match @samp{f(a) + f(b)} for any assignments of the
25436 meta-variables, and then it will see that @samp{f(x) - f(y)} does
25437 not match @samp{-f(a)} for any assignment of @samp{a}.  Because Calc
25438 tries only one rule at a time, it will not be able to rewrite
25439 @samp{f(x) - f(y)} with this rule set.  An explicit @samp{f(a) - f(b)}
25440 rule will have to be added.
25442 Another thing patterns will @emph{not} do is break up complex numbers.
25443 The pattern @samp{myconj(a + @w{b i)} := a - b i} will work for formulas
25444 involving the special constant @samp{i} (such as @samp{3 - 4 i}), but
25445 it will not match actual complex numbers like @samp{(3, -4)}.  A version
25446 of the above rule for complex numbers would be
25448 @example
25449 myconj(a)  :=  re(a) - im(a) (0,1)  :: im(a) != 0
25450 @end example
25452 @noindent
25453 (Because the @code{re} and @code{im} functions understand the properties
25454 of the special constant @samp{i}, this rule will also work for
25455 @samp{3 - 4 i}.  In fact, this particular rule would probably be better
25456 without the @samp{im(a) != 0} condition, since if @samp{im(a) = 0} the
25457 righthand side of the rule will still give the correct answer for the
25458 conjugate of a real number.)
25460 It is also possible to specify optional arguments in patterns.  The rule
25462 @example
25463 opt(a) x + opt(b) (x^opt(c) + opt(d))  :=  f(a, b, c, d)
25464 @end example
25466 @noindent
25467 will match the formula
25469 @example
25470 5 (x^2 - 4) + 3 x
25471 @end example
25473 @noindent
25474 in a fairly straightforward manner, but it will also match reduced
25475 formulas like
25477 @example
25478 x + x^2,    2(x + 1) - x,    x + x
25479 @end example
25481 @noindent
25482 producing, respectively,
25484 @example
25485 f(1, 1, 2, 0),   f(-1, 2, 1, 1),   f(1, 1, 1, 0)
25486 @end example
25488 (The latter two formulas can be entered only if default simplifications
25489 have been turned off with @kbd{m O}.)
25491 The default value for a term of a sum is zero.  The default value
25492 for a part of a product, for a power, or for the denominator of a
25493 quotient, is one.  Also, @samp{-x} matches the pattern @samp{opt(a) b}
25494 with @samp{a = -1}.
25496 In particular, the distributive-law rule can be refined to
25498 @example
25499 opt(a) x + opt(b) x  :=  (a + b) x
25500 @end example
25502 @noindent
25503 so that it will convert, e.g., @samp{a x - x}, to @samp{(a - 1) x}.
25505 The pattern @samp{opt(a) + opt(b) x} matches almost any formulas which
25506 are linear in @samp{x}.  You can also use the @code{lin} and @code{islin}
25507 functions with rewrite conditions to test for this; @pxref{Logical
25508 Operations}.  These functions are not as convenient to use in rewrite
25509 rules, but they recognize more kinds of formulas as linear:
25510 @samp{x/z} is considered linear with @cite{b = 1/z} by @code{lin},
25511 but it will not match the above pattern because that pattern calls
25512 for a multiplication, not a division.
25514 As another example, the obvious rule to replace @samp{sin(x)^2 + cos(x)^2}
25515 by 1,
25517 @example
25518 sin(x)^2 + cos(x)^2  :=  1
25519 @end example
25521 @noindent
25522 misses many cases because the sine and cosine may both be multiplied by
25523 an equal factor.  Here's a more successful rule:
25525 @example
25526 opt(a) sin(x)^2 + opt(a) cos(x)^2  :=  a
25527 @end example
25529 Note that this rule will @emph{not} match @samp{sin(x)^2 + 6 cos(x)^2}
25530 because one @cite{a} would have ``matched'' 1 while the other matched 6.
25532 Calc automatically converts a rule like
25534 @example
25535 f(x-1, x)  :=  g(x)
25536 @end example
25538 @noindent
25539 into the form
25541 @example
25542 f(temp, x)  :=  g(x)  :: temp = x-1
25543 @end example
25545 @noindent
25546 (where @code{temp} stands for a new, invented meta-variable that
25547 doesn't actually have a name).  This modified rule will successfully
25548 match @samp{f(6, 7)}, binding @samp{temp} and @samp{x} to 6 and 7,
25549 respectively, then verifying that they differ by one even though
25550 @samp{6} does not superficially look like @samp{x-1}.
25552 However, Calc does not solve equations to interpret a rule.  The
25553 following rule,
25555 @example
25556 f(x-1, x+1)  :=  g(x)
25557 @end example
25559 @noindent
25560 will not work.  That is, it will match @samp{f(a - 1 + b, a + 1 + b)}
25561 but not @samp{f(6, 8)}.  Calc always interprets at least one occurrence
25562 of a variable by literal matching.  If the variable appears ``isolated''
25563 then Calc is smart enough to use it for literal matching.  But in this
25564 last example, Calc is forced to rewrite the rule to @samp{f(x-1, temp)
25565 := g(x) :: temp = x+1} where the @samp{x-1} term must correspond to an
25566 actual ``something-minus-one'' in the target formula.
25568 A successful way to write this would be @samp{f(x, x+2) := g(x+1)}.
25569 You could make this resemble the original form more closely by using
25570 @code{let} notation, which is described in the next section:
25572 @example
25573 f(xm1, x+1)  :=  g(x)  :: let(x := xm1+1)
25574 @end example
25576 Calc does this rewriting or ``conditionalizing'' for any sub-pattern
25577 which involves only the functions in the following list, operating
25578 only on constants and meta-variables which have already been matched
25579 elsewhere in the pattern.  When matching a function call, Calc is
25580 careful to match arguments which are plain variables before arguments
25581 which are calls to any of the functions below, so that a pattern like
25582 @samp{f(x-1, x)} can be conditionalized even though the isolated
25583 @samp{x} comes after the @samp{x-1}.
25585 @smallexample
25586 + - * / \ % ^  abs sign  round rounde roundu trunc floor ceil
25587 max min  re im conj arg
25588 @end smallexample
25590 You can suppress all of the special treatments described in this
25591 section by surrounding a function call with a @code{plain} marker.
25592 This marker causes the function call which is its argument to be
25593 matched literally, without regard to commutativity, associativity,
25594 negation, or conditionalization.  When you use @code{plain}, the
25595 ``deep structure'' of the formula being matched can show through.
25596 For example,
25598 @example
25599 plain(a - a b)  :=  f(a, b)
25600 @end example
25602 @noindent
25603 will match only literal subtractions.  However, the @code{plain}
25604 marker does not affect its arguments' arguments.  In this case,
25605 commutativity and associativity is still considered while matching
25606 the @w{@samp{a b}} sub-pattern, so the whole pattern will match
25607 @samp{x - y x} as well as @samp{x - x y}.  We could go still
25608 further and use
25610 @example
25611 plain(a - plain(a b))  :=  f(a, b)
25612 @end example
25614 @noindent
25615 which would do a completely strict match for the pattern.
25617 By contrast, the @code{quote} marker means that not only the
25618 function name but also the arguments must be literally the same.
25619 The above pattern will match @samp{x - x y} but
25621 @example
25622 quote(a - a b)  :=  f(a, b)
25623 @end example
25625 @noindent
25626 will match only the single formula @samp{a - a b}.  Also,
25628 @example
25629 quote(a - quote(a b))  :=  f(a, b)
25630 @end example
25632 @noindent
25633 will match only @samp{a - quote(a b)}---probably not the desired
25634 effect!
25636 A certain amount of algebra is also done when substituting the
25637 meta-variables on the righthand side of a rule.  For example,
25638 in the rule
25640 @example
25641 a + f(b)  :=  f(a + b)
25642 @end example
25644 @noindent
25645 matching @samp{f(x) - y} would produce @samp{f((-y) + x)} if
25646 taken literally, but the rewrite mechanism will simplify the
25647 righthand side to @samp{f(x - y)} automatically.  (Of course,
25648 the default simplifications would do this anyway, so this
25649 special simplification is only noticeable if you have turned the
25650 default simplifications off.)  This rewriting is done only when
25651 a meta-variable expands to a ``negative-looking'' expression.
25652 If this simplification is not desirable, you can use a @code{plain}
25653 marker on the righthand side:
25655 @example
25656 a + f(b)  :=  f(plain(a + b))
25657 @end example
25659 @noindent
25660 In this example, we are still allowing the pattern-matcher to
25661 use all the algebra it can muster, but the righthand side will
25662 always simplify to a literal addition like @samp{f((-y) + x)}.
25664 @node Other Features of Rewrite Rules, Composing Patterns in Rewrite Rules, Algebraic Properties of Rewrite Rules, Rewrite Rules
25665 @subsection Other Features of Rewrite Rules
25667 @noindent
25668 Certain ``function names'' serve as markers in rewrite rules.
25669 Here is a complete list of these markers.  First are listed the
25670 markers that work inside a pattern; then come the markers that
25671 work in the righthand side of a rule.
25673 @c @starindex
25674 @tindex import
25675 One kind of marker, @samp{import(x)}, takes the place of a whole
25676 rule.  Here @cite{x} is the name of a variable containing another
25677 rule set; those rules are ``spliced into'' the rule set that
25678 imports them.  For example, if @samp{[f(a+b) := f(a) + f(b),
25679 f(a b) := a f(b) :: real(a)]} is stored in variable @samp{linearF},
25680 then the rule set @samp{[f(0) := 0, import(linearF)]} will apply
25681 all three rules.  It is possible to modify the imported rules
25682 slightly:  @samp{import(x, v1, x1, v2, x2, @dots{})} imports
25683 the rule set @cite{x} with all occurrences of @c{$v_1$}
25684 @cite{v1}, as either
25685 a variable name or a function name, replaced with @c{$x_1$}
25686 @cite{x1} and
25687 so on.  (If @c{$v_1$}
25688 @cite{v1} is used as a function name, then @c{$x_1$}
25689 @cite{x1}
25690 must be either a function name itself or a @w{@samp{< >}} nameless
25691 function; @pxref{Specifying Operators}.)  For example, @samp{[g(0) := 0,
25692 import(linearF, f, g)]} applies the linearity rules to the function
25693 @samp{g} instead of @samp{f}.  Imports can be nested, but the
25694 import-with-renaming feature may fail to rename sub-imports properly.
25696 The special functions allowed in patterns are:
25698 @table @samp
25699 @item quote(x)
25700 @c @starindex
25701 @tindex quote
25702 This pattern matches exactly @cite{x}; variable names in @cite{x} are
25703 not interpreted as meta-variables.  The only flexibility is that
25704 numbers are compared for numeric equality, so that the pattern
25705 @samp{f(quote(12))} will match both @samp{f(12)} and @samp{f(12.0)}.
25706 (Numbers are always treated this way by the rewrite mechanism:
25707 The rule @samp{f(x,x) := g(x)} will match @samp{f(12, 12.0)}.
25708 The rewrite may produce either @samp{g(12)} or @samp{g(12.0)}
25709 as a result in this case.)
25711 @item plain(x)
25712 @c @starindex
25713 @tindex plain
25714 Here @cite{x} must be a function call @samp{f(x1,x2,@dots{})}.  This
25715 pattern matches a call to function @cite{f} with the specified
25716 argument patterns.  No special knowledge of the properties of the
25717 function @cite{f} is used in this case; @samp{+} is not commutative or
25718 associative.  Unlike @code{quote}, the arguments @samp{x1,x2,@dots{}}
25719 are treated as patterns.  If you wish them to be treated ``plainly''
25720 as well, you must enclose them with more @code{plain} markers:
25721 @samp{plain(plain(@w{-a}) + plain(b c))}.
25723 @item opt(x,def)
25724 @c @starindex
25725 @tindex opt
25726 Here @cite{x} must be a variable name.  This must appear as an
25727 argument to a function or an element of a vector; it specifies that
25728 the argument or element is optional.
25729 As an argument to @samp{+}, @samp{-}, @samp{*}, @samp{&&}, or @samp{||},
25730 or as the second argument to @samp{/} or @samp{^}, the value @var{def}
25731 may be omitted.  The pattern @samp{x + opt(y)} matches a sum by
25732 binding one summand to @cite{x} and the other to @cite{y}, and it
25733 matches anything else by binding the whole expression to @cite{x} and
25734 zero to @cite{y}.  The other operators above work similarly.@refill
25736 For general miscellanous functions, the default value @code{def}
25737 must be specified.  Optional arguments are dropped starting with
25738 the rightmost one during matching.  For example, the pattern
25739 @samp{f(opt(a,0), b, opt(c,b))} will match @samp{f(b)}, @samp{f(a,b)},
25740 or @samp{f(a,b,c)}.  Default values of zero and @cite{b} are
25741 supplied in this example for the omitted arguments.  Note that
25742 the literal variable @cite{b} will be the default in the latter
25743 case, @emph{not} the value that matched the meta-variable @cite{b}.
25744 In other words, the default @var{def} is effectively quoted.
25746 @item condition(x,c)
25747 @c @starindex
25748 @tindex condition
25749 @tindex ::
25750 This matches the pattern @cite{x}, with the attached condition
25751 @cite{c}.  It is the same as @samp{x :: c}.
25753 @item pand(x,y)
25754 @c @starindex
25755 @tindex pand
25756 @tindex &&&
25757 This matches anything that matches both pattern @cite{x} and
25758 pattern @cite{y}.  It is the same as @samp{x &&& y}.
25759 @pxref{Composing Patterns in Rewrite Rules}.
25761 @item por(x,y)
25762 @c @starindex
25763 @tindex por
25764 @tindex |||
25765 This matches anything that matches either pattern @cite{x} or
25766 pattern @cite{y}.  It is the same as @w{@samp{x ||| y}}.
25768 @item pnot(x)
25769 @c @starindex
25770 @tindex pnot
25771 @tindex !!!
25772 This matches anything that does not match pattern @cite{x}.
25773 It is the same as @samp{!!! x}.
25775 @item cons(h,t)
25776 @c @mindex cons
25777 @tindex cons (rewrites)
25778 This matches any vector of one or more elements.  The first
25779 element is matched to @cite{h}; a vector of the remaining
25780 elements is matched to @cite{t}.  Note that vectors of fixed
25781 length can also be matched as actual vectors:  The rule
25782 @samp{cons(a,cons(b,[])) := cons(a+b,[])} is equivalent
25783 to the rule @samp{[a,b] := [a+b]}.
25785 @item rcons(t,h)
25786 @c @mindex rcons
25787 @tindex rcons (rewrites)
25788 This is like @code{cons}, except that the @emph{last} element
25789 is matched to @cite{h}, with the remaining elements matched
25790 to @cite{t}.
25792 @item apply(f,args)
25793 @c @mindex apply
25794 @tindex apply (rewrites)
25795 This matches any function call.  The name of the function, in
25796 the form of a variable, is matched to @cite{f}.  The arguments
25797 of the function, as a vector of zero or more objects, are
25798 matched to @samp{args}.  Constants, variables, and vectors
25799 do @emph{not} match an @code{apply} pattern.  For example,
25800 @samp{apply(f,x)} matches any function call, @samp{apply(quote(f),x)}
25801 matches any call to the function @samp{f}, @samp{apply(f,[a,b])}
25802 matches any function call with exactly two arguments, and
25803 @samp{apply(quote(f), cons(a,cons(b,x)))} matches any call
25804 to the function @samp{f} with two or more arguments.  Another
25805 way to implement the latter, if the rest of the rule does not
25806 need to refer to the first two arguments of @samp{f} by name,
25807 would be @samp{apply(quote(f), x :: vlen(x) >= 2)}.
25808 Here's a more interesting sample use of @code{apply}:
25810 @example
25811 apply(f,[x+n])  :=  n + apply(f,[x])
25812    :: in(f, [floor,ceil,round,trunc]) :: integer(n)
25813 @end example
25815 Note, however, that this will be slower to match than a rule
25816 set with four separate rules.  The reason is that Calc sorts
25817 the rules of a rule set according to top-level function name;
25818 if the top-level function is @code{apply}, Calc must try the
25819 rule for every single formula and sub-formula.  If the top-level
25820 function in the pattern is, say, @code{floor}, then Calc invokes
25821 the rule only for sub-formulas which are calls to @code{floor}.
25823 Formulas normally written with operators like @code{+} are still
25824 considered function calls:  @code{apply(f,x)} matches @samp{a+b}
25825 with @samp{f = add}, @samp{x = [a,b]}.
25827 You must use @code{apply} for meta-variables with function names
25828 on both sides of a rewrite rule:  @samp{apply(f, [x]) := f(x+1)}
25829 is @emph{not} correct, because it rewrites @samp{spam(6)} into
25830 @samp{f(7)}.  The righthand side should be @samp{apply(f, [x+1])}.
25831 Also note that you will have to use no-simplify (@kbd{m O})
25832 mode when entering this rule so that the @code{apply} isn't
25833 evaluated immediately to get the new rule @samp{f(x) := f(x+1)}.
25834 Or, use @kbd{s e} to enter the rule without going through the stack,
25835 or enter the rule as @samp{apply(f, [x]) := apply(f, [x+1]) @w{:: 1}}.
25836 @xref{Conditional Rewrite Rules}.
25838 @item select(x)
25839 @c @starindex
25840 @tindex select
25841 This is used for applying rules to formulas with selections;
25842 @pxref{Selections with Rewrite Rules}.
25843 @end table
25845 Special functions for the righthand sides of rules are:
25847 @table @samp
25848 @item quote(x)
25849 The notation @samp{quote(x)} is changed to @samp{x} when the
25850 righthand side is used.  As far as the rewrite rule is concerned,
25851 @code{quote} is invisible.  However, @code{quote} has the special
25852 property in Calc that its argument is not evaluated.  Thus,
25853 while it will not work to put the rule @samp{t(a) := typeof(a)}
25854 on the stack because @samp{typeof(a)} is evaluated immediately
25855 to produce @samp{t(a) := 100}, you can use @code{quote} to
25856 protect the righthand side:  @samp{t(a) := quote(typeof(a))}.
25857 (@xref{Conditional Rewrite Rules}, for another trick for
25858 protecting rules from evaluation.)
25860 @item plain(x)
25861 Special properties of and simplifications for the function call
25862 @cite{x} are not used.  One interesting case where @code{plain}
25863 is useful is the rule, @samp{q(x) := quote(x)}, trying to expand a
25864 shorthand notation for the @code{quote} function.  This rule will
25865 not work as shown; instead of replacing @samp{q(foo)} with
25866 @samp{quote(foo)}, it will replace it with @samp{foo}!  The correct
25867 rule would be @samp{q(x) := plain(quote(x))}.
25869 @item cons(h,t)
25870 Where @cite{t} is a vector, this is converted into an expanded
25871 vector during rewrite processing.  Note that @code{cons} is a regular
25872 Calc function which normally does this anyway; the only way @code{cons}
25873 is treated specially by rewrites is that @code{cons} on the righthand
25874 side of a rule will be evaluated even if default simplifications
25875 have been turned off.
25877 @item rcons(t,h)
25878 Analogous to @code{cons} except putting @cite{h} at the @emph{end} of
25879 the vector @cite{t}.
25881 @item apply(f,args)
25882 Where @cite{f} is a variable and @var{args} is a vector, this
25883 is converted to a function call.  Once again, note that @code{apply}
25884 is also a regular Calc function.
25886 @item eval(x)
25887 @c @starindex
25888 @tindex eval
25889 The formula @cite{x} is handled in the usual way, then the
25890 default simplifications are applied to it even if they have
25891 been turned off normally.  This allows you to treat any function
25892 similarly to the way @code{cons} and @code{apply} are always
25893 treated.  However, there is a slight difference:  @samp{cons(2+3, [])}
25894 with default simplifications off will be converted to @samp{[2+3]},
25895 whereas @samp{eval(cons(2+3, []))} will be converted to @samp{[5]}.
25897 @item evalsimp(x)
25898 @c @starindex
25899 @tindex evalsimp
25900 The formula @cite{x} has meta-variables substituted in the usual
25901 way, then algebraically simplified as if by the @kbd{a s} command.
25903 @item evalextsimp(x)
25904 @c @starindex
25905 @tindex evalextsimp
25906 The formula @cite{x} has meta-variables substituted in the normal
25907 way, then ``extendedly'' simplified as if by the @kbd{a e} command.
25909 @item select(x)
25910 @xref{Selections with Rewrite Rules}.
25911 @end table
25913 There are also some special functions you can use in conditions.
25915 @table @samp
25916 @item let(v := x)
25917 @c @starindex
25918 @tindex let
25919 The expression @cite{x} is evaluated with meta-variables substituted.
25920 The @kbd{a s} command's simplifications are @emph{not} applied by
25921 default, but @cite{x} can include calls to @code{evalsimp} or
25922 @code{evalextsimp} as described above to invoke higher levels
25923 of simplification.  The
25924 result of @cite{x} is then bound to the meta-variable @cite{v}.  As
25925 usual, if this meta-variable has already been matched to something
25926 else the two values must be equal; if the meta-variable is new then
25927 it is bound to the result of the expression.  This variable can then
25928 appear in later conditions, and on the righthand side of the rule.
25929 In fact, @cite{v} may be any pattern in which case the result of
25930 evaluating @cite{x} is matched to that pattern, binding any
25931 meta-variables that appear in that pattern.  Note that @code{let}
25932 can only appear by itself as a condition, or as one term of an
25933 @samp{&&} which is a whole condition:  It cannot be inside
25934 an @samp{||} term or otherwise buried.@refill
25936 The alternate, equivalent form @samp{let(v, x)} is also recognized.
25937 Note that the use of @samp{:=} by @code{let}, while still being
25938 assignment-like in character, is unrelated to the use of @samp{:=}
25939 in the main part of a rewrite rule.
25941 As an example, @samp{f(a) := g(ia) :: let(ia := 1/a) :: constant(ia)}
25942 replaces @samp{f(a)} with @samp{g} of the inverse of @samp{a}, if
25943 that inverse exists and is constant.  For example, if @samp{a} is a
25944 singular matrix the operation @samp{1/a} is left unsimplified and
25945 @samp{constant(ia)} fails, but if @samp{a} is an invertible matrix
25946 then the rule succeeds.  Without @code{let} there would be no way
25947 to express this rule that didn't have to invert the matrix twice.
25948 Note that, because the meta-variable @samp{ia} is otherwise unbound
25949 in this rule, the @code{let} condition itself always ``succeeds''
25950 because no matter what @samp{1/a} evaluates to, it can successfully
25951 be bound to @code{ia}.@refill
25953 Here's another example, for integrating cosines of linear
25954 terms:  @samp{myint(cos(y),x) := sin(y)/b :: let([a,b,x] := lin(y,x))}.
25955 The @code{lin} function returns a 3-vector if its argument is linear,
25956 or leaves itself unevaluated if not.  But an unevaluated @code{lin}
25957 call will not match the 3-vector on the lefthand side of the @code{let},
25958 so this @code{let} both verifies that @code{y} is linear, and binds
25959 the coefficients @code{a} and @code{b} for use elsewhere in the rule.
25960 (It would have been possible to use @samp{sin(a x + b)/b} for the
25961 righthand side instead, but using @samp{sin(y)/b} avoids gratuitous
25962 rearrangement of the argument of the sine.)@refill
25964 @c @starindex
25965 @tindex ierf
25966 Similarly, here is a rule that implements an inverse-@code{erf}
25967 function.  It uses @code{root} to search for a solution.  If
25968 @code{root} succeeds, it will return a vector of two numbers
25969 where the first number is the desired solution.  If no solution
25970 is found, @code{root} remains in symbolic form.  So we use
25971 @code{let} to check that the result was indeed a vector.
25973 @example
25974 ierf(x)  :=  y  :: let([y,z] := root(erf(a) = x, a, .5))
25975 @end example
25977 @item matches(v,p)
25978 The meta-variable @var{v}, which must already have been matched
25979 to something elsewhere in the rule, is compared against pattern
25980 @var{p}.  Since @code{matches} is a standard Calc function, it
25981 can appear anywhere in a condition.  But if it appears alone or
25982 as a term of a top-level @samp{&&}, then you get the special
25983 extra feature that meta-variables which are bound to things
25984 inside @var{p} can be used elsewhere in the surrounding rewrite
25985 rule.
25987 The only real difference between @samp{let(p := v)} and
25988 @samp{matches(v, p)} is that the former evaluates @samp{v} using
25989 the default simplifications, while the latter does not.
25991 @item remember
25992 @vindex remember
25993 This is actually a variable, not a function.  If @code{remember}
25994 appears as a condition in a rule, then when that rule succeeds
25995 the original expression and rewritten expression are added to the
25996 front of the rule set that contained the rule.  If the rule set
25997 was not stored in a variable, @code{remember} is ignored.  The
25998 lefthand side is enclosed in @code{quote} in the added rule if it
25999 contains any variables.
26001 For example, the rule @samp{f(n) := n f(n-1) :: remember} applied
26002 to @samp{f(7)} will add the rule @samp{f(7) := 7 f(6)} to the front
26003 of the rule set.  The rule set @code{EvalRules} works slightly
26004 differently:  There, the evaluation of @samp{f(6)} will complete before
26005 the result is added to the rule set, in this case as @samp{f(7) := 5040}.
26006 Thus @code{remember} is most useful inside @code{EvalRules}.
26008 It is up to you to ensure that the optimization performed by
26009 @code{remember} is safe.  For example, the rule @samp{foo(n) := n
26010 :: evalv(eatfoo) > 0 :: remember} is a bad idea (@code{evalv} is
26011 the function equivalent of the @kbd{=} command); if the variable
26012 @code{eatfoo} ever contains 1, rules like @samp{foo(7) := 7} will
26013 be added to the rule set and will continue to operate even if
26014 @code{eatfoo} is later changed to 0.
26016 @item remember(c)
26017 @c @starindex
26018 @tindex remember
26019 Remember the match as described above, but only if condition @cite{c}
26020 is true.  For example, @samp{remember(n % 4 = 0)} in the above factorial
26021 rule remembers only every fourth result.  Note that @samp{remember(1)}
26022 is equivalent to @samp{remember}, and @samp{remember(0)} has no effect.
26023 @end table
26025 @node Composing Patterns in Rewrite Rules, Nested Formulas with Rewrite Rules, Other Features of Rewrite Rules, Rewrite Rules
26026 @subsection Composing Patterns in Rewrite Rules
26028 @noindent
26029 There are three operators, @samp{&&&}, @samp{|||}, and @samp{!!!},
26030 that combine rewrite patterns to make larger patterns.  The
26031 combinations are ``and,'' ``or,'' and ``not,'' respectively, and
26032 these operators are the pattern equivalents of @samp{&&}, @samp{||}
26033 and @samp{!} (which operate on zero-or-nonzero logical values).
26035 Note that @samp{&&&}, @samp{|||}, and @samp{!!!} are left in symbolic
26036 form by all regular Calc features; they have special meaning only in
26037 the context of rewrite rule patterns.
26039 The pattern @samp{@var{p1} &&& @var{p2}} matches anything that
26040 matches both @var{p1} and @var{p2}.  One especially useful case is
26041 when one of @var{p1} or @var{p2} is a meta-variable.  For example,
26042 here is a rule that operates on error forms:
26044 @example
26045 f(x &&& a +/- b, x)  :=  g(x)
26046 @end example
26048 This does the same thing, but is arguably simpler than, the rule
26050 @example
26051 f(a +/- b, a +/- b)  :=  g(a +/- b)
26052 @end example
26054 @c @starindex
26055 @tindex ends
26056 Here's another interesting example:
26058 @example
26059 ends(cons(a, x) &&& rcons(y, b))  :=  [a, b]
26060 @end example
26062 @noindent
26063 which effectively clips out the middle of a vector leaving just
26064 the first and last elements.  This rule will change a one-element
26065 vector @samp{[a]} to @samp{[a, a]}.  The similar rule
26067 @example
26068 ends(cons(a, rcons(y, b)))  :=  [a, b]
26069 @end example
26071 @noindent
26072 would do the same thing except that it would fail to match a
26073 one-element vector.
26075 @tex
26076 \bigskip
26077 @end tex
26079 The pattern @samp{@var{p1} ||| @var{p2}} matches anything that
26080 matches either @var{p1} or @var{p2}.  Calc first tries matching
26081 against @var{p1}; if that fails, it goes on to try @var{p2}.
26083 @c @starindex
26084 @tindex curve
26085 A simple example of @samp{|||} is
26087 @example
26088 curve(inf ||| -inf)  :=  0
26089 @end example
26091 @noindent
26092 which converts both @samp{curve(inf)} and @samp{curve(-inf)} to zero.
26094 Here is a larger example:
26096 @example
26097 log(a, b) ||| (ln(a) :: let(b := e))  :=  mylog(a, b)
26098 @end example
26100 This matches both generalized and natural logarithms in a single rule.
26101 Note that the @samp{::} term must be enclosed in parentheses because
26102 that operator has lower precedence than @samp{|||} or @samp{:=}.
26104 (In practice this rule would probably include a third alternative,
26105 omitted here for brevity, to take care of @code{log10}.)
26107 While Calc generally treats interior conditions exactly the same as
26108 conditions on the outside of a rule, it does guarantee that if all the
26109 variables in the condition are special names like @code{e}, or already
26110 bound in the pattern to which the condition is attached (say, if
26111 @samp{a} had appeared in this condition), then Calc will process this
26112 condition right after matching the pattern to the left of the @samp{::}.
26113 Thus, we know that @samp{b} will be bound to @samp{e} only if the
26114 @code{ln} branch of the @samp{|||} was taken.
26116 Note that this rule was careful to bind the same set of meta-variables
26117 on both sides of the @samp{|||}.  Calc does not check this, but if
26118 you bind a certain meta-variable only in one branch and then use that
26119 meta-variable elsewhere in the rule, results are unpredictable:
26121 @example
26122 f(a,b) ||| g(b)  :=  h(a,b)
26123 @end example
26125 Here if the pattern matches @samp{g(17)}, Calc makes no promises about
26126 the value that will be substituted for @samp{a} on the righthand side.
26128 @tex
26129 \bigskip
26130 @end tex
26132 The pattern @samp{!!! @var{pat}} matches anything that does not
26133 match @var{pat}.  Any meta-variables that are bound while matching
26134 @var{pat} remain unbound outside of @var{pat}.
26136 For example,
26138 @example
26139 f(x &&& !!! a +/- b, !!![])  :=  g(x)
26140 @end example
26142 @noindent
26143 converts @code{f} whose first argument is anything @emph{except} an
26144 error form, and whose second argument is not the empty vector, into
26145 a similar call to @code{g} (but without the second argument).
26147 If we know that the second argument will be a vector (empty or not),
26148 then an equivalent rule would be:
26150 @example
26151 f(x, y)  :=  g(x)  :: typeof(x) != 7 :: vlen(y) > 0
26152 @end example
26154 @noindent
26155 where of course 7 is the @code{typeof} code for error forms.
26156 Another final condition, that works for any kind of @samp{y},
26157 would be @samp{!istrue(y == [])}.  (The @code{istrue} function
26158 returns an explicit 0 if its argument was left in symbolic form;
26159 plain @samp{!(y == [])} or @samp{y != []} would not work to replace
26160 @samp{!!![]} since these would be left unsimplified, and thus cause
26161 the rule to fail, if @samp{y} was something like a variable name.)
26163 It is possible for a @samp{!!!} to refer to meta-variables bound
26164 elsewhere in the pattern.  For example,
26166 @example
26167 f(a, !!!a)  :=  g(a)
26168 @end example
26170 @noindent
26171 matches any call to @code{f} with different arguments, changing
26172 this to @code{g} with only the first argument.
26174 If a function call is to be matched and one of the argument patterns
26175 contains a @samp{!!!} somewhere inside it, that argument will be
26176 matched last.  Thus
26178 @example
26179 f(!!!a, a)  :=  g(a)
26180 @end example
26182 @noindent
26183 will be careful to bind @samp{a} to the second argument of @code{f}
26184 before testing the first argument.  If Calc had tried to match the
26185 first argument of @code{f} first, the results would have been
26186 disasterous:  Since @code{a} was unbound so far, the pattern @samp{a}
26187 would have matched anything at all, and the pattern @samp{!!!a}
26188 therefore would @emph{not} have matched anything at all!
26190 @node Nested Formulas with Rewrite Rules, Multi-Phase Rewrite Rules, Composing Patterns in Rewrite Rules, Rewrite Rules
26191 @subsection Nested Formulas with Rewrite Rules
26193 @noindent
26194 When @kbd{a r} (@code{calc-rewrite}) is used, it takes an expression from
26195 the top of the stack and attempts to match any of the specified rules
26196 to any part of the expression, starting with the whole expression
26197 and then, if that fails, trying deeper and deeper sub-expressions.
26198 For each part of the expression, the rules are tried in the order
26199 they appear in the rules vector.  The first rule to match the first
26200 sub-expression wins; it replaces the matched sub-expression according
26201 to the @var{new} part of the rule.
26203 Often, the rule set will match and change the formula several times.
26204 The top-level formula is first matched and substituted repeatedly until
26205 it no longer matches the pattern; then, sub-formulas are tried, and
26206 so on.  Once every part of the formula has gotten its chance, the
26207 rewrite mechanism starts over again with the top-level formula
26208 (in case a substitution of one of its arguments has caused it again
26209 to match).  This continues until no further matches can be made
26210 anywhere in the formula.
26212 It is possible for a rule set to get into an infinite loop.  The
26213 most obvious case, replacing a formula with itself, is not a problem
26214 because a rule is not considered to ``succeed'' unless the righthand
26215 side actually comes out to something different than the original
26216 formula or sub-formula that was matched.  But if you accidentally
26217 had both @samp{ln(a b) := ln(a) + ln(b)} and the reverse
26218 @samp{ln(a) + ln(b) := ln(a b)} in your rule set, Calc would
26219 run forever switching a formula back and forth between the two
26220 forms.
26222 To avoid disaster, Calc normally stops after 100 changes have been
26223 made to the formula.  This will be enough for most multiple rewrites,
26224 but it will keep an endless loop of rewrites from locking up the
26225 computer forever.  (On most systems, you can also type @kbd{C-g} to
26226 halt any Emacs command prematurely.)
26228 To change this limit, give a positive numeric prefix argument.
26229 In particular, @kbd{M-1 a r} applies only one rewrite at a time,
26230 useful when you are first testing your rule (or just if repeated
26231 rewriting is not what is called for by your application).
26233 @c @starindex
26234 @c @mindex iter@idots
26235 @tindex iterations
26236 You can also put a ``function call'' @samp{iterations(@var{n})}
26237 in place of a rule anywhere in your rules vector (but usually at
26238 the top).  Then, @var{n} will be used instead of 100 as the default
26239 number of iterations for this rule set.  You can use
26240 @samp{iterations(inf)} if you want no iteration limit by default.
26241 A prefix argument will override the @code{iterations} limit in the
26242 rule set.
26244 @example
26245 [ iterations(1),
26246   f(x) := f(x+1) ]
26247 @end example
26249 More precisely, the limit controls the number of ``iterations,''
26250 where each iteration is a successful matching of a rule pattern whose
26251 righthand side, after substituting meta-variables and applying the
26252 default simplifications, is different from the original sub-formula
26253 that was matched.
26255 A prefix argument of zero sets the limit to infinity.  Use with caution!
26257 Given a negative numeric prefix argument, @kbd{a r} will match and
26258 substitute the top-level expression up to that many times, but
26259 will not attempt to match the rules to any sub-expressions.
26261 In a formula, @code{rewrite(@var{expr}, @var{rules}, @var{n})}
26262 does a rewriting operation.  Here @var{expr} is the expression
26263 being rewritten, @var{rules} is the rule, vector of rules, or
26264 variable containing the rules, and @var{n} is the optional
26265 iteration limit, which may be a positive integer, a negative
26266 integer, or @samp{inf} or @samp{-inf}.  If @var{n} is omitted
26267 the @code{iterations} value from the rule set is used; if both
26268 are omitted, 100 is used.
26270 @node Multi-Phase Rewrite Rules, Selections with Rewrite Rules, Nested Formulas with Rewrite Rules, Rewrite Rules
26271 @subsection Multi-Phase Rewrite Rules
26273 @noindent
26274 It is possible to separate a rewrite rule set into several @dfn{phases}.
26275 During each phase, certain rules will be enabled while certain others
26276 will be disabled.  A @dfn{phase schedule} controls the order in which
26277 phases occur during the rewriting process.
26279 @c @starindex
26280 @tindex phase
26281 @vindex all
26282 If a call to the marker function @code{phase} appears in the rules
26283 vector in place of a rule, all rules following that point will be
26284 members of the phase(s) identified in the arguments to @code{phase}.
26285 Phases are given integer numbers.  The markers @samp{phase()} and
26286 @samp{phase(all)} both mean the following rules belong to all phases;
26287 this is the default at the start of the rule set.
26289 If you do not explicitly schedule the phases, Calc sorts all phase
26290 numbers that appear in the rule set and executes the phases in
26291 ascending order.  For example, the rule set
26293 @group
26294 @example
26295 [ f0(x) := g0(x),
26296   phase(1),
26297   f1(x) := g1(x),
26298   phase(2),
26299   f2(x) := g2(x),
26300   phase(3),
26301   f3(x) := g3(x),
26302   phase(1,2),
26303   f4(x) := g4(x) ]
26304 @end example
26305 @end group
26307 @noindent
26308 has three phases, 1 through 3.  Phase 1 consists of the @code{f0},
26309 @code{f1}, and @code{f4} rules (in that order).  Phase 2 consists of
26310 @code{f0}, @code{f2}, and @code{f4}.  Phase 3 consists of @code{f0}
26311 and @code{f3}.
26313 When Calc rewrites a formula using this rule set, it first rewrites
26314 the formula using only the phase 1 rules until no further changes are
26315 possible.  Then it switches to the phase 2 rule set and continues
26316 until no further changes occur, then finally rewrites with phase 3.
26317 When no more phase 3 rules apply, rewriting finishes.  (This is
26318 assuming @kbd{a r} with a large enough prefix argument to allow the
26319 rewriting to run to completion; the sequence just described stops
26320 early if the number of iterations specified in the prefix argument,
26321 100 by default, is reached.)
26323 During each phase, Calc descends through the nested levels of the
26324 formula as described previously.  (@xref{Nested Formulas with Rewrite
26325 Rules}.)  Rewriting starts at the top of the formula, then works its
26326 way down to the parts, then goes back to the top and works down again.
26327 The phase 2 rules do not begin until no phase 1 rules apply anywhere
26328 in the formula.
26330 @c @starindex
26331 @tindex schedule
26332 A @code{schedule} marker appearing in the rule set (anywhere, but
26333 conventionally at the top) changes the default schedule of phases.
26334 In the simplest case, @code{schedule} has a sequence of phase numbers
26335 for arguments; each phase number is invoked in turn until the
26336 arguments to @code{schedule} are exhausted.  Thus adding
26337 @samp{schedule(3,2,1)} at the top of the above rule set would
26338 reverse the order of the phases; @samp{schedule(1,2,3)} would have
26339 no effect since this is the default schedule; and @samp{schedule(1,2,1,3)}
26340 would give phase 1 a second chance after phase 2 has completed, before
26341 moving on to phase 3.
26343 Any argument to @code{schedule} can instead be a vector of phase
26344 numbers (or even of sub-vectors).  Then the sub-sequence of phases
26345 described by the vector are tried repeatedly until no change occurs
26346 in any phase in the sequence.  For example, @samp{schedule([1, 2], 3)}
26347 tries phase 1, then phase 2, then, if either phase made any changes
26348 to the formula, repeats these two phases until they can make no
26349 further progress.  Finally, it goes on to phase 3 for finishing
26350 touches.
26352 Also, items in @code{schedule} can be variable names as well as
26353 numbers.  A variable name is interpreted as the name of a function
26354 to call on the whole formula.  For example, @samp{schedule(1, simplify)}
26355 says to apply the phase-1 rules (presumably, all of them), then to
26356 call @code{simplify} which is the function name equivalent of @kbd{a s}.
26357 Likewise, @samp{schedule([1, simplify])} says to alternate between
26358 phase 1 and @kbd{a s} until no further changes occur.
26360 Phases can be used purely to improve efficiency; if it is known that
26361 a certain group of rules will apply only at the beginning of rewriting,
26362 and a certain other group will apply only at the end, then rewriting
26363 will be faster if these groups are identified as separate phases.
26364 Once the phase 1 rules are done, Calc can put them aside and no longer
26365 spend any time on them while it works on phase 2.
26367 There are also some problems that can only be solved with several
26368 rewrite phases.  For a real-world example of a multi-phase rule set,
26369 examine the set @code{FitRules}, which is used by the curve-fitting
26370 command to convert a model expression to linear form.
26371 @xref{Curve Fitting Details}.  This set is divided into four phases.
26372 The first phase rewrites certain kinds of expressions to be more
26373 easily linearizable, but less computationally efficient.  After the
26374 linear components have been picked out, the final phase includes the
26375 opposite rewrites to put each component back into an efficient form.
26376 If both sets of rules were included in one big phase, Calc could get
26377 into an infinite loop going back and forth between the two forms.
26379 Elsewhere in @code{FitRules}, the components are first isolated,
26380 then recombined where possible to reduce the complexity of the linear
26381 fit, then finally packaged one component at a time into vectors.
26382 If the packaging rules were allowed to begin before the recombining
26383 rules were finished, some components might be put away into vectors
26384 before they had a chance to recombine.  By putting these rules in
26385 two separate phases, this problem is neatly avoided.
26387 @node Selections with Rewrite Rules, Matching Commands, Multi-Phase Rewrite Rules, Rewrite Rules
26388 @subsection Selections with Rewrite Rules
26390 @noindent
26391 If a sub-formula of the current formula is selected (as by @kbd{j s};
26392 @pxref{Selecting Subformulas}), the @kbd{a r} (@code{calc-rewrite})
26393 command applies only to that sub-formula.  Together with a negative
26394 prefix argument, you can use this fact to apply a rewrite to one
26395 specific part of a formula without affecting any other parts.
26397 @kindex j r
26398 @pindex calc-rewrite-selection
26399 The @kbd{j r} (@code{calc-rewrite-selection}) command allows more
26400 sophisticated operations on selections.  This command prompts for
26401 the rules in the same way as @kbd{a r}, but it then applies those
26402 rules to the whole formula in question even though a sub-formula
26403 of it has been selected.  However, the selected sub-formula will
26404 first have been surrounded by a @samp{select( )} function call.
26405 (Calc's evaluator does not understand the function name @code{select};
26406 this is only a tag used by the @kbd{j r} command.)
26408 For example, suppose the formula on the stack is @samp{2 (a + b)^2}
26409 and the sub-formula @samp{a + b} is selected.  This formula will
26410 be rewritten to @samp{2 select(a + b)^2} and then the rewrite
26411 rules will be applied in the usual way.  The rewrite rules can
26412 include references to @code{select} to tell where in the pattern
26413 the selected sub-formula should appear.
26415 If there is still exactly one @samp{select( )} function call in
26416 the formula after rewriting is done, it indicates which part of
26417 the formula should be selected afterwards.  Otherwise, the
26418 formula will be unselected.
26420 You can make @kbd{j r} act much like @kbd{a r} by enclosing both parts
26421 of the rewrite rule with @samp{select()}.  However, @kbd{j r}
26422 allows you to use the current selection in more flexible ways.
26423 Suppose you wished to make a rule which removed the exponent from
26424 the selected term; the rule @samp{select(a)^x := select(a)} would
26425 work.  In the above example, it would rewrite @samp{2 select(a + b)^2}
26426 to @samp{2 select(a + b)}.  This would then be returned to the
26427 stack as @samp{2 (a + b)} with the @samp{a + b} selected.
26429 The @kbd{j r} command uses one iteration by default, unlike
26430 @kbd{a r} which defaults to 100 iterations.  A numeric prefix
26431 argument affects @kbd{j r} in the same way as @kbd{a r}.
26432 @xref{Nested Formulas with Rewrite Rules}.
26434 As with other selection commands, @kbd{j r} operates on the stack
26435 entry that contains the cursor.  (If the cursor is on the top-of-stack
26436 @samp{.} marker, it works as if the cursor were on the formula
26437 at stack level 1.)
26439 If you don't specify a set of rules, the rules are taken from the
26440 top of the stack, just as with @kbd{a r}.  In this case, the
26441 cursor must indicate stack entry 2 or above as the formula to be
26442 rewritten (otherwise the same formula would be used as both the
26443 target and the rewrite rules).
26445 If the indicated formula has no selection, the cursor position within
26446 the formula temporarily selects a sub-formula for the purposes of this
26447 command.  If the cursor is not on any sub-formula (e.g., it is in
26448 the line-number area to the left of the formula), the @samp{select( )}
26449 markers are ignored by the rewrite mechanism and the rules are allowed
26450 to apply anywhere in the formula.
26452 As a special feature, the normal @kbd{a r} command also ignores
26453 @samp{select( )} calls in rewrite rules.  For example, if you used the
26454 above rule @samp{select(a)^x := select(a)} with @kbd{a r}, it would apply
26455 the rule as if it were @samp{a^x := a}.  Thus, you can write general
26456 purpose rules with @samp{select( )} hints inside them so that they
26457 will ``do the right thing'' in both @kbd{a r} and @kbd{j r},
26458 both with and without selections.
26460 @node Matching Commands, Automatic Rewrites, Selections with Rewrite Rules, Rewrite Rules
26461 @subsection Matching Commands
26463 @noindent
26464 @kindex a m
26465 @pindex calc-match
26466 @tindex match
26467 The @kbd{a m} (@code{calc-match}) [@code{match}] function takes a
26468 vector of formulas and a rewrite-rule-style pattern, and produces
26469 a vector of all formulas which match the pattern.  The command
26470 prompts you to enter the pattern; as for @kbd{a r}, you can enter
26471 a single pattern (i.e., a formula with meta-variables), or a
26472 vector of patterns, or a variable which contains patterns, or
26473 you can give a blank response in which case the patterns are taken
26474 from the top of the stack.  The pattern set will be compiled once
26475 and saved if it is stored in a variable.  If there are several
26476 patterns in the set, vector elements are kept if they match any
26477 of the patterns.
26479 For example, @samp{match(a+b, [x, x+y, x-y, 7, x+y+z])}
26480 will return @samp{[x+y, x-y, x+y+z]}.
26482 The @code{import} mechanism is not available for pattern sets.
26484 The @kbd{a m} command can also be used to extract all vector elements
26485 which satisfy any condition:  The pattern @samp{x :: x>0} will select
26486 all the positive vector elements.
26488 @kindex I a m
26489 @tindex matchnot
26490 With the Inverse flag [@code{matchnot}], this command extracts all
26491 vector elements which do @emph{not} match the given pattern.
26493 @c @starindex
26494 @tindex matches
26495 There is also a function @samp{matches(@var{x}, @var{p})} which
26496 evaluates to 1 if expression @var{x} matches pattern @var{p}, or
26497 to 0 otherwise.  This is sometimes useful for including into the
26498 conditional clauses of other rewrite rules.
26500 @c @starindex
26501 @tindex vmatches
26502 The function @code{vmatches} is just like @code{matches}, except
26503 that if the match succeeds it returns a vector of assignments to
26504 the meta-variables instead of the number 1.  For example,
26505 @samp{vmatches(f(1,2), f(a,b))} returns @samp{[a := 1, b := 2]}.
26506 If the match fails, the function returns the number 0.
26508 @node Automatic Rewrites, Debugging Rewrites, Matching Commands, Rewrite Rules
26509 @subsection Automatic Rewrites
26511 @noindent
26512 @cindex @code{EvalRules} variable
26513 @vindex EvalRules
26514 It is possible to get Calc to apply a set of rewrite rules on all
26515 results, effectively adding to the built-in set of default
26516 simplifications.  To do this, simply store your rule set in the
26517 variable @code{EvalRules}.  There is a convenient @kbd{s E} command
26518 for editing @code{EvalRules}; @pxref{Operations on Variables}.
26520 For example, suppose you want @samp{sin(a + b)} to be expanded out
26521 to @samp{sin(b) cos(a) + cos(b) sin(a)} wherever it appears, and
26522 similarly for @samp{cos(a + b)}.  The corresponding rewrite rule
26523 set would be,
26525 @group
26526 @smallexample
26527 [ sin(a + b)  :=  cos(a) sin(b) + sin(a) cos(b),
26528   cos(a + b)  :=  cos(a) cos(b) - sin(a) sin(b) ]
26529 @end smallexample
26530 @end group
26532 To apply these manually, you could put them in a variable called
26533 @code{trigexp} and then use @kbd{a r trigexp} every time you wanted
26534 to expand trig functions.  But if instead you store them in the
26535 variable @code{EvalRules}, they will automatically be applied to all
26536 sines and cosines of sums.  Then, with @samp{2 x} and @samp{45} on
26537 the stack, typing @kbd{+ S} will (assuming degrees mode) result in
26538 @samp{0.7071 sin(2 x) + 0.7071 cos(2 x)} automatically.
26540 As each level of a formula is evaluated, the rules from
26541 @code{EvalRules} are applied before the default simplifications.
26542 Rewriting continues until no further @code{EvalRules} apply.
26543 Note that this is different from the usual order of application of
26544 rewrite rules:  @code{EvalRules} works from the bottom up, simplifying
26545 the arguments to a function before the function itself, while @kbd{a r}
26546 applies rules from the top down.
26548 Because the @code{EvalRules} are tried first, you can use them to
26549 override the normal behavior of any built-in Calc function.
26551 It is important not to write a rule that will get into an infinite
26552 loop.  For example, the rule set @samp{[f(0) := 1, f(n) := n f(n-1)]}
26553 appears to be a good definition of a factorial function, but it is
26554 unsafe.  Imagine what happens if @samp{f(2.5)} is simplified.  Calc
26555 will continue to subtract 1 from this argument forever without reaching
26556 zero.  A safer second rule would be @samp{f(n) := n f(n-1) :: n>0}.
26557 Another dangerous rule is @samp{g(x, y) := g(y, x)}.  Rewriting
26558 @samp{g(2, 4)}, this would bounce back and forth between that and
26559 @samp{g(4, 2)} forever.  If an infinite loop in @code{EvalRules}
26560 occurs, Emacs will eventually stop with a ``Computation got stuck
26561 or ran too long'' message.
26563 Another subtle difference between @code{EvalRules} and regular rewrites
26564 concerns rules that rewrite a formula into an identical formula.  For
26565 example, @samp{f(n) := f(floor(n))} ``fails to match'' when @cite{n} is
26566 already an integer.  But in @code{EvalRules} this case is detected only
26567 if the righthand side literally becomes the original formula before any
26568 further simplification.  This means that @samp{f(n) := f(floor(n))} will
26569 get into an infinite loop if it occurs in @code{EvalRules}.  Calc will
26570 replace @samp{f(6)} with @samp{f(floor(6))}, which is different from
26571 @samp{f(6)}, so it will consider the rule to have matched and will
26572 continue simplifying that formula; first the argument is simplified
26573 to get @samp{f(6)}, then the rule matches again to get @samp{f(floor(6))}
26574 again, ad infinitum.  A much safer rule would check its argument first,
26575 say, with @samp{f(n) := f(floor(n)) :: !dint(n)}.
26577 (What really happens is that the rewrite mechanism substitutes the
26578 meta-variables in the righthand side of a rule, compares to see if the
26579 result is the same as the original formula and fails if so, then uses
26580 the default simplifications to simplify the result and compares again
26581 (and again fails if the formula has simplified back to its original
26582 form).  The only special wrinkle for the @code{EvalRules} is that the
26583 same rules will come back into play when the default simplifications
26584 are used.  What Calc wants to do is build @samp{f(floor(6))}, see that
26585 this is different from the original formula, simplify to @samp{f(6)},
26586 see that this is the same as the original formula, and thus halt the
26587 rewriting.  But while simplifying, @samp{f(6)} will again trigger
26588 the same @code{EvalRules} rule and Calc will get into a loop inside
26589 the rewrite mechanism itself.)
26591 The @code{phase}, @code{schedule}, and @code{iterations} markers do
26592 not work in @code{EvalRules}.  If the rule set is divided into phases,
26593 only the phase 1 rules are applied, and the schedule is ignored.
26594 The rules are always repeated as many times as possible.
26596 The @code{EvalRules} are applied to all function calls in a formula,
26597 but not to numbers (and other number-like objects like error forms),
26598 nor to vectors or individual variable names.  (Though they will apply
26599 to @emph{components} of vectors and error forms when appropriate.)  You
26600 might try to make a variable @code{phihat} which automatically expands
26601 to its definition without the need to press @kbd{=} by writing the
26602 rule @samp{quote(phihat) := (1-sqrt(5))/2}, but unfortunately this rule
26603 will not work as part of @code{EvalRules}.
26605 Finally, another limitation is that Calc sometimes calls its built-in
26606 functions directly rather than going through the default simplifications.
26607 When it does this, @code{EvalRules} will not be able to override those
26608 functions.  For example, when you take the absolute value of the complex
26609 number @cite{(2, 3)}, Calc computes @samp{sqrt(2*2 + 3*3)} by calling
26610 the multiplication, addition, and square root functions directly rather
26611 than applying the default simplifications to this formula.  So an
26612 @code{EvalRules} rule that (perversely) rewrites @samp{sqrt(13) := 6}
26613 would not apply.  (However, if you put Calc into symbolic mode so that
26614 @samp{sqrt(13)} will be left in symbolic form by the built-in square
26615 root function, your rule will be able to apply.  But if the complex
26616 number were @cite{(3,4)}, so that @samp{sqrt(25)} must be calculated,
26617 then symbolic mode will not help because @samp{sqrt(25)} can be
26618 evaluated exactly to 5.)
26620 One subtle restriction that normally only manifests itself with
26621 @code{EvalRules} is that while a given rewrite rule is in the process
26622 of being checked, that same rule cannot be recursively applied.  Calc
26623 effectively removes the rule from its rule set while checking the rule,
26624 then puts it back once the match succeeds or fails.  (The technical
26625 reason for this is that compiled pattern programs are not reentrant.)
26626 For example, consider the rule @samp{foo(x) := x :: foo(x/2) > 0}
26627 attempting to match @samp{foo(8)}.  This rule will be inactive while
26628 the condition @samp{foo(4) > 0} is checked, even though it might be
26629 an integral part of evaluating that condition.  Note that this is not
26630 a problem for the more usual recursive type of rule, such as
26631 @samp{foo(x) := foo(x/2)}, because there the rule has succeeded and
26632 been reactivated by the time the righthand side is evaluated.
26634 If @code{EvalRules} has no stored value (its default state), or if
26635 anything but a vector is stored in it, then it is ignored.
26637 Even though Calc's rewrite mechanism is designed to compare rewrite
26638 rules to formulas as quickly as possible, storing rules in
26639 @code{EvalRules} may make Calc run substantially slower.  This is
26640 particularly true of rules where the top-level call is a commonly used
26641 function, or is not fixed.  The rule @samp{f(n) := n f(n-1) :: n>0} will
26642 only activate the rewrite mechanism for calls to the function @code{f},
26643 but @samp{lg(n) + lg(m) := lg(n m)} will check every @samp{+} operator.
26644 And @samp{apply(f, [a*b]) := apply(f, [a]) + apply(f, [b]) ::
26645 in(f, [ln, log10])} may seem more ``efficient'' than two separate
26646 rules for @code{ln} and @code{log10}, but actually it is vastly less
26647 efficient because rules with @code{apply} as the top-level pattern
26648 must be tested against @emph{every} function call that is simplified.
26650 @cindex @code{AlgSimpRules} variable
26651 @vindex AlgSimpRules
26652 Suppose you want @samp{sin(a + b)} to be expanded out not all the time,
26653 but only when @kbd{a s} is used to simplify the formula.  The variable
26654 @code{AlgSimpRules} holds rules for this purpose.  The @kbd{a s} command
26655 will apply @code{EvalRules} and @code{AlgSimpRules} to the formula, as
26656 well as all of its built-in simplifications.
26658 Most of the special limitations for @code{EvalRules} don't apply to
26659 @code{AlgSimpRules}.  Calc simply does an @kbd{a r AlgSimpRules}
26660 command with an infinite repeat count as the first step of @kbd{a s}.
26661 It then applies its own built-in simplifications throughout the
26662 formula, and then repeats these two steps (along with applying the
26663 default simplifications) until no further changes are possible.
26665 @cindex @code{ExtSimpRules} variable
26666 @cindex @code{UnitSimpRules} variable
26667 @vindex ExtSimpRules
26668 @vindex UnitSimpRules
26669 There are also @code{ExtSimpRules} and @code{UnitSimpRules} variables
26670 that are used by @kbd{a e} and @kbd{u s}, respectively; these commands
26671 also apply @code{EvalRules} and @code{AlgSimpRules}.  The variable
26672 @code{IntegSimpRules} contains simplification rules that are used
26673 only during integration by @kbd{a i}.
26675 @node Debugging Rewrites, Examples of Rewrite Rules, Automatic Rewrites, Rewrite Rules
26676 @subsection Debugging Rewrites
26678 @noindent
26679 If a buffer named @samp{*Trace*} exists, the rewrite mechanism will
26680 record some useful information there as it operates.  The original
26681 formula is written there, as is the result of each successful rewrite,
26682 and the final result of the rewriting.  All phase changes are also
26683 noted.
26685 Calc always appends to @samp{*Trace*}.  You must empty this buffer
26686 yourself periodically if it is in danger of growing unwieldy.
26688 Note that the rewriting mechanism is substantially slower when the
26689 @samp{*Trace*} buffer exists, even if the buffer is not visible on
26690 the screen.  Once you are done, you will probably want to kill this
26691 buffer (with @kbd{C-x k *Trace* @key{RET}}).  If you leave it in
26692 existence and forget about it, all your future rewrite commands will
26693 be needlessly slow.
26695 @node Examples of Rewrite Rules, , Debugging Rewrites, Rewrite Rules
26696 @subsection Examples of Rewrite Rules
26698 @noindent
26699 Returning to the example of substituting the pattern
26700 @samp{sin(x)^2 + cos(x)^2} with 1, we saw that the rule
26701 @samp{opt(a) sin(x)^2 + opt(a) cos(x)^2 := a} does a good job of
26702 finding suitable cases.  Another solution would be to use the rule
26703 @samp{cos(x)^2 := 1 - sin(x)^2}, followed by algebraic simplification
26704 if necessary.  This rule will be the most effective way to do the job,
26705 but at the expense of making some changes that you might not desire.@refill
26707 Another algebraic rewrite rule is @samp{exp(x+y) := exp(x) exp(y)}.
26708 To make this work with the @w{@kbd{j r}} command so that it can be
26709 easily targeted to a particular exponential in a large formula,
26710 you might wish to write the rule as @samp{select(exp(x+y)) :=
26711 select(exp(x) exp(y))}.  The @samp{select} markers will be
26712 ignored by the regular @kbd{a r} command
26713 (@pxref{Selections with Rewrite Rules}).@refill
26715 A surprisingly useful rewrite rule is @samp{a/(b-c) := a*(b+c)/(b^2-c^2)}.
26716 This will simplify the formula whenever @cite{b} and/or @cite{c} can
26717 be made simpler by squaring.  For example, applying this rule to
26718 @samp{2 / (sqrt(2) + 3)} yields @samp{6:7 - 2:7 sqrt(2)} (assuming
26719 Symbolic Mode has been enabled to keep the square root from being
26720 evaulated to a floating-point approximation).  This rule is also
26721 useful when working with symbolic complex numbers, e.g.,
26722 @samp{(a + b i) / (c + d i)}.
26724 As another example, we could define our own ``triangular numbers'' function
26725 with the rules @samp{[tri(0) := 0, tri(n) := n + tri(n-1) :: n>0]}.  Enter
26726 this vector and store it in a variable:  @kbd{@w{s t} trirules}.  Now, given
26727 a suitable formula like @samp{tri(5)} on the stack, type @samp{a r trirules}
26728 to apply these rules repeatedly.  After six applications, @kbd{a r} will
26729 stop with 15 on the stack.  Once these rules are debugged, it would probably
26730 be most useful to add them to @code{EvalRules} so that Calc will evaluate
26731 the new @code{tri} function automatically.  We could then use @kbd{Z K} on
26732 the keyboard macro @kbd{' tri($) RET} to make a command that applies
26733 @code{tri} to the value on the top of the stack.  @xref{Programming}.
26735 @cindex Quaternions
26736 The following rule set, contributed by @c{Fran\c cois}
26737 @asis{Francois} Pinard, implements
26738 @dfn{quaternions}, a generalization of the concept of complex numbers.
26739 Quaternions have four components, and are here represented by function
26740 calls @samp{quat(@var{w}, [@var{x}, @var{y}, @var{z}])} with ``real
26741 part'' @var{w} and the three ``imaginary'' parts collected into a
26742 vector.  Various arithmetical operations on quaternions are supported.
26743 To use these rules, either add them to @code{EvalRules}, or create a
26744 command based on @kbd{a r} for simplifying quaternion formulas.
26745 A convenient way to enter quaternions would be a command defined by
26746 a keyboard macro containing: @kbd{' quat($$$$, [$$$, $$, $]) @key{RET}}.
26748 @smallexample
26749 [ quat(w, x, y, z) := quat(w, [x, y, z]),
26750   quat(w, [0, 0, 0]) := w,
26751   abs(quat(w, v)) := hypot(w, v),
26752   -quat(w, v) := quat(-w, -v),
26753   r + quat(w, v) := quat(r + w, v) :: real(r),
26754   r - quat(w, v) := quat(r - w, -v) :: real(r),
26755   quat(w1, v1) + quat(w2, v2) := quat(w1 + w2, v1 + v2),
26756   r * quat(w, v) := quat(r * w, r * v) :: real(r),
26757   plain(quat(w1, v1) * quat(w2, v2))
26758      := quat(w1 * w2 - v1 * v2, w1 * v2 + w2 * v1 + cross(v1, v2)),
26759   quat(w1, v1) / r := quat(w1 / r, v1 / r) :: real(r),
26760   z / quat(w, v) := z * quatinv(quat(w, v)),
26761   quatinv(quat(w, v)) := quat(w, -v) / (w^2 + v^2),
26762   quatsqr(quat(w, v)) := quat(w^2 - v^2, 2 * w * v),
26763   quat(w, v)^k := quatsqr(quat(w, v)^(k / 2))
26764                :: integer(k) :: k > 0 :: k % 2 = 0,
26765   quat(w, v)^k := quatsqr(quat(w, v)^((k - 1) / 2)) * quat(w, v)
26766                :: integer(k) :: k > 2,
26767   quat(w, v)^-k := quatinv(quat(w, v)^k) :: integer(k) :: k > 0 ]
26768 @end smallexample
26770 Quaternions, like matrices, have non-commutative multiplication.
26771 In other words, @cite{q1 * q2 = q2 * q1} is not necessarily true if
26772 @cite{q1} and @cite{q2} are @code{quat} forms.  The @samp{quat*quat}
26773 rule above uses @code{plain} to prevent Calc from rearranging the
26774 product.  It may also be wise to add the line @samp{[quat(), matrix]}
26775 to the @code{Decls} matrix, to ensure that Calc's other algebraic
26776 operations will not rearrange a quaternion product.  @xref{Declarations}.
26778 These rules also accept a four-argument @code{quat} form, converting
26779 it to the preferred form in the first rule.  If you would rather see
26780 results in the four-argument form, just append the two items
26781 @samp{phase(2), quat(w, [x, y, z]) := quat(w, x, y, z)} to the end
26782 of the rule set.  (But remember that multi-phase rule sets don't work
26783 in @code{EvalRules}.)
26785 @node Units, Store and Recall, Algebra, Top
26786 @chapter Operating on Units
26788 @noindent
26789 One special interpretation of algebraic formulas is as numbers with units.
26790 For example, the formula @samp{5 m / s^2} can be read ``five meters
26791 per second squared.''  The commands in this chapter help you
26792 manipulate units expressions in this form.  Units-related commands
26793 begin with the @kbd{u} prefix key.
26795 @menu
26796 * Basic Operations on Units::
26797 * The Units Table::
26798 * Predefined Units::
26799 * User-Defined Units::
26800 @end menu
26802 @node Basic Operations on Units, The Units Table, Units, Units
26803 @section Basic Operations on Units
26805 @noindent
26806 A @dfn{units expression} is a formula which is basically a number
26807 multiplied and/or divided by one or more @dfn{unit names}, which may
26808 optionally be raised to integer powers.  Actually, the value part need not
26809 be a number; any product or quotient involving unit names is a units
26810 expression.  Many of the units commands will also accept any formula,
26811 where the command applies to all units expressions which appear in the
26812 formula.
26814 A unit name is a variable whose name appears in the @dfn{unit table},
26815 or a variable whose name is a prefix character like @samp{k} (for ``kilo'')
26816 or @samp{u} (for ``micro'') followed by a name in the unit table.
26817 A substantial table of built-in units is provided with Calc;
26818 @pxref{Predefined Units}.  You can also define your own unit names;
26819 @pxref{User-Defined Units}.@refill
26821 Note that if the value part of a units expression is exactly @samp{1},
26822 it will be removed by the Calculator's automatic algebra routines:  The
26823 formula @samp{1 mm} is ``simplified'' to @samp{mm}.  This is only a
26824 display anomaly, however; @samp{mm} will work just fine as a
26825 representation of one millimeter.@refill
26827 You may find that Algebraic Mode (@pxref{Algebraic Entry}) makes working
26828 with units expressions easier.  Otherwise, you will have to remember
26829 to hit the apostrophe key every time you wish to enter units.
26831 @kindex u s
26832 @pindex calc-simplify-units
26833 @c @mindex usimpl@idots
26834 @tindex usimplify
26835 The @kbd{u s} (@code{calc-simplify-units}) [@code{usimplify}] command
26836 simplifies a units
26837 expression.  It uses @kbd{a s} (@code{calc-simplify}) to simplify the
26838 expression first as a regular algebraic formula; it then looks for
26839 features that can be further simplified by converting one object's units
26840 to be compatible with another's.  For example, @samp{5 m + 23 mm} will
26841 simplify to @samp{5.023 m}.  When different but compatible units are
26842 added, the righthand term's units are converted to match those of the
26843 lefthand term.  @xref{Simplification Modes}, for a way to have this done
26844 automatically at all times.@refill
26846 Units simplification also handles quotients of two units with the same
26847 dimensionality, as in @w{@samp{2 in s/L cm}} to @samp{5.08 s/L}; fractional
26848 powers of unit expressions, as in @samp{sqrt(9 mm^2)} to @samp{3 mm} and
26849 @samp{sqrt(9 acre)} to a quantity in meters; and @code{floor},
26850 @code{ceil}, @code{round}, @code{rounde}, @code{roundu}, @code{trunc},
26851 @code{float}, @code{frac}, @code{abs}, and @code{clean}
26852 applied to units expressions, in which case
26853 the operation in question is applied only to the numeric part of the
26854 expression.  Finally, trigonometric functions of quantities with units
26855 of angle are evaluated, regardless of the current angular mode.@refill
26857 @kindex u c
26858 @pindex calc-convert-units
26859 The @kbd{u c} (@code{calc-convert-units}) command converts a units
26860 expression to new, compatible units.  For example, given the units
26861 expression @samp{55 mph}, typing @kbd{u c m/s @key{RET}} produces
26862 @samp{24.5872 m/s}.  If the units you request are inconsistent with
26863 the original units, the number will be converted into your units
26864 times whatever ``remainder'' units are left over.  For example,
26865 converting @samp{55 mph} into acres produces @samp{6.08e-3 acre / m s}.
26866 (Recall that multiplication binds more strongly than division in Calc
26867 formulas, so the units here are acres per meter-second.)  Remainder
26868 units are expressed in terms of ``fundamental'' units like @samp{m} and
26869 @samp{s}, regardless of the input units.
26871 One special exception is that if you specify a single unit name, and
26872 a compatible unit appears somewhere in the units expression, then
26873 that compatible unit will be converted to the new unit and the
26874 remaining units in the expression will be left alone.  For example,
26875 given the input @samp{980 cm/s^2}, the command @kbd{u c ms} will
26876 change the @samp{s} to @samp{ms} to get @samp{9.8e-4 cm/ms^2}.
26877 The ``remainder unit'' @samp{cm} is left alone rather than being
26878 changed to the base unit @samp{m}.
26880 You can use explicit unit conversion instead of the @kbd{u s} command
26881 to gain more control over the units of the result of an expression.
26882 For example, given @samp{5 m + 23 mm}, you can type @kbd{u c m} or
26883 @kbd{u c mm} to express the result in either meters or millimeters.
26884 (For that matter, you could type @kbd{u c fath} to express the result
26885 in fathoms, if you preferred!)
26887 In place of a specific set of units, you can also enter one of the
26888 units system names @code{si}, @code{mks} (equivalent), or @code{cgs}.
26889 For example, @kbd{u c si @key{RET}} converts the expression into
26890 International System of Units (SI) base units.  Also, @kbd{u c base}
26891 converts to Calc's base units, which are the same as @code{si} units
26892 except that @code{base} uses @samp{g} as the fundamental unit of mass
26893 whereas @code{si} uses @samp{kg}.
26895 @cindex Composite units
26896 The @kbd{u c} command also accepts @dfn{composite units}, which
26897 are expressed as the sum of several compatible unit names.  For
26898 example, converting @samp{30.5 in} to units @samp{mi+ft+in} (miles,
26899 feet, and inches) produces @samp{2 ft + 6.5 in}.  Calc first
26900 sorts the unit names into order of decreasing relative size.
26901 It then accounts for as much of the input quantity as it can
26902 using an integer number times the largest unit, then moves on
26903 to the next smaller unit, and so on.  Only the smallest unit
26904 may have a non-integer amount attached in the result.  A few
26905 standard unit names exist for common combinations, such as
26906 @code{mfi} for @samp{mi+ft+in}, and @code{tpo} for @samp{ton+lb+oz}.
26907 Composite units are expanded as if by @kbd{a x}, so that
26908 @samp{(ft+in)/hr} is first converted to @samp{ft/hr+in/hr}.
26910 If the value on the stack does not contain any units, @kbd{u c} will
26911 prompt first for the old units which this value should be considered
26912 to have, then for the new units.  Assuming the old and new units you
26913 give are consistent with each other, the result also will not contain
26914 any units.  For example, @kbd{@w{u c} cm RET in RET} converts the number
26915 2 on the stack to 5.08.
26917 @kindex u b
26918 @pindex calc-base-units
26919 The @kbd{u b} (@code{calc-base-units}) command is shorthand for
26920 @kbd{u c base}; it converts the units expression on the top of the
26921 stack into @code{base} units.  If @kbd{u s} does not simplify a
26922 units expression as far as you would like, try @kbd{u b}.
26924 The @kbd{u c} and @kbd{u b} commands treat temperature units (like
26925 @samp{degC} and @samp{K}) as relative temperatures.  For example,
26926 @kbd{u c} converts @samp{10 degC} to @samp{18 degF}: A change of 10
26927 degrees Celsius corresponds to a change of 18 degrees Fahrenheit.
26929 @kindex u t
26930 @pindex calc-convert-temperature
26931 @cindex Temperature conversion
26932 The @kbd{u t} (@code{calc-convert-temperature}) command converts
26933 absolute temperatures.  The value on the stack must be a simple units
26934 expression with units of temperature only.  This command would convert
26935 @samp{10 degC} to @samp{50 degF}, the equivalent temperature on the
26936 Fahrenheit scale.@refill
26938 @kindex u r
26939 @pindex calc-remove-units
26940 @kindex u x
26941 @pindex calc-extract-units
26942 The @kbd{u r} (@code{calc-remove-units}) command removes units from the
26943 formula at the top of the stack.  The @kbd{u x}
26944 (@code{calc-extract-units}) command extracts only the units portion of a
26945 formula.  These commands essentially replace every term of the formula
26946 that does or doesn't (respectively) look like a unit name by the
26947 constant 1, then resimplify the formula.@refill
26949 @kindex u a
26950 @pindex calc-autorange-units
26951 The @kbd{u a} (@code{calc-autorange-units}) command turns on and off a
26952 mode in which unit prefixes like @code{k} (``kilo'') are automatically
26953 applied to keep the numeric part of a units expression in a reasonable
26954 range.  This mode affects @kbd{u s} and all units conversion commands
26955 except @kbd{u b}.  For example, with autoranging on, @samp{12345 Hz}
26956 will be simplified to @samp{12.345 kHz}.  Autoranging is useful for
26957 some kinds of units (like @code{Hz} and @code{m}), but is probably
26958 undesirable for non-metric units like @code{ft} and @code{tbsp}.
26959 (Composite units are more appropriate for those; see above.)
26961 Autoranging always applies the prefix to the leftmost unit name.
26962 Calc chooses the largest prefix that causes the number to be greater
26963 than or equal to 1.0.  Thus an increasing sequence of adjusted times
26964 would be @samp{1 ms, 10 ms, 100 ms, 1 s, 10 s, 100 s, 1 ks}.
26965 Generally the rule of thumb is that the number will be adjusted
26966 to be in the interval @samp{[1 .. 1000)}, although there are several
26967 exceptions to this rule.  First, if the unit has a power then this
26968 is not possible; @samp{0.1 s^2} simplifies to @samp{100000 ms^2}.
26969 Second, the ``centi-'' prefix is allowed to form @code{cm} (centimeters),
26970 but will not apply to other units.  The ``deci-,'' ``deka-,'' and
26971 ``hecto-'' prefixes are never used.  Thus the allowable interval is
26972 @samp{[1 .. 10)} for millimeters and @samp{[1 .. 100)} for centimeters.
26973 Finally, a prefix will not be added to a unit if the resulting name
26974 is also the actual name of another unit; @samp{1e-15 t} would normally
26975 be considered a ``femto-ton,'' but it is written as @samp{1000 at}
26976 (1000 atto-tons) instead because @code{ft} would be confused with feet.
26978 @node The Units Table, Predefined Units, Basic Operations on Units, Units
26979 @section The Units Table
26981 @noindent
26982 @kindex u v
26983 @pindex calc-enter-units-table
26984 The @kbd{u v} (@code{calc-enter-units-table}) command displays the units table
26985 in another buffer called @code{*Units Table*}.  Each entry in this table
26986 gives the unit name as it would appear in an expression, the definition
26987 of the unit in terms of simpler units, and a full name or description of
26988 the unit.  Fundamental units are defined as themselves; these are the
26989 units produced by the @kbd{u b} command.  The fundamental units are
26990 meters, seconds, grams, kelvins, amperes, candelas, moles, radians,
26991 and steradians.
26993 The Units Table buffer also displays the Unit Prefix Table.  Note that
26994 two prefixes, ``kilo'' and ``hecto,'' accept either upper- or lower-case
26995 prefix letters.  @samp{Meg} is also accepted as a synonym for the @samp{M}
26996 prefix.  Whenever a unit name can be interpreted as either a built-in name
26997 or a prefix followed by another built-in name, the former interpretation
26998 wins.  For example, @samp{2 pt} means two pints, not two pico-tons.
27000 The Units Table buffer, once created, is not rebuilt unless you define
27001 new units.  To force the buffer to be rebuilt, give any numeric prefix
27002 argument to @kbd{u v}.
27004 @kindex u V
27005 @pindex calc-view-units-table
27006 The @kbd{u V} (@code{calc-view-units-table}) command is like @kbd{u v} except
27007 that the cursor is not moved into the Units Table buffer.  You can
27008 type @kbd{u V} again to remove the Units Table from the display.  To
27009 return from the Units Table buffer after a @kbd{u v}, type @kbd{M-# c}
27010 again or use the regular Emacs @w{@kbd{C-x o}} (@code{other-window})
27011 command.  You can also kill the buffer with @kbd{C-x k} if you wish;
27012 the actual units table is safely stored inside the Calculator.
27014 @kindex u g
27015 @pindex calc-get-unit-definition
27016 The @kbd{u g} (@code{calc-get-unit-definition}) command retrieves a unit's
27017 defining expression and pushes it onto the Calculator stack.  For example,
27018 @kbd{u g in} will produce the expression @samp{2.54 cm}.  This is the
27019 same definition for the unit that would appear in the Units Table buffer.
27020 Note that this command works only for actual unit names; @kbd{u g km}
27021 will report that no such unit exists, for example, because @code{km} is
27022 really the unit @code{m} with a @code{k} (``kilo'') prefix.  To see a
27023 definition of a unit in terms of base units, it is easier to push the
27024 unit name on the stack and then reduce it to base units with @kbd{u b}.
27026 @kindex u e
27027 @pindex calc-explain-units
27028 The @kbd{u e} (@code{calc-explain-units}) command displays an English
27029 description of the units of the expression on the stack.  For example,
27030 for the expression @samp{62 km^2 g / s^2 mol K}, the description is
27031 ``Square-Kilometer Gram per (Second-squared Mole Degree-Kelvin).''  This
27032 command uses the English descriptions that appear in the righthand
27033 column of the Units Table.
27035 @node Predefined Units, User-Defined Units, The Units Table, Units
27036 @section Predefined Units
27038 @noindent
27039 Since the exact definitions of many kinds of units have evolved over the
27040 years, and since certain countries sometimes have local differences in
27041 their definitions, it is a good idea to examine Calc's definition of a
27042 unit before depending on its exact value.  For example, there are three
27043 different units for gallons, corresponding to the US (@code{gal}),
27044 Canadian (@code{galC}), and British (@code{galUK}) definitions.  Also,
27045 note that @code{oz} is a standard ounce of mass, @code{ozt} is a Troy
27046 ounce, and @code{ozfl} is a fluid ounce.
27048 The temperature units corresponding to degrees Kelvin and Centigrade
27049 (Celsius) are the same in this table, since most units commands treat
27050 temperatures as being relative.  The @code{calc-convert-temperature}
27051 command has special rules for handling the different absolute magnitudes
27052 of the various temperature scales.
27054 The unit of volume ``liters'' can be referred to by either the lower-case
27055 @code{l} or the upper-case @code{L}.
27057 The unit @code{A} stands for Amperes; the name @code{Ang} is used
27058 @tex
27059 for \AA ngstroms.
27060 @end tex
27061 @ifinfo
27062 for Angstroms.
27063 @end ifinfo
27065 The unit @code{pt} stands for pints; the name @code{point} stands for
27066 a typographical point, defined by @samp{72 point = 1 in}.  There is
27067 also @code{tpt}, which stands for a printer's point as defined by the
27068 @TeX{} typesetting system:  @samp{72.27 tpt = 1 in}.
27070 The unit @code{e} stands for the elementary (electron) unit of charge;
27071 because algebra command could mistake this for the special constant
27072 @cite{e}, Calc provides the alternate unit name @code{ech} which is
27073 preferable to @code{e}.
27075 The name @code{g} stands for one gram of mass; there is also @code{gf},
27076 one gram of force.  (Likewise for @kbd{lb}, pounds, and @kbd{lbf}.)
27077 Meanwhile, one ``@cite{g}'' of acceleration is denoted @code{ga}.
27079 The unit @code{ton} is a U.S. ton of @samp{2000 lb}, and @code{t} is
27080 a metric ton of @samp{1000 kg}.
27082 The names @code{s} (or @code{sec}) and @code{min} refer to units of
27083 time; @code{arcsec} and @code{arcmin} are units of angle.
27085 Some ``units'' are really physical constants; for example, @code{c}
27086 represents the speed of light, and @code{h} represents Planck's
27087 constant.  You can use these just like other units: converting
27088 @samp{.5 c} to @samp{m/s} expresses one-half the speed of light in
27089 meters per second.  You can also use this merely as a handy reference;
27090 the @kbd{u g} command gets the definition of one of these constants
27091 in its normal terms, and @kbd{u b} expresses the definition in base
27092 units.
27094 Two units, @code{pi} and @code{fsc} (the fine structure constant,
27095 approximately @i{1/137}) are dimensionless.  The units simplification
27096 commands simply treat these names as equivalent to their corresponding
27097 values.  However you can, for example, use @kbd{u c} to convert a pure
27098 number into multiples of the fine structure constant, or @kbd{u b} to
27099 convert this back into a pure number.  (When @kbd{u c} prompts for the
27100 ``old units,'' just enter a blank line to signify that the value
27101 really is unitless.)
27103 @c Describe angular units, luminosity vs. steradians problem.
27105 @node User-Defined Units, , Predefined Units, Units
27106 @section User-Defined Units
27108 @noindent
27109 Calc provides ways to get quick access to your selected ``favorite''
27110 units, as well as ways to define your own new units.
27112 @kindex u 0-9
27113 @pindex calc-quick-units
27114 @vindex Units
27115 @cindex @code{Units} variable
27116 @cindex Quick units
27117 To select your favorite units, store a vector of unit names or
27118 expressions in the Calc variable @code{Units}.  The @kbd{u 1}
27119 through @kbd{u 9} commands (@code{calc-quick-units}) provide access
27120 to these units.  If the value on the top of the stack is a plain
27121 number (with no units attached), then @kbd{u 1} gives it the
27122 specified units.  (Basically, it multiplies the number by the
27123 first item in the @code{Units} vector.)  If the number on the
27124 stack @emph{does} have units, then @kbd{u 1} converts that number
27125 to the new units.  For example, suppose the vector @samp{[in, ft]}
27126 is stored in @code{Units}.  Then @kbd{30 u 1} will create the
27127 expression @samp{30 in}, and @kbd{u 2} will convert that expression
27128 to @samp{2.5 ft}.
27130 The @kbd{u 0} command accesses the tenth element of @code{Units}.
27131 Only ten quick units may be defined at a time.  If the @code{Units}
27132 variable has no stored value (the default), or if its value is not
27133 a vector, then the quick-units commands will not function.  The
27134 @kbd{s U} command is a convenient way to edit the @code{Units}
27135 variable; @pxref{Operations on Variables}.
27137 @kindex u d
27138 @pindex calc-define-unit
27139 @cindex User-defined units
27140 The @kbd{u d} (@code{calc-define-unit}) command records the units
27141 expression on the top of the stack as the definition for a new,
27142 user-defined unit.  For example, putting @samp{16.5 ft} on the stack and
27143 typing @kbd{u d rod} defines the new unit @samp{rod} to be equivalent to
27144 16.5 feet.  The unit conversion and simplification commands will now
27145 treat @code{rod} just like any other unit of length.  You will also be
27146 prompted for an optional English description of the unit, which will
27147 appear in the Units Table.
27149 @kindex u u
27150 @pindex calc-undefine-unit
27151 The @kbd{u u} (@code{calc-undefine-unit}) command removes a user-defined
27152 unit.  It is not possible to remove one of the predefined units,
27153 however.
27155 If you define a unit with an existing unit name, your new definition
27156 will replace the original definition of that unit.  If the unit was a
27157 predefined unit, the old definition will not be replaced, only
27158 ``shadowed.''  The built-in definition will reappear if you later use
27159 @kbd{u u} to remove the shadowing definition.
27161 To create a new fundamental unit, use either 1 or the unit name itself
27162 as the defining expression.  Otherwise the expression can involve any
27163 other units that you like (except for composite units like @samp{mfi}).
27164 You can create a new composite unit with a sum of other units as the
27165 defining expression.  The next unit operation like @kbd{u c} or @kbd{u v}
27166 will rebuild the internal unit table incorporating your modifications.
27167 Note that erroneous definitions (such as two units defined in terms of
27168 each other) will not be detected until the unit table is next rebuilt;
27169 @kbd{u v} is a convenient way to force this to happen.
27171 Temperature units are treated specially inside the Calculator; it is not
27172 possible to create user-defined temperature units.
27174 @kindex u p
27175 @pindex calc-permanent-units
27176 @cindex @file{.emacs} file, user-defined units
27177 The @kbd{u p} (@code{calc-permanent-units}) command stores the user-defined
27178 units in your @file{.emacs} file, so that the units will still be
27179 available in subsequent Emacs sessions.  If there was already a set of
27180 user-defined units in your @file{.emacs} file, it is replaced by the
27181 new set.  (@xref{General Mode Commands}, for a way to tell Calc to use
27182 a different file instead of @file{.emacs}.)
27184 @node Store and Recall, Graphics, Units, Top
27185 @chapter Storing and Recalling
27187 @noindent
27188 Calculator variables are really just Lisp variables that contain numbers
27189 or formulas in a form that Calc can understand.  The commands in this
27190 section allow you to manipulate variables conveniently.  Commands related
27191 to variables use the @kbd{s} prefix key.
27193 @menu
27194 * Storing Variables::
27195 * Recalling Variables::
27196 * Operations on Variables::
27197 * Let Command::
27198 * Evaluates-To Operator::
27199 @end menu
27201 @node Storing Variables, Recalling Variables, Store and Recall, Store and Recall
27202 @section Storing Variables
27204 @noindent
27205 @kindex s s
27206 @pindex calc-store
27207 @cindex Storing variables
27208 @cindex Quick variables
27209 @vindex q0
27210 @vindex q9
27211 The @kbd{s s} (@code{calc-store}) command stores the value at the top of
27212 the stack into a specified variable.  It prompts you to enter the
27213 name of the variable.  If you press a single digit, the value is stored
27214 immediately in one of the ``quick'' variables @code{var-q0} through
27215 @code{var-q9}.  Or you can enter any variable name.  The prefix @samp{var-}
27216 is supplied for you; when a name appears in a formula (as in @samp{a+q2})
27217 the prefix @samp{var-} is also supplied there, so normally you can simply
27218 forget about @samp{var-} everywhere.  Its only purpose is to enable you to
27219 use Calc variables without fear of accidentally clobbering some variable in
27220 another Emacs package.  If you really want to store in an arbitrary Lisp
27221 variable, just backspace over the @samp{var-}.
27223 @kindex s t
27224 @pindex calc-store-into
27225 The @kbd{s s} command leaves the stored value on the stack.  There is
27226 also an @kbd{s t} (@code{calc-store-into}) command, which removes a
27227 value from the stack and stores it in a variable.
27229 If the top of stack value is an equation @samp{a = 7} or assignment
27230 @samp{a := 7} with a variable on the lefthand side, then Calc will
27231 assign that variable with that value by default, i.e., if you type
27232 @kbd{s s @key{RET}} or @kbd{s t @key{RET}}.  In this example, the
27233 value 7 would be stored in the variable @samp{a}.  (If you do type
27234 a variable name at the prompt, the top-of-stack value is stored in
27235 its entirety, even if it is an equation:  @samp{s s b @key{RET}}
27236 with @samp{a := 7} on the stack stores @samp{a := 7} in @code{b}.)
27238 In fact, the top of stack value can be a vector of equations or
27239 assignments with different variables on their lefthand sides; the
27240 default will be to store all the variables with their corresponding
27241 righthand sides simultaneously.
27243 It is also possible to type an equation or assignment directly at
27244 the prompt for the @kbd{s s} or @kbd{s t} command:  @kbd{s s foo = 7}.
27245 In this case the expression to the right of the @kbd{=} or @kbd{:=}
27246 symbol is evaluated as if by the @kbd{=} command, and that value is
27247 stored in the variable.  No value is taken from the stack; @kbd{s s}
27248 and @kbd{s t} are equivalent when used in this way.
27250 @kindex s 0-9
27251 @kindex t 0-9
27252 The prefix keys @kbd{s} and @kbd{t} may be followed immediately by a
27253 digit; @kbd{s 9} is equivalent to @kbd{s s 9}, and @kbd{t 9} is
27254 equivalent to @kbd{s t 9}.  (The @kbd{t} prefix is otherwise used
27255 for trail and time/date commands.)
27257 @kindex s +
27258 @kindex s -
27259 @c @mindex @idots
27260 @kindex s *
27261 @c @mindex @null
27262 @kindex s /
27263 @c @mindex @null
27264 @kindex s ^
27265 @c @mindex @null
27266 @kindex s |
27267 @c @mindex @null
27268 @kindex s n
27269 @c @mindex @null
27270 @kindex s &
27271 @c @mindex @null
27272 @kindex s [
27273 @c @mindex @null
27274 @kindex s ]
27275 @pindex calc-store-plus
27276 @pindex calc-store-minus
27277 @pindex calc-store-times
27278 @pindex calc-store-div
27279 @pindex calc-store-power
27280 @pindex calc-store-concat
27281 @pindex calc-store-neg
27282 @pindex calc-store-inv
27283 @pindex calc-store-decr
27284 @pindex calc-store-incr
27285 There are also several ``arithmetic store'' commands.  For example,
27286 @kbd{s +} removes a value from the stack and adds it to the specified
27287 variable.  The other arithmetic stores are @kbd{s -}, @kbd{s *}, @kbd{s /},
27288 @kbd{s ^}, and @w{@kbd{s |}} (vector concatenation), plus @kbd{s n} and
27289 @kbd{s &} which negate or invert the value in a variable, and @w{@kbd{s [}}
27290 and @kbd{s ]} which decrease or increase a variable by one.
27292 All the arithmetic stores accept the Inverse prefix to reverse the
27293 order of the operands.  If @cite{v} represents the contents of the
27294 variable, and @cite{a} is the value drawn from the stack, then regular
27295 @w{@kbd{s -}} assigns @c{$v \coloneq v - a$}
27296 @cite{v := v - a}, but @kbd{I s -} assigns
27297 @c{$v \coloneq a - v$}
27298 @cite{v := a - v}.  While @kbd{I s *} might seem pointless, it is
27299 useful if matrix multiplication is involved.  Actually, all the
27300 arithmetic stores use formulas designed to behave usefully both
27301 forwards and backwards:
27303 @group
27304 @example
27305 s +        v := v + a          v := a + v
27306 s -        v := v - a          v := a - v
27307 s *        v := v * a          v := a * v
27308 s /        v := v / a          v := a / v
27309 s ^        v := v ^ a          v := a ^ v
27310 s |        v := v | a          v := a | v
27311 s n        v := v / (-1)       v := (-1) / v
27312 s &        v := v ^ (-1)       v := (-1) ^ v
27313 s [        v := v - 1          v := 1 - v
27314 s ]        v := v - (-1)       v := (-1) - v
27315 @end example
27316 @end group
27318 In the last four cases, a numeric prefix argument will be used in
27319 place of the number one.  (For example, @kbd{M-2 s ]} increases
27320 a variable by 2, and @kbd{M-2 I s ]} replaces a variable by
27321 minus-two minus the variable.
27323 The first six arithmetic stores can also be typed @kbd{s t +}, @kbd{s t -},
27324 etc.  The commands @kbd{s s +}, @kbd{s s -}, and so on are analogous
27325 arithmetic stores that don't remove the value @cite{a} from the stack.
27327 All arithmetic stores report the new value of the variable in the
27328 Trail for your information.  They signal an error if the variable
27329 previously had no stored value.  If default simplifications have been
27330 turned off, the arithmetic stores temporarily turn them on for numeric
27331 arguments only (i.e., they temporarily do an @kbd{m N} command).
27332 @xref{Simplification Modes}.  Large vectors put in the trail by
27333 these commands always use abbreviated (@kbd{t .}) mode.
27335 @kindex s m
27336 @pindex calc-store-map
27337 The @kbd{s m} command is a general way to adjust a variable's value
27338 using any Calc function.  It is a ``mapping'' command analogous to
27339 @kbd{V M}, @kbd{V R}, etc.  @xref{Reducing and Mapping}, to see
27340 how to specify a function for a mapping command.  Basically,
27341 all you do is type the Calc command key that would invoke that
27342 function normally.  For example, @kbd{s m n} applies the @kbd{n}
27343 key to negate the contents of the variable, so @kbd{s m n} is
27344 equivalent to @kbd{s n}.  Also, @kbd{s m Q} takes the square root
27345 of the value stored in a variable, @kbd{s m v v} uses @kbd{v v} to
27346 reverse the vector stored in the variable, and @kbd{s m H I S}
27347 takes the hyperbolic arcsine of the variable contents.
27349 If the mapping function takes two or more arguments, the additional
27350 arguments are taken from the stack; the old value of the variable
27351 is provided as the first argument.  Thus @kbd{s m -} with @cite{a}
27352 on the stack computes @cite{v - a}, just like @kbd{s -}.  With the
27353 Inverse prefix, the variable's original value becomes the @emph{last}
27354 argument instead of the first.  Thus @kbd{I s m -} is also
27355 equivalent to @kbd{I s -}.
27357 @kindex s x
27358 @pindex calc-store-exchange
27359 The @kbd{s x} (@code{calc-store-exchange}) command exchanges the value
27360 of a variable with the value on the top of the stack.  Naturally, the
27361 variable must already have a stored value for this to work.
27363 You can type an equation or assignment at the @kbd{s x} prompt.  The
27364 command @kbd{s x a=6} takes no values from the stack; instead, it
27365 pushes the old value of @samp{a} on the stack and stores @samp{a = 6}.
27367 @kindex s u
27368 @pindex calc-unstore
27369 @cindex Void variables
27370 @cindex Un-storing variables
27371 Until you store something in them, variables are ``void,'' that is, they
27372 contain no value at all.  If they appear in an algebraic formula they
27373 will be left alone even if you press @kbd{=} (@code{calc-evaluate}).
27374 The @kbd{s u} (@code{calc-unstore}) command returns a variable to the
27375 void state.@refill
27377 The only variables with predefined values are the ``special constants''
27378 @code{pi}, @code{e}, @code{i}, @code{phi}, and @code{gamma}.  You are free
27379 to unstore these variables or to store new values into them if you like,
27380 although some of the algebraic-manipulation functions may assume these
27381 variables represent their standard values.  Calc displays a warning if
27382 you change the value of one of these variables, or of one of the other
27383 special variables @code{inf}, @code{uinf}, and @code{nan} (which are
27384 normally void).
27386 Note that @code{var-pi} doesn't actually have 3.14159265359 stored
27387 in it, but rather a special magic value that evaluates to @c{$\pi$}
27388 @cite{pi}
27389 at the current precision.  Likewise @code{var-e}, @code{var-i}, and
27390 @code{var-phi} evaluate according to the current precision or polar mode.
27391 If you recall a value from @code{pi} and store it back, this magic
27392 property will be lost.
27394 @kindex s c
27395 @pindex calc-copy-variable
27396 The @kbd{s c} (@code{calc-copy-variable}) command copies the stored
27397 value of one variable to another.  It differs from a simple @kbd{s r}
27398 followed by an @kbd{s t} in two important ways.  First, the value never
27399 goes on the stack and thus is never rounded, evaluated, or simplified
27400 in any way; it is not even rounded down to the current precision.
27401 Second, the ``magic'' contents of a variable like @code{var-e} can
27402 be copied into another variable with this command, perhaps because
27403 you need to unstore @code{var-e} right now but you wish to put it
27404 back when you're done.  The @kbd{s c} command is the only way to
27405 manipulate these magic values intact.
27407 @node Recalling Variables, Operations on Variables, Storing Variables, Store and Recall
27408 @section Recalling Variables
27410 @noindent
27411 @kindex s r
27412 @pindex calc-recall
27413 @cindex Recalling variables
27414 The most straightforward way to extract the stored value from a variable
27415 is to use the @kbd{s r} (@code{calc-recall}) command.  This command prompts
27416 for a variable name (similarly to @code{calc-store}), looks up the value
27417 of the specified variable, and pushes that value onto the stack.  It is
27418 an error to try to recall a void variable.
27420 It is also possible to recall the value from a variable by evaluating a
27421 formula containing that variable.  For example, @kbd{' a @key{RET} =} is
27422 the same as @kbd{s r a @key{RET}} except that if the variable is void, the
27423 former will simply leave the formula @samp{a} on the stack whereas the
27424 latter will produce an error message.
27426 @kindex r 0-9
27427 The @kbd{r} prefix may be followed by a digit, so that @kbd{r 9} is
27428 equivalent to @kbd{s r 9}.  (The @kbd{r} prefix is otherwise unused
27429 in the current version of Calc.)
27431 @node Operations on Variables, Let Command, Recalling Variables, Store and Recall
27432 @section Other Operations on Variables
27434 @noindent
27435 @kindex s e
27436 @pindex calc-edit-variable
27437 The @kbd{s e} (@code{calc-edit-variable}) command edits the stored
27438 value of a variable without ever putting that value on the stack
27439 or simplifying or evaluating the value.  It prompts for the name of
27440 the variable to edit.  If the variable has no stored value, the
27441 editing buffer will start out empty.  If the editing buffer is
27442 empty when you press @key{M-# M-#} to finish, the variable will
27443 be made void.  @xref{Editing Stack Entries}, for a general
27444 description of editing.
27446 The @kbd{s e} command is especially useful for creating and editing
27447 rewrite rules which are stored in variables.  Sometimes these rules
27448 contain formulas which must not be evaluated until the rules are
27449 actually used.  (For example, they may refer to @samp{deriv(x,y)},
27450 where @code{x} will someday become some expression involving @code{y};
27451 if you let Calc evaluate the rule while you are defining it, Calc will
27452 replace @samp{deriv(x,y)} with 0 because the formula @code{x} does
27453 not itself refer to @code{y}.)  By contrast, recalling the variable,
27454 editing with @kbd{`}, and storing will evaluate the variable's value
27455 as a side effect of putting the value on the stack.
27457 @kindex s A
27458 @kindex s D
27459 @c @mindex @idots
27460 @kindex s E
27461 @c @mindex @null
27462 @kindex s F
27463 @c @mindex @null
27464 @kindex s G
27465 @c @mindex @null
27466 @kindex s H
27467 @c @mindex @null
27468 @kindex s I
27469 @c @mindex @null
27470 @kindex s L
27471 @c @mindex @null
27472 @kindex s P
27473 @c @mindex @null
27474 @kindex s R
27475 @c @mindex @null
27476 @kindex s T
27477 @c @mindex @null
27478 @kindex s U
27479 @c @mindex @null
27480 @kindex s X
27481 @pindex calc-store-AlgSimpRules
27482 @pindex calc-store-Decls
27483 @pindex calc-store-EvalRules
27484 @pindex calc-store-FitRules
27485 @pindex calc-store-GenCount
27486 @pindex calc-store-Holidays
27487 @pindex calc-store-IntegLimit
27488 @pindex calc-store-LineStyles
27489 @pindex calc-store-PointStyles
27490 @pindex calc-store-PlotRejects
27491 @pindex calc-store-TimeZone
27492 @pindex calc-store-Units
27493 @pindex calc-store-ExtSimpRules
27494 There are several special-purpose variable-editing commands that
27495 use the @kbd{s} prefix followed by a shifted letter:
27497 @table @kbd
27498 @item s A
27499 Edit @code{AlgSimpRules}.  @xref{Algebraic Simplifications}.
27500 @item s D
27501 Edit @code{Decls}.  @xref{Declarations}.
27502 @item s E
27503 Edit @code{EvalRules}.  @xref{Default Simplifications}.
27504 @item s F
27505 Edit @code{FitRules}.  @xref{Curve Fitting}.
27506 @item s G
27507 Edit @code{GenCount}.  @xref{Solving Equations}.
27508 @item s H
27509 Edit @code{Holidays}.  @xref{Business Days}.
27510 @item s I
27511 Edit @code{IntegLimit}.  @xref{Calculus}.
27512 @item s L
27513 Edit @code{LineStyles}.  @xref{Graphics}.
27514 @item s P
27515 Edit @code{PointStyles}.  @xref{Graphics}.
27516 @item s R
27517 Edit @code{PlotRejects}.  @xref{Graphics}.
27518 @item s T
27519 Edit @code{TimeZone}.  @xref{Time Zones}.
27520 @item s U
27521 Edit @code{Units}.  @xref{User-Defined Units}.
27522 @item s X
27523 Edit @code{ExtSimpRules}.  @xref{Unsafe Simplifications}.
27524 @end table
27526 These commands are just versions of @kbd{s e} that use fixed variable
27527 names rather than prompting for the variable name.
27529 @kindex s p
27530 @pindex calc-permanent-variable
27531 @cindex Storing variables
27532 @cindex Permanent variables
27533 @cindex @file{.emacs} file, veriables
27534 The @kbd{s p} (@code{calc-permanent-variable}) command saves a
27535 variable's value permanently in your @file{.emacs} file, so that its
27536 value will still be available in future Emacs sessions.  You can
27537 re-execute @w{@kbd{s p}} later on to update the saved value, but the
27538 only way to remove a saved variable is to edit your @file{.emacs} file
27539 by hand.  (@xref{General Mode Commands}, for a way to tell Calc to
27540 use a different file instead of @file{.emacs}.)
27542 If you do not specify the name of a variable to save (i.e.,
27543 @kbd{s p @key{RET}}), all @samp{var-} variables with defined values
27544 are saved except for the special constants @code{pi}, @code{e},
27545 @code{i}, @code{phi}, and @code{gamma}; the variables @code{TimeZone}
27546 and @code{PlotRejects};
27547 @code{FitRules}, @code{DistribRules}, and other built-in rewrite
27548 rules; and @code{PlotData@var{n}} variables generated
27549 by the graphics commands.  (You can still save these variables by
27550 explicitly naming them in an @kbd{s p} command.)@refill
27552 @kindex s i
27553 @pindex calc-insert-variables
27554 The @kbd{s i} (@code{calc-insert-variables}) command writes
27555 the values of all @samp{var-} variables into a specified buffer.
27556 The variables are written in the form of Lisp @code{setq} commands
27557 which store the values in string form.  You can place these commands
27558 in your @file{.emacs} buffer if you wish, though in this case it
27559 would be easier to use @kbd{s p @key{RET}}.  (Note that @kbd{s i}
27560 omits the same set of variables as @w{@kbd{s p @key{RET}}}; the difference
27561 is that @kbd{s i} will store the variables in any buffer, and it also
27562 stores in a more human-readable format.)
27564 @node Let Command, Evaluates-To Operator, Operations on Variables, Store and Recall
27565 @section The Let Command
27567 @noindent
27568 @kindex s l
27569 @pindex calc-let
27570 @cindex Variables, temporary assignment
27571 @cindex Temporary assignment to variables
27572 If you have an expression like @samp{a+b^2} on the stack and you wish to
27573 compute its value where @cite{b=3}, you can simply store 3 in @cite{b} and
27574 then press @kbd{=} to reevaluate the formula.  This has the side-effect
27575 of leaving the stored value of 3 in @cite{b} for future operations.
27577 The @kbd{s l} (@code{calc-let}) command evaluates a formula under a
27578 @emph{temporary} assignment of a variable.  It stores the value on the
27579 top of the stack into the specified variable, then evaluates the
27580 second-to-top stack entry, then restores the original value (or lack of one)
27581 in the variable.  Thus after @kbd{'@w{ }a+b^2 @key{RET} 3 s l b @key{RET}},
27582 the stack will contain the formula @samp{a + 9}.  The subsequent command
27583 @kbd{@w{5 s l a} @key{RET}} will replace this formula with the number 14.
27584 The variables @samp{a} and @samp{b} are not permanently affected in any way
27585 by these commands.
27587 The value on the top of the stack may be an equation or assignment, or
27588 a vector of equations or assignments, in which case the default will be
27589 analogous to the case of @kbd{s t @key{RET}}.  @xref{Storing Variables}.
27591 Also, you can answer the variable-name prompt with an equation or
27592 assignment:  @kbd{s l b=3 RET} is the same as storing 3 on the stack
27593 and typing @kbd{s l b RET}.
27595 The @kbd{a b} (@code{calc-substitute}) command is another way to substitute
27596 a variable with a value in a formula.  It does an actual substitution
27597 rather than temporarily assigning the variable and evaluating.  For
27598 example, letting @cite{n=2} in @samp{f(n pi)} with @kbd{a b} will
27599 produce @samp{f(2 pi)}, whereas @kbd{s l} would give @samp{f(6.28)}
27600 since the evaluation step will also evaluate @code{pi}.
27602 @node Evaluates-To Operator, , Let Command, Store and Recall
27603 @section The Evaluates-To Operator
27605 @noindent
27606 @tindex evalto
27607 @tindex =>
27608 @cindex Evaluates-to operator
27609 @cindex @samp{=>} operator
27610 The special algebraic symbol @samp{=>} is known as the @dfn{evaluates-to
27611 operator}.  (It will show up as an @code{evalto} function call in
27612 other language modes like Pascal and @TeX{}.)  This is a binary
27613 operator, that is, it has a lefthand and a righthand argument,
27614 although it can be entered with the righthand argument omitted.
27616 A formula like @samp{@var{a} => @var{b}} is evaluated by Calc as
27617 follows:  First, @var{a} is not simplified or modified in any
27618 way.  The previous value of argument @var{b} is thrown away; the
27619 formula @var{a} is then copied and evaluated as if by the @kbd{=}
27620 command according to all current modes and stored variable values,
27621 and the result is installed as the new value of @var{b}.
27623 For example, suppose you enter the algebraic formula @samp{2 + 3 => 17}.
27624 The number 17 is ignored, and the lefthand argument is left in its
27625 unevaluated form; the result is the formula @samp{2 + 3 => 5}.
27627 @kindex s =
27628 @pindex calc-evalto
27629 You can enter an @samp{=>} formula either directly using algebraic
27630 entry (in which case the righthand side may be omitted since it is
27631 going to be replaced right away anyhow), or by using the @kbd{s =}
27632 (@code{calc-evalto}) command, which takes @var{a} from the stack
27633 and replaces it with @samp{@var{a} => @var{b}}.
27635 Calc keeps track of all @samp{=>} operators on the stack, and
27636 recomputes them whenever anything changes that might affect their
27637 values, i.e., a mode setting or variable value.  This occurs only
27638 if the @samp{=>} operator is at the top level of the formula, or
27639 if it is part of a top-level vector.  In other words, pushing
27640 @samp{2 + (a => 17)} will change the 17 to the actual value of
27641 @samp{a} when you enter the formula, but the result will not be
27642 dynamically updated when @samp{a} is changed later because the
27643 @samp{=>} operator is buried inside a sum.  However, a vector
27644 of @samp{=>} operators will be recomputed, since it is convenient
27645 to push a vector like @samp{[a =>, b =>, c =>]} on the stack to
27646 make a concise display of all the variables in your problem.
27647 (Another way to do this would be to use @samp{[a, b, c] =>},
27648 which provides a slightly different format of display.  You
27649 can use whichever you find easiest to read.)
27651 @kindex m C
27652 @pindex calc-auto-recompute
27653 The @kbd{m C} (@code{calc-auto-recompute}) command allows you to
27654 turn this automatic recomputation on or off.  If you turn
27655 recomputation off, you must explicitly recompute an @samp{=>}
27656 operator on the stack in one of the usual ways, such as by
27657 pressing @kbd{=}.  Turning recomputation off temporarily can save
27658 a lot of time if you will be changing several modes or variables
27659 before you look at the @samp{=>} entries again.
27661 Most commands are not especially useful with @samp{=>} operators
27662 as arguments.  For example, given @samp{x + 2 => 17}, it won't
27663 work to type @kbd{1 +} to get @samp{x + 3 => 18}.  If you want
27664 to operate on the lefthand side of the @samp{=>} operator on
27665 the top of the stack, type @kbd{j 1} (that's the digit ``one'')
27666 to select the lefthand side, execute your commands, then type
27667 @kbd{j u} to unselect.
27669 All current modes apply when an @samp{=>} operator is computed,
27670 including the current simplification mode.  Recall that the
27671 formula @samp{x + y + x} is not handled by Calc's default
27672 simplifications, but the @kbd{a s} command will reduce it to
27673 the simpler form @samp{y + 2 x}.  You can also type @kbd{m A}
27674 to enable an algebraic-simplification mode in which the
27675 equivalent of @kbd{a s} is used on all of Calc's results.
27676 If you enter @samp{x + y + x =>} normally, the result will
27677 be @samp{x + y + x => x + y + x}.  If you change to
27678 algebraic-simplification mode, the result will be
27679 @samp{x + y + x => y + 2 x}.  However, just pressing @kbd{a s}
27680 once will have no effect on @samp{x + y + x => x + y + x},
27681 because the righthand side depends only on the lefthand side
27682 and the current mode settings, and the lefthand side is not
27683 affected by commands like @kbd{a s}.
27685 The ``let'' command (@kbd{s l}) has an interesting interaction
27686 with the @samp{=>} operator.  The @kbd{s l} command evaluates the
27687 second-to-top stack entry with the top stack entry supplying
27688 a temporary value for a given variable.  As you might expect,
27689 if that stack entry is an @samp{=>} operator its righthand
27690 side will temporarily show this value for the variable.  In
27691 fact, all @samp{=>}s on the stack will be updated if they refer
27692 to that variable.  But this change is temporary in the sense
27693 that the next command that causes Calc to look at those stack
27694 entries will make them revert to the old variable value.
27696 @group
27697 @smallexample
27698 2:  a => a             2:  a => 17         2:  a => a
27699 1:  a + 1 => a + 1     1:  a + 1 => 18     1:  a + 1 => a + 1
27700     .                      .                   .
27702                            17 s l a RET        p 8 RET
27703 @end smallexample
27704 @end group
27706 Here the @kbd{p 8} command changes the current precision,
27707 thus causing the @samp{=>} forms to be recomputed after the
27708 influence of the ``let'' is gone.  The @kbd{d SPC} command
27709 (@code{calc-refresh}) is a handy way to force the @samp{=>}
27710 operators on the stack to be recomputed without any other
27711 side effects.
27713 @kindex s :
27714 @pindex calc-assign
27715 @tindex assign
27716 @tindex :=
27717 Embedded Mode also uses @samp{=>} operators.  In embedded mode,
27718 the lefthand side of an @samp{=>} operator can refer to variables
27719 assigned elsewhere in the file by @samp{:=} operators.  The
27720 assignment operator @samp{a := 17} does not actually do anything
27721 by itself.  But Embedded Mode recognizes it and marks it as a sort
27722 of file-local definition of the variable.  You can enter @samp{:=}
27723 operators in algebraic mode, or by using the @kbd{s :}
27724 (@code{calc-assign}) [@code{assign}] command which takes a variable
27725 and value from the stack and replaces them with an assignment.
27727 @xref{TeX Language Mode}, for the way @samp{=>} appears in
27728 @TeX{} language output.  The @dfn{eqn} mode gives similar
27729 treatment to @samp{=>}.
27731 @node Graphics, Kill and Yank, Store and Recall, Top
27732 @chapter Graphics
27734 @noindent
27735 The commands for graphing data begin with the @kbd{g} prefix key.  Calc
27736 uses GNUPLOT 2.0 or 3.0 to do graphics.  These commands will only work
27737 if GNUPLOT is available on your system.  (While GNUPLOT sounds like
27738 a relative of GNU Emacs, it is actually completely unrelated.
27739 However, it is free software and can be obtained from the Free
27740 Software Foundation's machine @samp{prep.ai.mit.edu}.)
27742 @vindex calc-gnuplot-name
27743 If you have GNUPLOT installed on your system but Calc is unable to
27744 find it, you may need to set the @code{calc-gnuplot-name} variable
27745 in your @file{.emacs} file.  You may also need to set some Lisp
27746 variables to show Calc how to run GNUPLOT on your system; these
27747 are described under @kbd{g D} and @kbd{g O} below.  If you are
27748 using the X window system, Calc will configure GNUPLOT for you
27749 automatically.  If you have GNUPLOT 3.0 and you are not using X,
27750 Calc will configure GNUPLOT to display graphs using simple character
27751 graphics that will work on any terminal.
27753 @menu
27754 * Basic Graphics::
27755 * Three Dimensional Graphics::
27756 * Managing Curves::
27757 * Graphics Options::
27758 * Devices::
27759 @end menu
27761 @node Basic Graphics, Three Dimensional Graphics, Graphics, Graphics
27762 @section Basic Graphics
27764 @noindent
27765 @kindex g f
27766 @pindex calc-graph-fast
27767 The easiest graphics command is @kbd{g f} (@code{calc-graph-fast}).
27768 This command takes two vectors of equal length from the stack.
27769 The vector at the top of the stack represents the ``y'' values of
27770 the various data points.  The vector in the second-to-top position
27771 represents the corresponding ``x'' values.  This command runs
27772 GNUPLOT (if it has not already been started by previous graphing
27773 commands) and displays the set of data points.  The points will
27774 be connected by lines, and there will also be some kind of symbol
27775 to indicate the points themselves.
27777 The ``x'' entry may instead be an interval form, in which case suitable
27778 ``x'' values are interpolated between the minimum and maximum values of
27779 the interval (whether the interval is open or closed is ignored).
27781 The ``x'' entry may also be a number, in which case Calc uses the
27782 sequence of ``x'' values @cite{x}, @cite{x+1}, @cite{x+2}, etc.
27783 (Generally the number 0 or 1 would be used for @cite{x} in this case.)
27785 The ``y'' entry may be any formula instead of a vector.  Calc effectively
27786 uses @kbd{N} (@code{calc-eval-num}) to evaluate variables in the formula;
27787 the result of this must be a formula in a single (unassigned) variable.
27788 The formula is plotted with this variable taking on the various ``x''
27789 values.  Graphs of formulas by default use lines without symbols at the
27790 computed data points.  Note that if neither ``x'' nor ``y'' is a vector,
27791 Calc guesses at a reasonable number of data points to use.  See the
27792 @kbd{g N} command below.  (The ``x'' values must be either a vector
27793 or an interval if ``y'' is a formula.)
27795 @c @starindex
27796 @tindex xy
27797 If ``y'' is (or evaluates to) a formula of the form
27798 @samp{xy(@var{x}, @var{y})} then the result is a
27799 parametric plot.  The two arguments of the fictitious @code{xy} function
27800 are used as the ``x'' and ``y'' coordinates of the curve, respectively.
27801 In this case the ``x'' vector or interval you specified is not directly
27802 visible in the graph.  For example, if ``x'' is the interval @samp{[0..360]}
27803 and ``y'' is the formula @samp{xy(sin(t), cos(t))}, the resulting graph
27804 will be a circle.@refill
27806 Also, ``x'' and ``y'' may each be variable names, in which case Calc
27807 looks for suitable vectors, intervals, or formulas stored in those
27808 variables.
27810 The ``x'' and ``y'' values for the data points (as pulled from the vectors,
27811 calculated from the formulas, or interpolated from the intervals) should
27812 be real numbers (integers, fractions, or floats).  If either the ``x''
27813 value or the ``y'' value of a given data point is not a real number, that
27814 data point will be omitted from the graph.  The points on either side
27815 of the invalid point will @emph{not} be connected by a line.
27817 See the documentation for @kbd{g a} below for a description of the way
27818 numeric prefix arguments affect @kbd{g f}.
27820 @cindex @code{PlotRejects} variable
27821 @vindex PlotRejects
27822 If you store an empty vector in the variable @code{PlotRejects}
27823 (i.e., @kbd{[ ] s t PlotRejects}), Calc will append information to
27824 this vector for every data point which was rejected because its
27825 ``x'' or ``y'' values were not real numbers.  The result will be
27826 a matrix where each row holds the curve number, data point number,
27827 ``x'' value, and ``y'' value for a rejected data point.
27828 @xref{Evaluates-To Operator}, for a handy way to keep tabs on the
27829 current value of @code{PlotRejects}.  @xref{Operations on Variables},
27830 for the @kbd{s R} command which is another easy way to examine
27831 @code{PlotRejects}.
27833 @kindex g c
27834 @pindex calc-graph-clear
27835 To clear the graphics display, type @kbd{g c} (@code{calc-graph-clear}).
27836 If the GNUPLOT output device is an X window, the window will go away.
27837 Effects on other kinds of output devices will vary.  You don't need
27838 to use @kbd{g c} if you don't want to---if you give another @kbd{g f}
27839 or @kbd{g p} command later on, it will reuse the existing graphics
27840 window if there is one.
27842 @node Three Dimensional Graphics, Managing Curves, Basic Graphics, Graphics
27843 @section Three-Dimensional Graphics
27845 @kindex g F
27846 @pindex calc-graph-fast-3d
27847 The @kbd{g F} (@code{calc-graph-fast-3d}) command makes a three-dimensional
27848 graph.  It works only if you have GNUPLOT 3.0 or later; with GNUPLOT 2.0,
27849 you will see a GNUPLOT error message if you try this command.
27851 The @kbd{g F} command takes three values from the stack, called ``x'',
27852 ``y'', and ``z'', respectively.  As was the case for 2D graphs, there
27853 are several options for these values.
27855 In the first case, ``x'' and ``y'' are each vectors (not necessarily of
27856 the same length); either or both may instead be interval forms.  The
27857 ``z'' value must be a matrix with the same number of rows as elements
27858 in ``x'', and the same number of columns as elements in ``y''.  The
27859 result is a surface plot where @c{$z_{ij}$}
27860 @cite{z_ij} is the height of the point
27861 at coordinate @cite{(x_i, y_j)} on the surface.  The 3D graph will
27862 be displayed from a certain default viewpoint; you can change this
27863 viewpoint by adding a @samp{set view} to the @samp{*Gnuplot Commands*}
27864 buffer as described later.  See the GNUPLOT 3.0 documentation for a
27865 description of the @samp{set view} command.
27867 Each point in the matrix will be displayed as a dot in the graph,
27868 and these points will be connected by a grid of lines (@dfn{isolines}).
27870 In the second case, ``x'', ``y'', and ``z'' are all vectors of equal
27871 length.  The resulting graph displays a 3D line instead of a surface,
27872 where the coordinates of points along the line are successive triplets
27873 of values from the input vectors.
27875 In the third case, ``x'' and ``y'' are vectors or interval forms, and
27876 ``z'' is any formula involving two variables (not counting variables
27877 with assigned values).  These variables are sorted into alphabetical
27878 order; the first takes on values from ``x'' and the second takes on
27879 values from ``y'' to form a matrix of results that are graphed as a
27880 3D surface.
27882 @c @starindex
27883 @tindex xyz
27884 If the ``z'' formula evaluates to a call to the fictitious function
27885 @samp{xyz(@var{x}, @var{y}, @var{z})}, then the result is a
27886 ``parametric surface.''  In this case, the axes of the graph are
27887 taken from the @var{x} and @var{y} values in these calls, and the
27888 ``x'' and ``y'' values from the input vectors or intervals are used only
27889 to specify the range of inputs to the formula.  For example, plotting
27890 @samp{[0..360], [0..180], xyz(sin(x)*sin(y), cos(x)*sin(y), cos(y))}
27891 will draw a sphere.  (Since the default resolution for 3D plots is
27892 5 steps in each of ``x'' and ``y'', this will draw a very crude
27893 sphere.  You could use the @kbd{g N} command, described below, to
27894 increase this resolution, or specify the ``x'' and ``y'' values as
27895 vectors with more than 5 elements.
27897 It is also possible to have a function in a regular @kbd{g f} plot
27898 evaluate to an @code{xyz} call.  Since @kbd{g f} plots a line, not
27899 a surface, the result will be a 3D parametric line.  For example,
27900 @samp{[[0..720], xyz(sin(x), cos(x), x)]} will plot two turns of a
27901 helix (a three-dimensional spiral).
27903 As for @kbd{g f}, each of ``x'', ``y'', and ``z'' may instead be
27904 variables containing the relevant data.
27906 @node Managing Curves, Graphics Options, Three Dimensional Graphics, Graphics
27907 @section Managing Curves
27909 @noindent
27910 The @kbd{g f} command is really shorthand for the following commands:
27911 @kbd{C-u g d  g a  g p}.  Likewise, @w{@kbd{g F}} is shorthand for
27912 @kbd{C-u g d  g A  g p}.  You can gain more control over your graph
27913 by using these commands directly.
27915 @kindex g a
27916 @pindex calc-graph-add
27917 The @kbd{g a} (@code{calc-graph-add}) command adds the ``curve''
27918 represented by the two values on the top of the stack to the current
27919 graph.  You can have any number of curves in the same graph.  When
27920 you give the @kbd{g p} command, all the curves will be drawn superimposed
27921 on the same axes.
27923 The @kbd{g a} command (and many others that affect the current graph)
27924 will cause a special buffer, @samp{*Gnuplot Commands*}, to be displayed
27925 in another window.  This buffer is a template of the commands that will
27926 be sent to GNUPLOT when it is time to draw the graph.  The first
27927 @kbd{g a} command adds a @code{plot} command to this buffer.  Succeeding
27928 @kbd{g a} commands add extra curves onto that @code{plot} command.
27929 Other graph-related commands put other GNUPLOT commands into this
27930 buffer.  In normal usage you never need to work with this buffer
27931 directly, but you can if you wish.  The only constraint is that there
27932 must be only one @code{plot} command, and it must be the last command
27933 in the buffer.  If you want to save and later restore a complete graph
27934 configuration, you can use regular Emacs commands to save and restore
27935 the contents of the @samp{*Gnuplot Commands*} buffer.
27937 @vindex PlotData1
27938 @vindex PlotData2
27939 If the values on the stack are not variable names, @kbd{g a} will invent
27940 variable names for them (of the form @samp{PlotData@var{n}}) and store
27941 the values in those variables.  The ``x'' and ``y'' variables are what
27942 go into the @code{plot} command in the template.  If you add a curve
27943 that uses a certain variable and then later change that variable, you
27944 can replot the graph without having to delete and re-add the curve.
27945 That's because the variable name, not the vector, interval or formula
27946 itself, is what was added by @kbd{g a}.
27948 A numeric prefix argument on @kbd{g a} or @kbd{g f} changes the way
27949 stack entries are interpreted as curves.  With a positive prefix
27950 argument @cite{n}, the top @cite{n} stack entries are ``y'' values
27951 for @cite{n} different curves which share a common ``x'' value in
27952 the @cite{n+1}st stack entry.  (Thus @kbd{g a} with no prefix
27953 argument is equivalent to @kbd{C-u 1 g a}.)
27955 A prefix of zero or plain @kbd{C-u} means to take two stack entries,
27956 ``x'' and ``y'' as usual, but to interpret ``y'' as a vector of
27957 ``y'' values for several curves that share a common ``x''.
27959 A negative prefix argument tells Calc to read @cite{n} vectors from
27960 the stack; each vector @cite{[x, y]} describes an independent curve.
27961 This is the only form of @kbd{g a} that creates several curves at once
27962 that don't have common ``x'' values.  (Of course, the range of ``x''
27963 values covered by all the curves ought to be roughly the same if
27964 they are to look nice on the same graph.)
27966 For example, to plot @c{$\sin n x$}
27967 @cite{sin(n x)} for integers @cite{n}
27968 from 1 to 5, you could use @kbd{v x} to create a vector of integers
27969 (@cite{n}), then @kbd{V M '} or @kbd{V M $} to map @samp{sin(n x)}
27970 across this vector.  The resulting vector of formulas is suitable
27971 for use as the ``y'' argument to a @kbd{C-u g a} or @kbd{C-u g f}
27972 command.
27974 @kindex g A
27975 @pindex calc-graph-add-3d
27976 The @kbd{g A} (@code{calc-graph-add-3d}) command adds a 3D curve
27977 to the graph.  It is not legal to intermix 2D and 3D curves in a
27978 single graph.  This command takes three arguments, ``x'', ``y'',
27979 and ``z'', from the stack.  With a positive prefix @cite{n}, it
27980 takes @cite{n+2} arguments (common ``x'' and ``y'', plus @cite{n}
27981 separate ``z''s).  With a zero prefix, it takes three stack entries
27982 but the ``z'' entry is a vector of curve values.  With a negative
27983 prefix @cite{-n}, it takes @cite{n} vectors of the form @cite{[x, y, z]}.
27984 The @kbd{g A} command works by adding a @code{splot} (surface-plot)
27985 command to the @samp{*Gnuplot Commands*} buffer.
27987 (Although @kbd{g a} adds a 2D @code{plot} command to the
27988 @samp{*Gnuplot Commands*} buffer, Calc changes this to @code{splot}
27989 before sending it to GNUPLOT if it notices that the data points are
27990 evaluating to @code{xyz} calls.  It will not work to mix 2D and 3D
27991 @kbd{g a} curves in a single graph, although Calc does not currently
27992 check for this.)
27994 @kindex g d
27995 @pindex calc-graph-delete
27996 The @kbd{g d} (@code{calc-graph-delete}) command deletes the most
27997 recently added curve from the graph.  It has no effect if there are
27998 no curves in the graph.  With a numeric prefix argument of any kind,
27999 it deletes all of the curves from the graph.
28001 @kindex g H
28002 @pindex calc-graph-hide
28003 The @kbd{g H} (@code{calc-graph-hide}) command ``hides'' or ``unhides''
28004 the most recently added curve.  A hidden curve will not appear in
28005 the actual plot, but information about it such as its name and line and
28006 point styles will be retained.
28008 @kindex g j
28009 @pindex calc-graph-juggle
28010 The @kbd{g j} (@code{calc-graph-juggle}) command moves the curve
28011 at the end of the list (the ``most recently added curve'') to the
28012 front of the list.  The next-most-recent curve is thus exposed for
28013 @w{@kbd{g d}} or similar commands to use.  With @kbd{g j} you can work
28014 with any curve in the graph even though curve-related commands only
28015 affect the last curve in the list.
28017 @kindex g p
28018 @pindex calc-graph-plot
28019 The @kbd{g p} (@code{calc-graph-plot}) command uses GNUPLOT to draw
28020 the graph described in the @samp{*Gnuplot Commands*} buffer.  Any
28021 GNUPLOT parameters which are not defined by commands in this buffer
28022 are reset to their default values.  The variables named in the @code{plot}
28023 command are written to a temporary data file and the variable names
28024 are then replaced by the file name in the template.  The resulting
28025 plotting commands are fed to the GNUPLOT program.  See the documentation
28026 for the GNUPLOT program for more specific information.  All temporary
28027 files are removed when Emacs or GNUPLOT exits.
28029 If you give a formula for ``y'', Calc will remember all the values that
28030 it calculates for the formula so that later plots can reuse these values.
28031 Calc throws out these saved values when you change any circumstances
28032 that may affect the data, such as switching from Degrees to Radians
28033 mode, or changing the value of a parameter in the formula.  You can
28034 force Calc to recompute the data from scratch by giving a negative
28035 numeric prefix argument to @kbd{g p}.
28037 Calc uses a fairly rough step size when graphing formulas over intervals.
28038 This is to ensure quick response.  You can ``refine'' a plot by giving
28039 a positive numeric prefix argument to @kbd{g p}.  Calc goes through
28040 the data points it has computed and saved from previous plots of the
28041 function, and computes and inserts a new data point midway between
28042 each of the existing points.  You can refine a plot any number of times,
28043 but beware that the amount of calculation involved doubles each time.
28045 Calc does not remember computed values for 3D graphs.  This means the
28046 numerix prefix argument, if any, to @kbd{g p} is effectively ignored if
28047 the current graph is three-dimensional.
28049 @kindex g P
28050 @pindex calc-graph-print
28051 The @kbd{g P} (@code{calc-graph-print}) command is like @kbd{g p},
28052 except that it sends the output to a printer instead of to the
28053 screen.  More precisely, @kbd{g p} looks for @samp{set terminal}
28054 or @samp{set output} commands in the @samp{*Gnuplot Commands*} buffer;
28055 lacking these it uses the default settings.  However, @kbd{g P}
28056 ignores @samp{set terminal} and @samp{set output} commands and
28057 uses a different set of default values.  All of these values are
28058 controlled by the @kbd{g D} and @kbd{g O} commands discussed below.
28059 Provided everything is set up properly, @kbd{g p} will plot to
28060 the screen unless you have specified otherwise and @kbd{g P} will
28061 always plot to the printer.
28063 @node Graphics Options, Devices, Managing Curves, Graphics
28064 @section Graphics Options
28066 @noindent
28067 @kindex g g
28068 @pindex calc-graph-grid
28069 The @kbd{g g} (@code{calc-graph-grid}) command turns the ``grid''
28070 on and off.  It is off by default; tick marks appear only at the
28071 edges of the graph.  With the grid turned on, dotted lines appear
28072 across the graph at each tick mark.  Note that this command only
28073 changes the setting in @samp{*Gnuplot Commands*}; to see the effects
28074 of the change you must give another @kbd{g p} command.
28076 @kindex g b
28077 @pindex calc-graph-border
28078 The @kbd{g b} (@code{calc-graph-border}) command turns the border
28079 (the box that surrounds the graph) on and off.  It is on by default.
28080 This command will only work with GNUPLOT 3.0 and later versions.
28082 @kindex g k
28083 @pindex calc-graph-key
28084 The @kbd{g k} (@code{calc-graph-key}) command turns the ``key''
28085 on and off.  The key is a chart in the corner of the graph that
28086 shows the correspondence between curves and line styles.  It is
28087 off by default, and is only really useful if you have several
28088 curves on the same graph.
28090 @kindex g N
28091 @pindex calc-graph-num-points
28092 The @kbd{g N} (@code{calc-graph-num-points}) command allows you
28093 to select the number of data points in the graph.  This only affects
28094 curves where neither ``x'' nor ``y'' is specified as a vector.
28095 Enter a blank line to revert to the default value (initially 15).
28096 With no prefix argument, this command affects only the current graph.
28097 With a positive prefix argument this command changes or, if you enter
28098 a blank line, displays the default number of points used for all
28099 graphs created by @kbd{g a} that don't specify the resolution explicitly.
28100 With a negative prefix argument, this command changes or displays
28101 the default value (initially 5) used for 3D graphs created by @kbd{g A}.
28102 Note that a 3D setting of 5 means that a total of @cite{5^2 = 25} points
28103 will be computed for the surface.
28105 Data values in the graph of a function are normally computed to a
28106 precision of five digits, regardless of the current precision at the
28107 time. This is usually more than adequate, but there are cases where
28108 it will not be.  For example, plotting @cite{1 + x} with @cite{x} in the
28109 interval @samp{[0 ..@: 1e-6]} will round all the data points down
28110 to 1.0!  Putting the command @samp{set precision @var{n}} in the
28111 @samp{*Gnuplot Commands*} buffer will cause the data to be computed
28112 at precision @var{n} instead of 5.  Since this is such a rare case,
28113 there is no keystroke-based command to set the precision.
28115 @kindex g h
28116 @pindex calc-graph-header
28117 The @kbd{g h} (@code{calc-graph-header}) command sets the title
28118 for the graph.  This will show up centered above the graph.
28119 The default title is blank (no title).
28121 @kindex g n
28122 @pindex calc-graph-name
28123 The @kbd{g n} (@code{calc-graph-name}) command sets the title of an
28124 individual curve.  Like the other curve-manipulating commands, it
28125 affects the most recently added curve, i.e., the last curve on the
28126 list in the @samp{*Gnuplot Commands*} buffer.  To set the title of
28127 the other curves you must first juggle them to the end of the list
28128 with @kbd{g j}, or edit the @samp{*Gnuplot Commands*} buffer by hand.
28129 Curve titles appear in the key; if the key is turned off they are
28130 not used.
28132 @kindex g t
28133 @kindex g T
28134 @pindex calc-graph-title-x
28135 @pindex calc-graph-title-y
28136 The @kbd{g t} (@code{calc-graph-title-x}) and @kbd{g T}
28137 (@code{calc-graph-title-y}) commands set the titles on the ``x''
28138 and ``y'' axes, respectively.  These titles appear next to the
28139 tick marks on the left and bottom edges of the graph, respectively.
28140 Calc does not have commands to control the tick marks themselves,
28141 but you can edit them into the @samp{*Gnuplot Commands*} buffer if
28142 you wish.  See the GNUPLOT documentation for details.
28144 @kindex g r
28145 @kindex g R
28146 @pindex calc-graph-range-x
28147 @pindex calc-graph-range-y
28148 The @kbd{g r} (@code{calc-graph-range-x}) and @kbd{g R}
28149 (@code{calc-graph-range-y}) commands set the range of values on the
28150 ``x'' and ``y'' axes, respectively.  You are prompted to enter a
28151 suitable range.  This should be either a pair of numbers of the
28152 form, @samp{@var{min}:@var{max}}, or a blank line to revert to the
28153 default behavior of setting the range based on the range of values
28154 in the data, or @samp{$} to take the range from the top of the stack.
28155 Ranges on the stack can be represented as either interval forms or
28156 vectors:  @samp{[@var{min} ..@: @var{max}]} or @samp{[@var{min}, @var{max}]}.
28158 @kindex g l
28159 @kindex g L
28160 @pindex calc-graph-log-x
28161 @pindex calc-graph-log-y
28162 The @kbd{g l} (@code{calc-graph-log-x}) and @kbd{g L} (@code{calc-graph-log-y})
28163 commands allow you to set either or both of the axes of the graph to
28164 be logarithmic instead of linear.
28166 @kindex g C-l
28167 @kindex g C-r
28168 @kindex g C-t
28169 @pindex calc-graph-log-z
28170 @pindex calc-graph-range-z
28171 @pindex calc-graph-title-z
28172 For 3D plots, @kbd{g C-t}, @kbd{g C-r}, and @kbd{g C-l} (those are
28173 letters with the Control key held down) are the corresponding commands
28174 for the ``z'' axis.
28176 @kindex g z
28177 @kindex g Z
28178 @pindex calc-graph-zero-x
28179 @pindex calc-graph-zero-y
28180 The @kbd{g z} (@code{calc-graph-zero-x}) and @kbd{g Z}
28181 (@code{calc-graph-zero-y}) commands control whether a dotted line is
28182 drawn to indicate the ``x'' and/or ``y'' zero axes.  (These are the same
28183 dotted lines that would be drawn there anyway if you used @kbd{g g} to
28184 turn the ``grid'' feature on.)  Zero-axis lines are on by default, and
28185 may be turned off only in GNUPLOT 3.0 and later versions.  They are
28186 not available for 3D plots.
28188 @kindex g s
28189 @pindex calc-graph-line-style
28190 The @kbd{g s} (@code{calc-graph-line-style}) command turns the connecting
28191 lines on or off for the most recently added curve, and optionally selects
28192 the style of lines to be used for that curve.  Plain @kbd{g s} simply
28193 toggles the lines on and off.  With a numeric prefix argument, @kbd{g s}
28194 turns lines on and sets a particular line style.  Line style numbers
28195 start at one and their meanings vary depending on the output device.
28196 GNUPLOT guarantees that there will be at least six different line styles
28197 available for any device.
28199 @kindex g S
28200 @pindex calc-graph-point-style
28201 The @kbd{g S} (@code{calc-graph-point-style}) command similarly turns
28202 the symbols at the data points on or off, or sets the point style.
28203 If you turn both lines and points off, the data points will show as
28204 tiny dots.
28206 @cindex @code{LineStyles} variable
28207 @cindex @code{PointStyles} variable
28208 @vindex LineStyles
28209 @vindex PointStyles
28210 Another way to specify curve styles is with the @code{LineStyles} and
28211 @code{PointStyles} variables.  These variables initially have no stored
28212 values, but if you store a vector of integers in one of these variables,
28213 the @kbd{g a} and @kbd{g f} commands will use those style numbers
28214 instead of the defaults for new curves that are added to the graph.
28215 An entry should be a positive integer for a specific style, or 0 to let
28216 the style be chosen automatically, or @i{-1} to turn off lines or points
28217 altogether.  If there are more curves than elements in the vector, the
28218 last few curves will continue to have the default styles.  Of course,
28219 you can later use @kbd{g s} and @kbd{g S} to change any of these styles.
28221 For example, @kbd{'[2 -1 3] RET s t LineStyles} causes the first curve
28222 to have lines in style number 2, the second curve to have no connecting
28223 lines, and the third curve to have lines in style 3.  Point styles will
28224 still be assigned automatically, but you could store another vector in
28225 @code{PointStyles} to define them, too.
28227 @node Devices, , Graphics Options, Graphics
28228 @section Graphical Devices
28230 @noindent
28231 @kindex g D
28232 @pindex calc-graph-device
28233 The @kbd{g D} (@code{calc-graph-device}) command sets the device name
28234 (or ``terminal name'' in GNUPLOT lingo) to be used by @kbd{g p} commands
28235 on this graph.  It does not affect the permanent default device name.
28236 If you enter a blank name, the device name reverts to the default.
28237 Enter @samp{?} to see a list of supported devices.
28239 With a positive numeric prefix argument, @kbd{g D} instead sets
28240 the default device name, used by all plots in the future which do
28241 not override it with a plain @kbd{g D} command.  If you enter a
28242 blank line this command shows you the current default.  The special
28243 name @code{default} signifies that Calc should choose @code{x11} if
28244 the X window system is in use (as indicated by the presence of a
28245 @code{DISPLAY} environment variable), or otherwise @code{dumb} under
28246 GNUPLOT 3.0 and later, or @code{postscript} under GNUPLOT 2.0.
28247 This is the initial default value.
28249 The @code{dumb} device is an interface to ``dumb terminals,'' i.e.,
28250 terminals with no special graphics facilities.  It writes a crude
28251 picture of the graph composed of characters like @code{-} and @code{|}
28252 to a buffer called @samp{*Gnuplot Trail*}, which Calc then displays.
28253 The graph is made the same size as the Emacs screen, which on most
28254 dumb terminals will be @c{$80\times24$}
28255 @asis{80x24} characters.  The graph is displayed in
28256 an Emacs ``recursive edit''; type @kbd{q} or @kbd{M-# M-#} to exit
28257 the recursive edit and return to Calc.  Note that the @code{dumb}
28258 device is present only in GNUPLOT 3.0 and later versions.
28260 The word @code{dumb} may be followed by two numbers separated by
28261 spaces.  These are the desired width and height of the graph in
28262 characters.  Also, the device name @code{big} is like @code{dumb}
28263 but creates a graph four times the width and height of the Emacs
28264 screen.  You will then have to scroll around to view the entire
28265 graph.  In the @samp{*Gnuplot Trail*} buffer, @key{SPC}, @key{DEL},
28266 @kbd{<}, and @kbd{>} are defined to scroll by one screenful in each
28267 of the four directions.
28269 With a negative numeric prefix argument, @kbd{g D} sets or displays
28270 the device name used by @kbd{g P} (@code{calc-graph-print}).  This
28271 is initially @code{postscript}.  If you don't have a PostScript
28272 printer, you may decide once again to use @code{dumb} to create a
28273 plot on any text-only printer.
28275 @kindex g O
28276 @pindex calc-graph-output
28277 The @kbd{g O} (@code{calc-graph-output}) command sets the name of
28278 the output file used by GNUPLOT.  For some devices, notably @code{x11},
28279 there is no output file and this information is not used.  Many other
28280 ``devices'' are really file formats like @code{postscript}; in these
28281 cases the output in the desired format goes into the file you name
28282 with @kbd{g O}.  Type @kbd{g O stdout RET} to set GNUPLOT to write
28283 to its standard output stream, i.e., to @samp{*Gnuplot Trail*}.
28284 This is the default setting.
28286 Another special output name is @code{tty}, which means that GNUPLOT
28287 is going to write graphics commands directly to its standard output,
28288 which you wish Emacs to pass through to your terminal.  Tektronix
28289 graphics terminals, among other devices, operate this way.  Calc does
28290 this by telling GNUPLOT to write to a temporary file, then running a
28291 sub-shell executing the command @samp{cat tempfile >/dev/tty}.  On
28292 typical Unix systems, this will copy the temporary file directly to
28293 the terminal, bypassing Emacs entirely.  You will have to type @kbd{C-l}
28294 to Emacs afterwards to refresh the screen.
28296 Once again, @kbd{g O} with a positive or negative prefix argument
28297 sets the default or printer output file names, respectively.  In each
28298 case you can specify @code{auto}, which causes Calc to invent a temporary
28299 file name for each @kbd{g p} (or @kbd{g P}) command.  This temporary file
28300 will be deleted once it has been displayed or printed.  If the output file
28301 name is not @code{auto}, the file is not automatically deleted.
28303 The default and printer devices and output files can be saved
28304 permanently by the @kbd{m m} (@code{calc-save-modes}) command.  The
28305 default number of data points (see @kbd{g N}) and the X geometry
28306 (see @kbd{g X}) are also saved.  Other graph information is @emph{not}
28307 saved; you can save a graph's configuration simply by saving the contents
28308 of the @samp{*Gnuplot Commands*} buffer.
28310 @vindex calc-gnuplot-plot-command
28311 @vindex calc-gnuplot-default-device
28312 @vindex calc-gnuplot-default-output
28313 @vindex calc-gnuplot-print-command
28314 @vindex calc-gnuplot-print-device
28315 @vindex calc-gnuplot-print-output
28316 If you are installing Calc you may wish to configure the default and
28317 printer devices and output files for the whole system.  The relevant
28318 Lisp variables are @code{calc-gnuplot-default-device} and @code{-output},
28319 and @code{calc-gnuplot-print-device} and @code{-output}.  The output
28320 file names must be either strings as described above, or Lisp
28321 expressions which are evaluated on the fly to get the output file names.
28323 Other important Lisp variables are @code{calc-gnuplot-plot-command} and
28324 @code{calc-gnuplot-print-command}, which give the system commands to
28325 display or print the output of GNUPLOT, respectively.  These may be
28326 @code{nil} if no command is necessary, or strings which can include
28327 @samp{%s} to signify the name of the file to be displayed or printed.
28328 Or, these variables may contain Lisp expressions which are evaluated
28329 to display or print the output.
28331 @kindex g x
28332 @pindex calc-graph-display
28333 The @kbd{g x} (@code{calc-graph-display}) command lets you specify
28334 on which X window system display your graphs should be drawn.  Enter
28335 a blank line to see the current display name.  This command has no
28336 effect unless the current device is @code{x11}.
28338 @kindex g X
28339 @pindex calc-graph-geometry
28340 The @kbd{g X} (@code{calc-graph-geometry}) command is a similar
28341 command for specifying the position and size of the X window.
28342 The normal value is @code{default}, which generally means your
28343 window manager will let you place the window interactively.
28344 Entering @samp{800x500+0+0} would create an 800-by-500 pixel
28345 window in the upper-left corner of the screen.
28347 The buffer called @samp{*Gnuplot Trail*} holds a transcript of the
28348 session with GNUPLOT.  This shows the commands Calc has ``typed'' to
28349 GNUPLOT and the responses it has received.  Calc tries to notice when an
28350 error message has appeared here and display the buffer for you when
28351 this happens.  You can check this buffer yourself if you suspect
28352 something has gone wrong.
28354 @kindex g C
28355 @pindex calc-graph-command
28356 The @kbd{g C} (@code{calc-graph-command}) command prompts you to
28357 enter any line of text, then simply sends that line to the current
28358 GNUPLOT process.  The @samp{*Gnuplot Trail*} buffer looks deceptively
28359 like a Shell buffer but you can't type commands in it yourself.
28360 Instead, you must use @kbd{g C} for this purpose.
28362 @kindex g v
28363 @kindex g V
28364 @pindex calc-graph-view-commands
28365 @pindex calc-graph-view-trail
28366 The @kbd{g v} (@code{calc-graph-view-commands}) and @kbd{g V}
28367 (@code{calc-graph-view-trail}) commands display the @samp{*Gnuplot Commands*}
28368 and @samp{*Gnuplot Trail*} buffers, respectively, in another window.
28369 This happens automatically when Calc thinks there is something you
28370 will want to see in either of these buffers.  If you type @kbd{g v}
28371 or @kbd{g V} when the relevant buffer is already displayed, the
28372 buffer is hidden again.
28374 One reason to use @kbd{g v} is to add your own commands to the
28375 @samp{*Gnuplot Commands*} buffer.  Press @kbd{g v}, then use
28376 @kbd{C-x o} to switch into that window.  For example, GNUPLOT has
28377 @samp{set label} and @samp{set arrow} commands that allow you to
28378 annotate your plots.  Since Calc doesn't understand these commands,
28379 you have to add them to the @samp{*Gnuplot Commands*} buffer
28380 yourself, then use @w{@kbd{g p}} to replot using these new commands.  Note
28381 that your commands must appear @emph{before} the @code{plot} command.
28382 To get help on any GNUPLOT feature, type, e.g., @kbd{g C help set label}.
28383 You may have to type @kbd{g C RET} a few times to clear the
28384 ``press return for more'' or ``subtopic of @dots{}'' requests.
28385 Note that Calc always sends commands (like @samp{set nolabel}) to
28386 reset all plotting parameters to the defaults before each plot, so
28387 to delete a label all you need to do is delete the @samp{set label}
28388 line you added (or comment it out with @samp{#}) and then replot
28389 with @kbd{g p}.
28391 @kindex g q
28392 @pindex calc-graph-quit
28393 You can use @kbd{g q} (@code{calc-graph-quit}) to kill the GNUPLOT
28394 process that is running.  The next graphing command you give will
28395 start a fresh GNUPLOT process.  The word @samp{Graph} appears in
28396 the Calc window's mode line whenever a GNUPLOT process is currently
28397 running.  The GNUPLOT process is automatically killed when you
28398 exit Emacs if you haven't killed it manually by then.
28400 @kindex g K
28401 @pindex calc-graph-kill
28402 The @kbd{g K} (@code{calc-graph-kill}) command is like @kbd{g q}
28403 except that it also views the @samp{*Gnuplot Trail*} buffer so that
28404 you can see the process being killed.  This is better if you are
28405 killing GNUPLOT because you think it has gotten stuck.
28407 @node Kill and Yank, Keypad Mode, Graphics, Top
28408 @chapter Kill and Yank Functions
28410 @noindent
28411 The commands in this chapter move information between the Calculator and
28412 other Emacs editing buffers.
28414 In many cases Embedded Mode is an easier and more natural way to
28415 work with Calc from a regular editing buffer.  @xref{Embedded Mode}.
28417 @menu
28418 * Killing From Stack::
28419 * Yanking Into Stack::
28420 * Grabbing From Buffers::
28421 * Yanking Into Buffers::
28422 * X Cut and Paste::
28423 @end menu
28425 @node Killing From Stack, Yanking Into Stack, Kill and Yank, Kill and Yank
28426 @section Killing from the Stack
28428 @noindent
28429 @kindex C-k
28430 @pindex calc-kill
28431 @kindex M-k
28432 @pindex calc-copy-as-kill
28433 @kindex C-w
28434 @pindex calc-kill-region
28435 @kindex M-w
28436 @pindex calc-copy-region-as-kill
28437 @cindex Kill ring
28438 @dfn{Kill} commands are Emacs commands that insert text into the
28439 ``kill ring,'' from which it can later be ``yanked'' by a @kbd{C-y}
28440 command.  Three common kill commands in normal Emacs are @kbd{C-k}, which
28441 kills one line, @kbd{C-w}, which kills the region between mark and point,
28442 and @kbd{M-w}, which puts the region into the kill ring without actually
28443 deleting it.  All of these commands work in the Calculator, too.  Also,
28444 @kbd{M-k} has been provided to complete the set; it puts the current line
28445 into the kill ring without deleting anything.
28447 The kill commands are unusual in that they pay attention to the location
28448 of the cursor in the Calculator buffer.  If the cursor is on or below the
28449 bottom line, the kill commands operate on the top of the stack.  Otherwise,
28450 they operate on whatever stack element the cursor is on.  Calc's kill
28451 commands always operate on whole stack entries.  (They act the same as their
28452 standard Emacs cousins except they ``round up'' the specified region to
28453 encompass full lines.)  The text is copied into the kill ring exactly as
28454 it appears on the screen, including line numbers if they are enabled.
28456 A numeric prefix argument to @kbd{C-k} or @kbd{M-k} affects the number
28457 of lines killed.  A positive argument kills the current line and @cite{n-1}
28458 lines below it.  A negative argument kills the @cite{-n} lines above the
28459 current line.  Again this mirrors the behavior of the standard Emacs
28460 @kbd{C-k} command.  Although a whole line is always deleted, @kbd{C-k}
28461 with no argument copies only the number itself into the kill ring, whereas
28462 @kbd{C-k} with a prefix argument of 1 copies the number with its trailing
28463 newline.
28465 @node Yanking Into Stack, Grabbing From Buffers, Killing From Stack, Kill and Yank
28466 @section Yanking into the Stack
28468 @noindent
28469 @kindex C-y
28470 @pindex calc-yank
28471 The @kbd{C-y} command yanks the most recently killed text back into the
28472 Calculator.  It pushes this value onto the top of the stack regardless of
28473 the cursor position.  In general it re-parses the killed text as a number
28474 or formula (or a list of these separated by commas or newlines).  However if
28475 the thing being yanked is something that was just killed from the Calculator
28476 itself, its full internal structure is yanked.  For example, if you have
28477 set the floating-point display mode to show only four significant digits,
28478 then killing and re-yanking 3.14159 (which displays as 3.142) will yank the
28479 full 3.14159, even though yanking it into any other buffer would yank the
28480 number in its displayed form, 3.142.  (Since the default display modes
28481 show all objects to their full precision, this feature normally makes no
28482 difference.)
28484 @node Grabbing From Buffers, Yanking Into Buffers, Yanking Into Stack, Kill and Yank
28485 @section Grabbing from Other Buffers
28487 @noindent
28488 @kindex M-# g
28489 @pindex calc-grab-region
28490 The @kbd{M-# g} (@code{calc-grab-region}) command takes the text between
28491 point and mark in the current buffer and attempts to parse it as a
28492 vector of values.  Basically, it wraps the text in vector brackets
28493 @samp{[ ]} unless the text already is enclosed in vector brackets,
28494 then reads the text as if it were an algebraic entry.  The contents
28495 of the vector may be numbers, formulas, or any other Calc objects.
28496 If the @kbd{M-# g} command works successfully, it does an automatic
28497 @kbd{M-# c} to enter the Calculator buffer.
28499 A numeric prefix argument grabs the specified number of lines around
28500 point, ignoring the mark.  A positive prefix grabs from point to the
28501 @cite{n}th following newline (so that @kbd{M-1 M-# g} grabs from point
28502 to the end of the current line); a negative prefix grabs from point
28503 back to the @cite{n+1}st preceding newline.  In these cases the text
28504 that is grabbed is exactly the same as the text that @kbd{C-k} would
28505 delete given that prefix argument.
28507 A prefix of zero grabs the current line; point may be anywhere on the
28508 line.
28510 A plain @kbd{C-u} prefix interprets the region between point and mark
28511 as a single number or formula rather than a vector.  For example,
28512 @kbd{M-# g} on the text @samp{2 a b} produces the vector of three
28513 values @samp{[2, a, b]}, but @kbd{C-u M-# g} on the same region
28514 reads a formula which is a product of three things:  @samp{2 a b}.
28515 (The text @samp{a + b}, on the other hand, will be grabbed as a
28516 vector of one element by plain @kbd{M-# g} because the interpretation
28517 @samp{[a, +, b]} would be a syntax error.)
28519 If a different language has been specified (@pxref{Language Modes}),
28520 the grabbed text will be interpreted according to that language.
28522 @kindex M-# r
28523 @pindex calc-grab-rectangle
28524 The @kbd{M-# r} (@code{calc-grab-rectangle}) command takes the text between
28525 point and mark and attempts to parse it as a matrix.  If point and mark
28526 are both in the leftmost column, the lines in between are parsed in their
28527 entirety.  Otherwise, point and mark define the corners of a rectangle
28528 whose contents are parsed.
28530 Each line of the grabbed area becomes a row of the matrix.  The result
28531 will actually be a vector of vectors, which Calc will treat as a matrix
28532 only if every row contains the same number of values.
28534 If a line contains a portion surrounded by square brackets (or curly
28535 braces), that portion is interpreted as a vector which becomes a row
28536 of the matrix.  Any text surrounding the bracketed portion on the line
28537 is ignored.
28539 Otherwise, the entire line is interpreted as a row vector as if it
28540 were surrounded by square brackets.  Leading line numbers (in the
28541 format used in the Calc stack buffer) are ignored.  If you wish to
28542 force this interpretation (even if the line contains bracketed
28543 portions), give a negative numeric prefix argument to the
28544 @kbd{M-# r} command.
28546 If you give a numeric prefix argument of zero or plain @kbd{C-u}, each
28547 line is instead interpreted as a single formula which is converted into
28548 a one-element vector.  Thus the result of @kbd{C-u M-# r} will be a
28549 one-column matrix.  For example, suppose one line of the data is the
28550 expression @samp{2 a}.  A plain @w{@kbd{M-# r}} will interpret this as
28551 @samp{[2 a]}, which in turn is read as a two-element vector that forms
28552 one row of the matrix.  But a @kbd{C-u M-# r} will interpret this row
28553 as @samp{[2*a]}.
28555 If you give a positive numeric prefix argument @var{n}, then each line
28556 will be split up into columns of width @var{n}; each column is parsed
28557 separately as a matrix element.  If a line contained
28558 @w{@samp{2 +/- 3 4 +/- 5}}, then grabbing with a prefix argument of 8
28559 would correctly split the line into two error forms.@refill
28561 @xref{Matrix Functions}, to see how to pull the matrix apart into its
28562 constituent rows and columns.  (If it is a @c{$1\times1$}
28563 @asis{1x1} matrix, just hit @kbd{v u}
28564 (@code{calc-unpack}) twice.)
28566 @kindex M-# :
28567 @kindex M-# _
28568 @pindex calc-grab-sum-across
28569 @pindex calc-grab-sum-down
28570 @cindex Summing rows and columns of data
28571 The @kbd{M-# :} (@code{calc-grab-sum-down}) command is a handy way to
28572 grab a rectangle of data and sum its columns.  It is equivalent to
28573 typing @kbd{M-# r}, followed by @kbd{V R : +} (the vector reduction
28574 command that sums the columns of a matrix; @pxref{Reducing}).  The
28575 result of the command will be a vector of numbers, one for each column
28576 in the input data.  The @kbd{M-# _} (@code{calc-grab-sum-across}) command
28577 similarly grabs a rectangle and sums its rows by executing @w{@kbd{V R _ +}}.
28579 As well as being more convenient, @kbd{M-# :} and @kbd{M-# _} are also
28580 much faster because they don't actually place the grabbed vector on
28581 the stack.  In a @kbd{M-# r V R : +} sequence, formatting the vector
28582 for display on the stack takes a large fraction of the total time
28583 (unless you have planned ahead and used @kbd{v .} and @kbd{t .} modes).
28585 For example, suppose we have a column of numbers in a file which we
28586 wish to sum.  Go to one corner of the column and press @kbd{C-@@} to
28587 set the mark; go to the other corner and type @kbd{M-# :}.  Since there
28588 is only one column, the result will be a vector of one number, the sum.
28589 (You can type @kbd{v u} to unpack this vector into a plain number if
28590 you want to do further arithmetic with it.)
28592 To compute the product of the column of numbers, we would have to do
28593 it ``by hand'' since there's no special grab-and-multiply command.
28594 Use @kbd{M-# r} to grab the column of numbers into the calculator in
28595 the form of a column matrix.  The statistics command @kbd{u *} is a
28596 handy way to find the product of a vector or matrix of numbers.
28597 @xref{Statistical Operations}.  Another approach would be to use
28598 an explicit column reduction command, @kbd{V R : *}.
28600 @node Yanking Into Buffers, X Cut and Paste, Grabbing From Buffers, Kill and Yank
28601 @section Yanking into Other Buffers
28603 @noindent
28604 @kindex y
28605 @pindex calc-copy-to-buffer
28606 The plain @kbd{y} (@code{calc-copy-to-buffer}) command inserts the number
28607 at the top of the stack into the most recently used normal editing buffer.
28608 (More specifically, this is the most recently used buffer which is displayed
28609 in a window and whose name does not begin with @samp{*}.  If there is no
28610 such buffer, this is the most recently used buffer except for Calculator
28611 and Calc Trail buffers.)  The number is inserted exactly as it appears and
28612 without a newline.  (If line-numbering is enabled, the line number is
28613 normally not included.)  The number is @emph{not} removed from the stack.
28615 With a prefix argument, @kbd{y} inserts several numbers, one per line.
28616 A positive argument inserts the specified number of values from the top
28617 of the stack.  A negative argument inserts the @cite{n}th value from the
28618 top of the stack.  An argument of zero inserts the entire stack.  Note
28619 that @kbd{y} with an argument of 1 is slightly different from @kbd{y}
28620 with no argument; the former always copies full lines, whereas the
28621 latter strips off the trailing newline.
28623 With a lone @kbd{C-u} as a prefix argument, @kbd{y} @emph{replaces} the
28624 region in the other buffer with the yanked text, then quits the
28625 Calculator, leaving you in that buffer.  A typical use would be to use
28626 @kbd{M-# g} to read a region of data into the Calculator, operate on the
28627 data to produce a new matrix, then type @kbd{C-u y} to replace the
28628 original data with the new data.  One might wish to alter the matrix
28629 display style (@pxref{Vector and Matrix Formats}) or change the current
28630 display language (@pxref{Language Modes}) before doing this.  Also, note
28631 that this command replaces a linear region of text (as grabbed by
28632 @kbd{M-# g}), not a rectangle (as grabbed by @kbd{M-# r}).@refill
28634 If the editing buffer is in overwrite (as opposed to insert) mode,
28635 and the @kbd{C-u} prefix was not used, then the yanked number will
28636 overwrite the characters following point rather than being inserted
28637 before those characters.  The usual conventions of overwrite mode
28638 are observed; for example, characters will be inserted at the end of
28639 a line rather than overflowing onto the next line.  Yanking a multi-line
28640 object such as a matrix in overwrite mode overwrites the next @var{n}
28641 lines in the buffer, lengthening or shortening each line as necessary.
28642 Finally, if the thing being yanked is a simple integer or floating-point
28643 number (like @samp{-1.2345e-3}) and the characters following point also
28644 make up such a number, then Calc will replace that number with the new
28645 number, lengthening or shortening as necessary.  The concept of
28646 ``overwrite mode'' has thus been generalized from overwriting characters
28647 to overwriting one complete number with another.
28649 @kindex M-# y
28650 The @kbd{M-# y} key sequence is equivalent to @kbd{y} except that
28651 it can be typed anywhere, not just in Calc.  This provides an easy
28652 way to guarantee that Calc knows which editing buffer you want to use!
28654 @node X Cut and Paste, , Yanking Into Buffers, Kill and Yank
28655 @section X Cut and Paste
28657 @noindent
28658 If you are using Emacs with the X window system, there is an easier
28659 way to move small amounts of data into and out of the calculator:
28660 Use the mouse-oriented cut and paste facilities of X.
28662 The default bindings for a three-button mouse cause the left button
28663 to move the Emacs cursor to the given place, the right button to
28664 select the text between the cursor and the clicked location, and
28665 the middle button to yank the selection into the buffer at the
28666 clicked location.  So, if you have a Calc window and an editing
28667 window on your Emacs screen, you can use left-click/right-click
28668 to select a number, vector, or formula from one window, then
28669 middle-click to paste that value into the other window.  When you
28670 paste text into the Calc window, Calc interprets it as an algebraic
28671 entry.  It doesn't matter where you click in the Calc window; the
28672 new value is always pushed onto the top of the stack.
28674 The @code{xterm} program that is typically used for general-purpose
28675 shell windows in X interprets the mouse buttons in the same way.
28676 So you can use the mouse to move data between Calc and any other
28677 Unix program.  One nice feature of @code{xterm} is that a double
28678 left-click selects one word, and a triple left-click selects a
28679 whole line.  So you can usually transfer a single number into Calc
28680 just by double-clicking on it in the shell, then middle-clicking
28681 in the Calc window.
28683 @node Keypad Mode, Embedded Mode, Kill and Yank, Introduction
28684 @chapter ``Keypad'' Mode
28686 @noindent
28687 @kindex M-# k
28688 @pindex calc-keypad
28689 The @kbd{M-# k} (@code{calc-keypad}) command starts the Calculator
28690 and displays a picture of a calculator-style keypad.  If you are using
28691 the X window system, you can click on any of the ``keys'' in the
28692 keypad using the left mouse button to operate the calculator.
28693 The original window remains the selected window; in keypad mode
28694 you can type in your file while simultaneously performing
28695 calculations with the mouse.
28697 @pindex full-calc-keypad
28698 If you have used @kbd{M-# b} first, @kbd{M-# k} instead invokes
28699 the @code{full-calc-keypad} command, which takes over the whole
28700 Emacs screen and displays the keypad, the Calc stack, and the Calc
28701 trail all at once.  This mode would normally be used when running
28702 Calc standalone (@pxref{Standalone Operation}).
28704 If you aren't using the X window system, you must switch into
28705 the @samp{*Calc Keypad*} window, place the cursor on the desired
28706 ``key,'' and type @key{SPC} or @key{RET}.  If you think this
28707 is easier than using Calc normally, go right ahead.
28709 Calc commands are more or less the same in keypad mode.  Certain
28710 keypad keys differ slightly from the corresponding normal Calc
28711 keystrokes; all such deviations are described below.
28713 Keypad Mode includes many more commands than will fit on the keypad
28714 at once.  Click the right mouse button [@code{calc-keypad-menu}]
28715 to switch to the next menu.  The bottom five rows of the keypad
28716 stay the same; the top three rows change to a new set of commands.
28717 To return to earlier menus, click the middle mouse button
28718 [@code{calc-keypad-menu-back}] or simply advance through the menus
28719 until you wrap around.  Typing @key{TAB} inside the keypad window
28720 is equivalent to clicking the right mouse button there.
28722 You can always click the @key{EXEC} button and type any normal
28723 Calc key sequence.  This is equivalent to switching into the
28724 Calc buffer, typing the keys, then switching back to your
28725 original buffer.
28727 @menu
28728 * Keypad Main Menu::
28729 * Keypad Functions Menu::
28730 * Keypad Binary Menu::
28731 * Keypad Vectors Menu::
28732 * Keypad Modes Menu::
28733 @end menu
28735 @node Keypad Main Menu, Keypad Functions Menu, Keypad Mode, Keypad Mode
28736 @section Main Menu
28738 @group
28739 @smallexample
28740 |----+-----Calc 2.00-----+----1
28741 |FLR |CEIL|RND |TRNC|CLN2|FLT |
28742 |----+----+----+----+----+----|
28743 | LN |EXP |    |ABS |IDIV|MOD |
28744 |----+----+----+----+----+----|
28745 |SIN |COS |TAN |SQRT|y^x |1/x |
28746 |----+----+----+----+----+----|
28747 |  ENTER  |+/- |EEX |UNDO| <- |
28748 |-----+---+-+--+--+-+---++----|
28749 | INV |  7  |  8  |  9  |  /  |
28750 |-----+-----+-----+-----+-----|
28751 | HYP |  4  |  5  |  6  |  *  |
28752 |-----+-----+-----+-----+-----|
28753 |EXEC |  1  |  2  |  3  |  -  |
28754 |-----+-----+-----+-----+-----|
28755 | OFF |  0  |  .  | PI  |  +  |
28756 |-----+-----+-----+-----+-----+
28757 @end smallexample
28758 @end group
28760 @noindent
28761 This is the menu that appears the first time you start Keypad Mode.
28762 It will show up in a vertical window on the right side of your screen.
28763 Above this menu is the traditional Calc stack display.  On a 24-line
28764 screen you will be able to see the top three stack entries.
28766 The ten digit keys, decimal point, and @key{EEX} key are used for
28767 entering numbers in the obvious way.  @key{EEX} begins entry of an
28768 exponent in scientific notation.  Just as with regular Calc, the
28769 number is pushed onto the stack as soon as you press @key{ENTER}
28770 or any other function key.
28772 The @key{+/-} key corresponds to normal Calc's @kbd{n} key.  During
28773 numeric entry it changes the sign of the number or of the exponent.
28774 At other times it changes the sign of the number on the top of the
28775 stack.
28777 The @key{INV} and @key{HYP} keys modify other keys.  As well as
28778 having the effects described elsewhere in this manual, Keypad Mode
28779 defines several other ``inverse'' operations.  These are described
28780 below and in the following sections.
28782 The @key{ENTER} key finishes the current numeric entry, or otherwise
28783 duplicates the top entry on the stack.
28785 The @key{UNDO} key undoes the most recent Calc operation.
28786 @kbd{INV UNDO} is the ``redo'' command, and @kbd{HYP UNDO} is
28787 ``last arguments'' (@kbd{M-RET}).
28789 The @key{<-} key acts as a ``backspace'' during numeric entry.
28790 At other times it removes the top stack entry.  @kbd{INV <-}
28791 clears the entire stack.  @kbd{HYP <-} takes an integer from
28792 the stack, then removes that many additional stack elements.
28794 The @key{EXEC} key prompts you to enter any keystroke sequence
28795 that would normally work in Calc mode.  This can include a
28796 numeric prefix if you wish.  It is also possible simply to
28797 switch into the Calc window and type commands in it; there is
28798 nothing ``magic'' about this window when Keypad Mode is active.
28800 The other keys in this display perform their obvious calculator
28801 functions.  @key{CLN2} rounds the top-of-stack by temporarily
28802 reducing the precision by 2 digits.  @key{FLT} converts an
28803 integer or fraction on the top of the stack to floating-point.
28805 The @key{INV} and @key{HYP} keys combined with several of these keys
28806 give you access to some common functions even if the appropriate menu
28807 is not displayed.  Obviously you don't need to learn these keys
28808 unless you find yourself wasting time switching among the menus.
28810 @table @kbd
28811 @item INV +/-
28812 is the same as @key{1/x}.
28813 @item INV +
28814 is the same as @key{SQRT}.
28815 @item INV -
28816 is the same as @key{CONJ}.
28817 @item INV *
28818 is the same as @key{y^x}.
28819 @item INV /
28820 is the same as @key{INV y^x} (the @cite{x}th root of @cite{y}).
28821 @item HYP/INV 1
28822 are the same as @key{SIN} / @kbd{INV SIN}.
28823 @item HYP/INV 2
28824 are the same as @key{COS} / @kbd{INV COS}.
28825 @item HYP/INV 3
28826 are the same as @key{TAN} / @kbd{INV TAN}.
28827 @item INV/HYP 4
28828 are the same as @key{LN} / @kbd{HYP LN}.
28829 @item INV/HYP 5
28830 are the same as @key{EXP} / @kbd{HYP EXP}.
28831 @item INV 6
28832 is the same as @key{ABS}.
28833 @item INV 7
28834 is the same as @key{RND} (@code{calc-round}).
28835 @item INV 8
28836 is the same as @key{CLN2}.
28837 @item INV 9
28838 is the same as @key{FLT} (@code{calc-float}).
28839 @item INV 0
28840 is the same as @key{IMAG}.
28841 @item INV .
28842 is the same as @key{PREC}.
28843 @item INV ENTER
28844 is the same as @key{SWAP}.
28845 @item HYP ENTER
28846 is the same as @key{RLL3}.
28847 @item INV HYP ENTER
28848 is the same as @key{OVER}.
28849 @item HYP +/-
28850 packs the top two stack entries as an error form.
28851 @item HYP EEX
28852 packs the top two stack entries as a modulo form.
28853 @item INV EEX
28854 creates an interval form; this removes an integer which is one
28855 of 0 @samp{[]}, 1 @samp{[)}, 2 @samp{(]} or 3 @samp{()}, followed
28856 by the two limits of the interval.
28857 @end table
28859 The @kbd{OFF} key turns Calc off; typing @kbd{M-# k} or @kbd{M-# M-#}
28860 again has the same effect.  This is analogous to typing @kbd{q} or
28861 hitting @kbd{M-# c} again in the normal calculator.  If Calc is
28862 running standalone (the @code{full-calc-keypad} command appeared in the
28863 command line that started Emacs), then @kbd{OFF} is replaced with
28864 @kbd{EXIT}; clicking on this actually exits Emacs itself.
28866 @node Keypad Functions Menu, Keypad Binary Menu, Keypad Main Menu, Keypad Mode
28867 @section Functions Menu
28869 @group
28870 @smallexample
28871 |----+----+----+----+----+----2
28872 |IGAM|BETA|IBET|ERF |BESJ|BESY|
28873 |----+----+----+----+----+----|
28874 |IMAG|CONJ| RE |ATN2|RAND|RAGN|
28875 |----+----+----+----+----+----|
28876 |GCD |FACT|DFCT|BNOM|PERM|NXTP|
28877 |----+----+----+----+----+----|
28878 @end smallexample
28879 @end group
28881 @noindent
28882 This menu provides various operations from the @kbd{f} and @kbd{k}
28883 prefix keys.
28885 @key{IMAG} multiplies the number on the stack by the imaginary
28886 number @cite{i = (0, 1)}.
28888 @key{RE} extracts the real part a complex number.  @kbd{INV RE}
28889 extracts the imaginary part.
28891 @key{RAND} takes a number from the top of the stack and computes
28892 a random number greater than or equal to zero but less than that
28893 number.  (@xref{Random Numbers}.)  @key{RAGN} is the ``random
28894 again'' command; it computes another random number using the
28895 same limit as last time.
28897 @key{INV GCD} computes the LCM (least common multiple) function.
28899 @key{INV FACT} is the gamma function.  @c{$\Gamma(x) = (x-1)!$}
28900 @cite{gamma(x) = (x-1)!}.
28902 @key{PERM} is the number-of-permutations function, which is on the
28903 @kbd{H k c} key in normal Calc.
28905 @key{NXTP} finds the next prime after a number.  @kbd{INV NXTP}
28906 finds the previous prime.
28908 @node Keypad Binary Menu, Keypad Vectors Menu, Keypad Functions Menu, Keypad Mode
28909 @section Binary Menu
28911 @group
28912 @smallexample
28913 |----+----+----+----+----+----3
28914 |AND | OR |XOR |NOT |LSH |RSH |
28915 |----+----+----+----+----+----|
28916 |DEC |HEX |OCT |BIN |WSIZ|ARSH|
28917 |----+----+----+----+----+----|
28918 | A  | B  | C  | D  | E  | F  |
28919 |----+----+----+----+----+----|
28920 @end smallexample
28921 @end group
28923 @noindent
28924 The keys in this menu perform operations on binary integers.
28925 Note that both logical and arithmetic right-shifts are provided.
28926 @key{INV LSH} rotates one bit to the left.
28928 The ``difference'' function (normally on @kbd{b d}) is on @key{INV AND}.
28929 The ``clip'' function (normally on @w{@kbd{b c}}) is on @key{INV NOT}.
28931 The @key{DEC}, @key{HEX}, @key{OCT}, and @key{BIN} keys select the
28932 current radix for display and entry of numbers:  Decimal, hexadecimal,
28933 octal, or binary.  The six letter keys @key{A} through @key{F} are used
28934 for entering hexadecimal numbers.
28936 The @key{WSIZ} key displays the current word size for binary operations
28937 and allows you to enter a new word size.  You can respond to the prompt
28938 using either the keyboard or the digits and @key{ENTER} from the keypad.
28939 The initial word size is 32 bits.
28941 @node Keypad Vectors Menu, Keypad Modes Menu, Keypad Binary Menu, Keypad Mode
28942 @section Vectors Menu
28944 @group
28945 @smallexample
28946 |----+----+----+----+----+----4
28947 |SUM |PROD|MAX |MAP*|MAP^|MAP$|
28948 |----+----+----+----+----+----|
28949 |MINV|MDET|MTRN|IDNT|CRSS|"x" |
28950 |----+----+----+----+----+----|
28951 |PACK|UNPK|INDX|BLD |LEN |... |
28952 |----+----+----+----+----+----|
28953 @end smallexample
28954 @end group
28956 @noindent
28957 The keys in this menu operate on vectors and matrices.
28959 @key{PACK} removes an integer @var{n} from the top of the stack;
28960 the next @var{n} stack elements are removed and packed into a vector,
28961 which is replaced onto the stack.  Thus the sequence
28962 @kbd{1 ENTER 3 ENTER 5 ENTER 3 PACK} enters the vector
28963 @samp{[1, 3, 5]} onto the stack.  To enter a matrix, build each row
28964 on the stack as a vector, then use a final @key{PACK} to collect the
28965 rows into a matrix.
28967 @key{UNPK} unpacks the vector on the stack, pushing each of its
28968 components separately.
28970 @key{INDX} removes an integer @var{n}, then builds a vector of
28971 integers from 1 to @var{n}.  @kbd{INV INDX} takes three numbers
28972 from the stack:  The vector size @var{n}, the starting number,
28973 and the increment.  @kbd{BLD} takes an integer @var{n} and any
28974 value @var{x} and builds a vector of @var{n} copies of @var{x}.
28976 @key{IDNT} removes an integer @var{n}, then builds an @var{n}-by-@var{n}
28977 identity matrix.
28979 @key{LEN} replaces a vector by its length, an integer.
28981 @key{...} turns on or off ``abbreviated'' display mode for large vectors.
28983 @key{MINV}, @key{MDET}, @key{MTRN}, and @key{CROSS} are the matrix
28984 inverse, determinant, and transpose, and vector cross product.
28986 @key{SUM} replaces a vector by the sum of its elements.  It is
28987 equivalent to @kbd{u +} in normal Calc (@pxref{Statistical Operations}).
28988 @key{PROD} computes the product of the elements of a vector, and
28989 @key{MAX} computes the maximum of all the elements of a vector.
28991 @key{INV SUM} computes the alternating sum of the first element
28992 minus the second, plus the third, minus the fourth, and so on.
28993 @key{INV MAX} computes the minimum of the vector elements.
28995 @key{HYP SUM} computes the mean of the vector elements.
28996 @key{HYP PROD} computes the sample standard deviation.
28997 @key{HYP MAX} computes the median.
28999 @key{MAP*} multiplies two vectors elementwise.  It is equivalent
29000 to the @kbd{V M *} command.  @key{MAP^} computes powers elementwise.
29001 The arguments must be vectors of equal length, or one must be a vector
29002 and the other must be a plain number.  For example, @kbd{2 MAP^} squares
29003 all the elements of a vector.
29005 @key{MAP$} maps the formula on the top of the stack across the
29006 vector in the second-to-top position.  If the formula contains
29007 several variables, Calc takes that many vectors starting at the
29008 second-to-top position and matches them to the variables in
29009 alphabetical order.  The result is a vector of the same size as
29010 the input vectors, whose elements are the formula evaluated with
29011 the variables set to the various sets of numbers in those vectors.
29012 For example, you could simulate @key{MAP^} using @key{MAP$} with
29013 the formula @samp{x^y}.
29015 The @kbd{"x"} key pushes the variable name @cite{x} onto the
29016 stack.  To build the formula @cite{x^2 + 6}, you would use the
29017 key sequence @kbd{"x" 2 y^x 6 +}.  This formula would then be
29018 suitable for use with the @key{MAP$} key described above.
29019 With @key{INV}, @key{HYP}, or @key{INV} and @key{HYP}, the
29020 @kbd{"x"} key pushes the variable names @cite{y}, @cite{z}, and
29021 @cite{t}, respectively.
29023 @node Keypad Modes Menu, , Keypad Vectors Menu, Keypad Mode
29024 @section Modes Menu
29026 @group
29027 @smallexample
29028 |----+----+----+----+----+----5
29029 |FLT |FIX |SCI |ENG |GRP |    |
29030 |----+----+----+----+----+----|
29031 |RAD |DEG |FRAC|POLR|SYMB|PREC|
29032 |----+----+----+----+----+----|
29033 |SWAP|RLL3|RLL4|OVER|STO |RCL |
29034 |----+----+----+----+----+----|
29035 @end smallexample
29036 @end group
29038 @noindent
29039 The keys in this menu manipulate modes, variables, and the stack.
29041 The @key{FLT}, @key{FIX}, @key{SCI}, and @key{ENG} keys select
29042 floating-point, fixed-point, scientific, or engineering notation.
29043 @key{FIX} displays two digits after the decimal by default; the
29044 others display full precision.  With the @key{INV} prefix, these
29045 keys pop a number-of-digits argument from the stack.
29047 The @key{GRP} key turns grouping of digits with commas on or off.
29048 @kbd{INV GRP} enables grouping to the right of the decimal point as
29049 well as to the left.
29051 The @key{RAD} and @key{DEG} keys switch between radians and degrees
29052 for trigonometric functions.
29054 The @key{FRAC} key turns Fraction mode on or off.  This affects
29055 whether commands like @kbd{/} with integer arguments produce
29056 fractional or floating-point results.
29058 The @key{POLR} key turns Polar mode on or off, determining whether
29059 polar or rectangular complex numbers are used by default.
29061 The @key{SYMB} key turns Symbolic mode on or off, in which
29062 operations that would produce inexact floating-point results
29063 are left unevaluated as algebraic formulas.
29065 The @key{PREC} key selects the current precision.  Answer with
29066 the keyboard or with the keypad digit and @key{ENTER} keys.
29068 The @key{SWAP} key exchanges the top two stack elements.
29069 The @key{RLL3} key rotates the top three stack elements upwards.
29070 The @key{RLL4} key rotates the top four stack elements upwards.
29071 The @key{OVER} key duplicates the second-to-top stack element.
29073 The @key{STO} and @key{RCL} keys are analogous to @kbd{s t} and
29074 @kbd{s r} in regular Calc.  @xref{Store and Recall}.  Click the
29075 @key{STO} or @key{RCL} key, then one of the ten digits.  (Named
29076 variables are not available in Keypad Mode.)  You can also use,
29077 for example, @kbd{STO + 3} to add to register 3.
29079 @node Embedded Mode, Programming, Keypad Mode, Top
29080 @chapter Embedded Mode
29082 @noindent
29083 Embedded Mode in Calc provides an alternative to copying numbers
29084 and formulas back and forth between editing buffers and the Calc
29085 stack.  In Embedded Mode, your editing buffer becomes temporarily
29086 linked to the stack and this copying is taken care of automatically.
29088 @menu
29089 * Basic Embedded Mode::
29090 * More About Embedded Mode::
29091 * Assignments in Embedded Mode::
29092 * Mode Settings in Embedded Mode::
29093 * Customizing Embedded Mode::
29094 @end menu
29096 @node Basic Embedded Mode, More About Embedded Mode, Embedded Mode, Embedded Mode
29097 @section Basic Embedded Mode
29099 @noindent
29100 @kindex M-# e
29101 @pindex calc-embedded
29102 To enter Embedded mode, position the Emacs point (cursor) on a
29103 formula in any buffer and press @kbd{M-# e} (@code{calc-embedded}).
29104 Note that @kbd{M-# e} is not to be used in the Calc stack buffer
29105 like most Calc commands, but rather in regular editing buffers that
29106 are visiting your own files.
29108 Calc normally scans backward and forward in the buffer for the
29109 nearest opening and closing @dfn{formula delimiters}.  The simplest
29110 delimiters are blank lines.  Other delimiters that Embedded Mode
29111 understands are:
29113 @enumerate
29114 @item
29115 The @TeX{} and La@TeX{} math delimiters @samp{$ $}, @samp{$$ $$},
29116 @samp{\[ \]}, and @samp{\( \)};
29117 @item
29118 Lines beginning with @samp{\begin} and @samp{\end};
29119 @item
29120 Lines beginning with @samp{@@} (Texinfo delimiters).
29121 @item
29122 Lines beginning with @samp{.EQ} and @samp{.EN} (@dfn{eqn} delimiters);
29123 @item
29124 Lines containing a single @samp{%} or @samp{.\"} symbol and nothing else.
29125 @end enumerate
29127 @xref{Customizing Embedded Mode}, to see how to make Calc recognize
29128 your own favorite delimiters.  Delimiters like @samp{$ $} can appear
29129 on their own separate lines or in-line with the formula.
29131 If you give a positive or negative numeric prefix argument, Calc
29132 instead uses the current point as one end of the formula, and moves
29133 forward or backward (respectively) by that many lines to find the
29134 other end.  Explicit delimiters are not necessary in this case.
29136 With a prefix argument of zero, Calc uses the current region
29137 (delimited by point and mark) instead of formula delimiters.
29139 @kindex M-# w
29140 @pindex calc-embedded-word
29141 With a prefix argument of @kbd{C-u} only, Calc scans for the first
29142 non-numeric character (i.e., the first character that is not a
29143 digit, sign, decimal point, or upper- or lower-case @samp{e})
29144 forward and backward to delimit the formula.  @kbd{M-# w}
29145 (@code{calc-embedded-word}) is equivalent to @kbd{C-u M-# e}.
29147 When you enable Embedded mode for a formula, Calc reads the text
29148 between the delimiters and tries to interpret it as a Calc formula.
29149 It's best if the current Calc language mode is correct for the
29150 formula, but Calc can generally identify @TeX{} formulas and
29151 Big-style formulas even if the language mode is wrong.  If Calc
29152 can't make sense of the formula, it beeps and refuses to enter
29153 Embedded mode.  But if the current language is wrong, Calc can
29154 sometimes parse the formula successfully (but incorrectly);
29155 for example, the C expression @samp{atan(a[1])} can be parsed
29156 in Normal language mode, but the @code{atan} won't correspond to
29157 the built-in @code{arctan} function, and the @samp{a[1]} will be
29158 interpreted as @samp{a} times the vector @samp{[1]}!
29160 If you press @kbd{M-# e} or @kbd{M-# w} to activate an embedded
29161 formula which is blank, say with the cursor on the space between
29162 the two delimiters @samp{$ $}, Calc will immediately prompt for
29163 an algebraic entry.
29165 Only one formula in one buffer can be enabled at a time.  If you
29166 move to another area of the current buffer and give Calc commands,
29167 Calc turns Embedded mode off for the old formula and then tries
29168 to restart Embedded mode at the new position.  Other buffers are
29169 not affected by Embedded mode.
29171 When Embedded mode begins, Calc pushes the current formula onto
29172 the stack.  No Calc stack window is created; however, Calc copies
29173 the top-of-stack position into the original buffer at all times.
29174 You can create a Calc window by hand with @kbd{M-# o} if you
29175 find you need to see the entire stack.
29177 For example, typing @kbd{M-# e} while somewhere in the formula
29178 @samp{n>2} in the following line enables Embedded mode on that
29179 inequality:
29181 @example
29182 We define $F_n = F_(n-1)+F_(n-2)$ for all $n>2$.
29183 @end example
29185 @noindent
29186 The formula @cite{n>2} will be pushed onto the Calc stack, and
29187 the top of stack will be copied back into the editing buffer.
29188 This means that spaces will appear around the @samp{>} symbol
29189 to match Calc's usual display style:
29191 @example
29192 We define $F_n = F_(n-1)+F_(n-2)$ for all $n > 2$.
29193 @end example
29195 @noindent
29196 No spaces have appeared around the @samp{+} sign because it's
29197 in a different formula, one which we have not yet touched with
29198 Embedded mode.
29200 Now that Embedded mode is enabled, keys you type in this buffer
29201 are interpreted as Calc commands.  At this point we might use
29202 the ``commute'' command @kbd{j C} to reverse the inequality.
29203 This is a selection-based command for which we first need to
29204 move the cursor onto the operator (@samp{>} in this case) that
29205 needs to be commuted.
29207 @example
29208 We define $F_n = F_(n-1)+F_(n-2)$ for all $2 < n$.
29209 @end example
29211 The @kbd{M-# o} command is a useful way to open a Calc window
29212 without actually selecting that window.  Giving this command
29213 verifies that @samp{2 < n} is also on the Calc stack.  Typing
29214 @kbd{17 RET} would produce:
29216 @example
29217 We define $F_n = F_(n-1)+F_(n-2)$ for all $17$.
29218 @end example
29220 @noindent
29221 with @samp{2 < n} and @samp{17} on the stack; typing @key{TAB}
29222 at this point will exchange the two stack values and restore
29223 @samp{2 < n} to the embedded formula.  Even though you can't
29224 normally see the stack in Embedded mode, it is still there and
29225 it still operates in the same way.  But, as with old-fashioned
29226 RPN calculators, you can only see the value at the top of the
29227 stack at any given time (unless you use @kbd{M-# o}).
29229 Typing @kbd{M-# e} again turns Embedded mode off.  The Calc
29230 window reveals that the formula @w{@samp{2 < n}} is automatically
29231 removed from the stack, but the @samp{17} is not.  Entering
29232 Embedded mode always pushes one thing onto the stack, and
29233 leaving Embedded mode always removes one thing.  Anything else
29234 that happens on the stack is entirely your business as far as
29235 Embedded mode is concerned.
29237 If you press @kbd{M-# e} in the wrong place by accident, it is
29238 possible that Calc will be able to parse the nearby text as a
29239 formula and will mangle that text in an attempt to redisplay it
29240 ``properly'' in the current language mode.  If this happens,
29241 press @kbd{M-# e} again to exit Embedded mode, then give the
29242 regular Emacs ``undo'' command (@kbd{C-_} or @kbd{C-x u}) to put
29243 the text back the way it was before Calc edited it.  Note that Calc's
29244 own Undo command (typed before you turn Embedded mode back off)
29245 will not do you any good, because as far as Calc is concerned
29246 you haven't done anything with this formula yet.
29248 @node More About Embedded Mode, Assignments in Embedded Mode, Basic Embedded Mode, Embedded Mode
29249 @section More About Embedded Mode
29251 @noindent
29252 When Embedded mode ``activates'' a formula, i.e., when it examines
29253 the formula for the first time since the buffer was created or
29254 loaded, Calc tries to sense the language in which the formula was
29255 written.  If the formula contains any @TeX{}-like @samp{\} sequences,
29256 it is parsed (i.e., read) in @TeX{} mode.  If the formula appears to
29257 be written in multi-line Big mode, it is parsed in Big mode.  Otherwise,
29258 it is parsed according to the current language mode.
29260 Note that Calc does not change the current language mode according
29261 to what it finds.  Even though it can read a @TeX{} formula when
29262 not in @TeX{} mode, it will immediately rewrite this formula using
29263 whatever language mode is in effect.  You must then type @kbd{d T}
29264 to switch Calc permanently into @TeX{} mode if that is what you
29265 desire.
29267 @tex
29268 \bigskip
29269 @end tex
29271 @kindex d p
29272 @pindex calc-show-plain
29273 Calc's parser is unable to read certain kinds of formulas.  For
29274 example, with @kbd{v ]} (@code{calc-matrix-brackets}) you can
29275 specify matrix display styles which the parser is unable to
29276 recognize as matrices.  The @kbd{d p} (@code{calc-show-plain})
29277 command turns on a mode in which a ``plain'' version of a
29278 formula is placed in front of the fully-formatted version.
29279 When Calc reads a formula that has such a plain version in
29280 front, it reads the plain version and ignores the formatted
29281 version.
29283 Plain formulas are preceded and followed by @samp{%%%} signs
29284 by default.  This notation has the advantage that the @samp{%}
29285 character begins a comment in @TeX{}, so if your formula is
29286 embedded in a @TeX{} document its plain version will be
29287 invisible in the final printed copy.  @xref{Customizing
29288 Embedded Mode}, to see how to change the ``plain'' formula
29289 delimiters, say to something that @dfn{eqn} or some other
29290 formatter will treat as a comment.
29292 There are several notations which Calc's parser for ``big''
29293 formatted formulas can't yet recognize.  In particular, it can't
29294 read the large symbols for @code{sum}, @code{prod}, and @code{integ},
29295 and it can't handle @samp{=>} with the righthand argument omitted.
29296 Also, Calc won't recognize special formats you have defined with
29297 the @kbd{Z C} command (@pxref{User-Defined Compositions}).  In
29298 these cases it is important to use ``plain'' mode to make sure
29299 Calc will be able to read your formula later.
29301 Another example where ``plain'' mode is important is if you have
29302 specified a float mode with few digits of precision.  Normally
29303 any digits that are computed but not displayed will simply be
29304 lost when you save and re-load your embedded buffer, but ``plain''
29305 mode allows you to make sure that the complete number is present
29306 in the file as well as the rounded-down number.
29308 @tex
29309 \bigskip
29310 @end tex
29312 Embedded buffers remember active formulas for as long as they
29313 exist in Emacs memory.  Suppose you have an embedded formula
29314 which is @c{$\pi$}
29315 @cite{pi} to the normal 12 decimal places, and then
29316 type @w{@kbd{C-u 5 d n}} to display only five decimal places.
29317 If you then type @kbd{d n}, all 12 places reappear because the
29318 full number is still there on the Calc stack.  More surprisingly,
29319 even if you exit Embedded mode and later re-enter it for that
29320 formula, typing @kbd{d n} will restore all 12 places because
29321 each buffer remembers all its active formulas.  However, if you
29322 save the buffer in a file and reload it in a new Emacs session,
29323 all non-displayed digits will have been lost unless you used
29324 ``plain'' mode.
29326 @tex
29327 \bigskip
29328 @end tex
29330 In some applications of Embedded mode, you will want to have a
29331 sequence of copies of a formula that show its evolution as you
29332 work on it.  For example, you might want to have a sequence
29333 like this in your file (elaborating here on the example from
29334 the ``Getting Started'' chapter):
29336 @smallexample
29337 The derivative of
29339                               ln(ln(x))
29343                   @r{(the derivative of }ln(ln(x))@r{)}
29345 whose value at x = 2 is
29347                             @r{(the value)}
29349 and at x = 3 is
29351                             @r{(the value)}
29352 @end smallexample
29354 @kindex M-# d
29355 @pindex calc-embedded-duplicate
29356 The @kbd{M-# d} (@code{calc-embedded-duplicate}) command is a
29357 handy way to make sequences like this.  If you type @kbd{M-# d},
29358 the formula under the cursor (which may or may not have Embedded
29359 mode enabled for it at the time) is copied immediately below and
29360 Embedded mode is then enabled for that copy.
29362 For this example, you would start with just
29364 @smallexample
29365 The derivative of
29367                               ln(ln(x))
29368 @end smallexample
29370 @noindent
29371 and press @kbd{M-# d} with the cursor on this formula.  The result
29374 @smallexample
29375 The derivative of
29377                               ln(ln(x))
29380                               ln(ln(x))
29381 @end smallexample
29383 @noindent
29384 with the second copy of the formula enabled in Embedded mode.
29385 You can now press @kbd{a d x RET} to take the derivative, and
29386 @kbd{M-# d M-# d} to make two more copies of the derivative.
29387 To complete the computations, type @kbd{3 s l x RET} to evaluate
29388 the last formula, then move up to the second-to-last formula
29389 and type @kbd{2 s l x RET}.
29391 Finally, you would want to press @kbd{M-# e} to exit Embedded
29392 mode, then go up and insert the necessary text in between the
29393 various formulas and numbers.
29395 @tex
29396 \bigskip
29397 @end tex
29399 @kindex M-# f
29400 @kindex M-# '
29401 @pindex calc-embedded-new-formula
29402 The @kbd{M-# f} (@code{calc-embedded-new-formula}) command
29403 creates a new embedded formula at the current point.  It inserts
29404 some default delimiters, which are usually just blank lines,
29405 and then does an algebraic entry to get the formula (which is
29406 then enabled for Embedded mode).  This is just shorthand for
29407 typing the delimiters yourself, positioning the cursor between
29408 the new delimiters, and pressing @kbd{M-# e}.  The key sequence
29409 @kbd{M-# '} is equivalent to @kbd{M-# f}.
29411 @kindex M-# n
29412 @kindex M-# p
29413 @pindex calc-embedded-next
29414 @pindex calc-embedded-previous
29415 The @kbd{M-# n} (@code{calc-embedded-next}) and @kbd{M-# p}
29416 (@code{calc-embedded-previous}) commands move the cursor to the
29417 next or previous active embedded formula in the buffer.  They
29418 can take positive or negative prefix arguments to move by several
29419 formulas.  Note that these commands do not actually examine the
29420 text of the buffer looking for formulas; they only see formulas
29421 which have previously been activated in Embedded mode.  In fact,
29422 @kbd{M-# n} and @kbd{M-# p} are a useful way to tell which
29423 embedded formulas are currently active.  Also, note that these
29424 commands do not enable Embedded mode on the next or previous
29425 formula, they just move the cursor.  (By the way, @kbd{M-# n} is
29426 not as awkward to type as it may seem, because @kbd{M-#} ignores
29427 Shift and Meta on the second keystroke:  @kbd{M-# M-N} can be typed
29428 by holding down Shift and Meta and alternately typing two keys.)
29430 @kindex M-# `
29431 @pindex calc-embedded-edit
29432 The @kbd{M-# `} (@code{calc-embedded-edit}) command edits the
29433 embedded formula at the current point as if by @kbd{`} (@code{calc-edit}).
29434 Embedded mode does not have to be enabled for this to work.  Press
29435 @kbd{M-# M-#} to finish the edit, or @kbd{M-# x} to cancel.
29437 @node Assignments in Embedded Mode, Mode Settings in Embedded Mode, More About Embedded Mode, Embedded Mode
29438 @section Assignments in Embedded Mode
29440 @noindent
29441 The @samp{:=} (assignment) and @samp{=>} (``evaluates-to'') operators
29442 are especially useful in Embedded mode.  They allow you to make
29443 a definition in one formula, then refer to that definition in
29444 other formulas embedded in the same buffer.
29446 An embedded formula which is an assignment to a variable, as in
29448 @example
29449 foo := 5
29450 @end example
29452 @noindent
29453 records @cite{5} as the stored value of @code{foo} for the
29454 purposes of Embedded mode operations in the current buffer.  It
29455 does @emph{not} actually store @cite{5} as the ``global'' value
29456 of @code{foo}, however.  Regular Calc operations, and Embedded
29457 formulas in other buffers, will not see this assignment.
29459 One way to use this assigned value is simply to create an
29460 Embedded formula elsewhere that refers to @code{foo}, and to press
29461 @kbd{=} in that formula.  However, this permanently replaces the
29462 @code{foo} in the formula with its current value.  More interesting
29463 is to use @samp{=>} elsewhere:
29465 @example
29466 foo + 7 => 12
29467 @end example
29469 @xref{Evaluates-To Operator}, for a general discussion of @samp{=>}.
29471 If you move back and change the assignment to @code{foo}, any
29472 @samp{=>} formulas which refer to it are automatically updated.
29474 @example
29475 foo := 17
29477 foo + 7 => 24
29478 @end example
29480 The obvious question then is, @emph{how} can one easily change the
29481 assignment to @code{foo}?  If you simply select the formula in
29482 Embedded mode and type 17, the assignment itself will be replaced
29483 by the 17.  The effect on the other formula will be that the
29484 variable @code{foo} becomes unassigned:
29486 @example
29489 foo + 7 => foo + 7
29490 @end example
29492 The right thing to do is first to use a selection command (@kbd{j 2}
29493 will do the trick) to select the righthand side of the assignment.
29494 Then, @kbd{17 TAB DEL} will swap the 17 into place (@pxref{Selecting
29495 Subformulas}, to see how this works).
29497 @kindex M-# j
29498 @pindex calc-embedded-select
29499 The @kbd{M-# j} (@code{calc-embedded-select}) command provides an
29500 easy way to operate on assigments.  It is just like @kbd{M-# e},
29501 except that if the enabled formula is an assignment, it uses
29502 @kbd{j 2} to select the righthand side.  If the enabled formula
29503 is an evaluates-to, it uses @kbd{j 1} to select the lefthand side.
29504 A formula can also be a combination of both:
29506 @example
29507 bar := foo + 3 => 20
29508 @end example
29510 @noindent
29511 in which case @kbd{M-# j} will select the middle part (@samp{foo + 3}).
29513 The formula is automatically deselected when you leave Embedded
29514 mode.
29516 @kindex M-# u
29517 @kindex M-# =
29518 @pindex calc-embedded-update
29519 Another way to change the assignment to @code{foo} would simply be
29520 to edit the number using regular Emacs editing rather than Embedded
29521 mode.  Then, we have to find a way to get Embedded mode to notice
29522 the change.  The @kbd{M-# u} or @kbd{M-# =}
29523 (@code{calc-embedded-update-formula}) command is a convenient way
29524 to do this.@refill
29526 @example
29527 foo := 6
29529 foo + 7 => 13
29530 @end example
29532 Pressing @kbd{M-# u} is much like pressing @kbd{M-# e = M-# e}, that
29533 is, temporarily enabling Embedded mode for the formula under the
29534 cursor and then evaluating it with @kbd{=}.  But @kbd{M-# u} does
29535 not actually use @kbd{M-# e}, and in fact another formula somewhere
29536 else can be enabled in Embedded mode while you use @kbd{M-# u} and
29537 that formula will not be disturbed.
29539 With a numeric prefix argument, @kbd{M-# u} updates all active
29540 @samp{=>} formulas in the buffer.  Formulas which have not yet
29541 been activated in Embedded mode, and formulas which do not have
29542 @samp{=>} as their top-level operator, are not affected by this.
29543 (This is useful only if you have used @kbd{m C}; see below.)
29545 With a plain @kbd{C-u} prefix, @kbd{C-u M-# u} updates only in the
29546 region between mark and point rather than in the whole buffer.
29548 @kbd{M-# u} is also a handy way to activate a formula, such as an
29549 @samp{=>} formula that has freshly been typed in or loaded from a
29550 file.
29552 @kindex M-# a
29553 @pindex calc-embedded-activate
29554 The @kbd{M-# a} (@code{calc-embedded-activate}) command scans
29555 through the current buffer and activates all embedded formulas
29556 that contain @samp{:=} or @samp{=>} symbols.  This does not mean
29557 that Embedded mode is actually turned on, but only that the
29558 formulas' positions are registered with Embedded mode so that
29559 the @samp{=>} values can be properly updated as assignments are
29560 changed.
29562 It is a good idea to type @kbd{M-# a} right after loading a file
29563 that uses embedded @samp{=>} operators.  Emacs includes a nifty
29564 ``buffer-local variables'' feature that you can use to do this
29565 automatically.  The idea is to place near the end of your file
29566 a few lines that look like this:
29568 @example
29569 --- Local Variables: ---
29570 --- eval:(calc-embedded-activate) ---
29571 --- End: ---
29572 @end example
29574 @noindent
29575 where the leading and trailing @samp{---} can be replaced by
29576 any suitable strings (which must be the same on all three lines)
29577 or omitted altogether; in a @TeX{} file, @samp{%} would be a good
29578 leading string and no trailing string would be necessary.  In a
29579 C program, @samp{/*} and @samp{*/} would be good leading and
29580 trailing strings.
29582 When Emacs loads a file into memory, it checks for a Local Variables
29583 section like this one at the end of the file.  If it finds this
29584 section, it does the specified things (in this case, running
29585 @kbd{M-# a} automatically) before editing of the file begins.
29586 The Local Variables section must be within 3000 characters of the
29587 end of the file for Emacs to find it, and it must be in the last
29588 page of the file if the file has any page separators.
29589 @xref{File Variables, , Local Variables in Files, emacs, the
29590 Emacs manual}.
29592 Note that @kbd{M-# a} does not update the formulas it finds.
29593 To do this, type, say, @kbd{M-1 M-# u} after @w{@kbd{M-# a}}.
29594 Generally this should not be a problem, though, because the
29595 formulas will have been up-to-date already when the file was
29596 saved.
29598 Normally, @kbd{M-# a} activates all the formulas it finds, but
29599 any previous active formulas remain active as well.  With a
29600 positive numeric prefix argument, @kbd{M-# a} first deactivates
29601 all current active formulas, then actives the ones it finds in
29602 its scan of the buffer.  With a negative prefix argument,
29603 @kbd{M-# a} simply deactivates all formulas.
29605 Embedded mode has two symbols, @samp{Active} and @samp{~Active},
29606 which it puts next to the major mode name in a buffer's mode line.
29607 It puts @samp{Active} if it has reason to believe that all
29608 formulas in the buffer are active, because you have typed @kbd{M-# a}
29609 and Calc has not since had to deactivate any formulas (which can
29610 happen if Calc goes to update an @samp{=>} formula somewhere because
29611 a variable changed, and finds that the formula is no longer there
29612 due to some kind of editing outside of Embedded mode).  Calc puts
29613 @samp{~Active} in the mode line if some, but probably not all,
29614 formulas in the buffer are active.  This happens if you activate
29615 a few formulas one at a time but never use @kbd{M-# a}, or if you
29616 used @kbd{M-# a} but then Calc had to deactivate a formula
29617 because it lost track of it.  If neither of these symbols appears
29618 in the mode line, no embedded formulas are active in the buffer
29619 (e.g., before Embedded mode has been used, or after a @kbd{M-- M-# a}).
29621 Embedded formulas can refer to assignments both before and after them
29622 in the buffer.  If there are several assignments to a variable, the
29623 nearest preceding assignment is used if there is one, otherwise the
29624 following assignment is used.
29626 @example
29627 x => 1
29629 x := 1
29631 x => 1
29633 x := 2
29635 x => 2
29636 @end example
29638 As well as simple variables, you can also assign to subscript
29639 expressions of the form @samp{@var{var}_@var{number}} (as in
29640 @code{x_0}), or @samp{@var{var}_@var{var}} (as in @code{x_max}).
29641 Assignments to other kinds of objects can be represented by Calc,
29642 but the automatic linkage between assignments and references works
29643 only for plain variables and these two kinds of subscript expressions.
29645 If there are no assignments to a given variable, the global
29646 stored value for the variable is used (@pxref{Storing Variables}),
29647 or, if no value is stored, the variable is left in symbolic form.
29648 Note that global stored values will be lost when the file is saved
29649 and loaded in a later Emacs session, unless you have used the
29650 @kbd{s p} (@code{calc-permanent-variable}) command to save them;
29651 @pxref{Operations on Variables}.
29653 The @kbd{m C} (@code{calc-auto-recompute}) command turns automatic
29654 recomputation of @samp{=>} forms on and off.  If you turn automatic
29655 recomputation off, you will have to use @kbd{M-# u} to update these
29656 formulas manually after an assignment has been changed.  If you
29657 plan to change several assignments at once, it may be more efficient
29658 to type @kbd{m C}, change all the assignments, then use @kbd{M-1 M-# u}
29659 to update the entire buffer afterwards.  The @kbd{m C} command also
29660 controls @samp{=>} formulas on the stack; @pxref{Evaluates-To
29661 Operator}.  When you turn automatic recomputation back on, the
29662 stack will be updated but the Embedded buffer will not; you must
29663 use @kbd{M-# u} to update the buffer by hand.
29665 @node Mode Settings in Embedded Mode, Customizing Embedded Mode, Assignments in Embedded Mode, Embedded Mode
29666 @section Mode Settings in Embedded Mode
29668 @noindent
29669 Embedded Mode has a rather complicated mechanism for handling mode
29670 settings in Embedded formulas.  It is possible to put annotations
29671 in the file that specify mode settings either global to the entire
29672 file or local to a particular formula or formulas.  In the latter
29673 case, different modes can be specified for use when a formula
29674 is the enabled Embedded Mode formula.
29676 When you give any mode-setting command, like @kbd{m f} (for fraction
29677 mode) or @kbd{d s} (for scientific notation), Embedded Mode adds
29678 a line like the following one to the file just before the opening
29679 delimiter of the formula.
29681 @example
29682 % [calc-mode: fractions: t]
29683 % [calc-mode: float-format: (sci 0)]
29684 @end example
29686 When Calc interprets an embedded formula, it scans the text before
29687 the formula for mode-setting annotations like these and sets the
29688 Calc buffer to match these modes.  Modes not explicitly described
29689 in the file are not changed.  Calc scans all the way to the top of
29690 the file, or up to a line of the form
29692 @example
29693 % [calc-defaults]
29694 @end example
29696 @noindent
29697 which you can insert at strategic places in the file if this backward
29698 scan is getting too slow, or just to provide a barrier between one
29699 ``zone'' of mode settings and another.
29701 If the file contains several annotations for the same mode, the
29702 closest one before the formula is used.  Annotations after the
29703 formula are never used (except for global annotations, described
29704 below).
29706 The scan does not look for the leading @samp{% }, only for the
29707 square brackets and the text they enclose.  You can edit the mode
29708 annotations to a style that works better in context if you wish.
29709 @xref{Customizing Embedded Mode}, to see how to change the style
29710 that Calc uses when it generates the annotations.  You can write
29711 mode annotations into the file yourself if you know the syntax;
29712 the easiest way to find the syntax for a given mode is to let
29713 Calc write the annotation for it once and see what it does.
29715 If you give a mode-changing command for a mode that already has
29716 a suitable annotation just above the current formula, Calc will
29717 modify that annotation rather than generating a new, conflicting
29718 one.
29720 Mode annotations have three parts, separated by colons.  (Spaces
29721 after the colons are optional.)  The first identifies the kind
29722 of mode setting, the second is a name for the mode itself, and
29723 the third is the value in the form of a Lisp symbol, number,
29724 or list.  Annotations with unrecognizable text in the first or
29725 second parts are ignored.  The third part is not checked to make
29726 sure the value is of a legal type or range; if you write an
29727 annotation by hand, be sure to give a proper value or results
29728 will be unpredictable.  Mode-setting annotations are case-sensitive.
29730 While Embedded Mode is enabled, the word @code{Local} appears in
29731 the mode line.  This is to show that mode setting commands generate
29732 annotations that are ``local'' to the current formula or set of
29733 formulas.  The @kbd{m R} (@code{calc-mode-record-mode}) command
29734 causes Calc to generate different kinds of annotations.  Pressing
29735 @kbd{m R} repeatedly cycles through the possible modes.
29737 @code{LocEdit} and @code{LocPerm} modes generate annotations
29738 that look like this, respectively:
29740 @example
29741 % [calc-edit-mode: float-format: (sci 0)]
29742 % [calc-perm-mode: float-format: (sci 5)]
29743 @end example
29745 The first kind of annotation will be used only while a formula
29746 is enabled in Embedded Mode.  The second kind will be used only
29747 when the formula is @emph{not} enabled.  (Whether the formula
29748 is ``active'' or not, i.e., whether Calc has seen this formula
29749 yet, is not relevant here.)
29751 @code{Global} mode generates an annotation like this at the end
29752 of the file:
29754 @example
29755 % [calc-global-mode: fractions t]
29756 @end example
29758 Global mode annotations affect all formulas throughout the file,
29759 and may appear anywhere in the file.  This allows you to tuck your
29760 mode annotations somewhere out of the way, say, on a new page of
29761 the file, as long as those mode settings are suitable for all
29762 formulas in the file.
29764 Enabling a formula with @kbd{M-# e} causes a fresh scan for local
29765 mode annotations; you will have to use this after adding annotations
29766 above a formula by hand to get the formula to notice them.  Updating
29767 a formula with @kbd{M-# u} will also re-scan the local modes, but
29768 global modes are only re-scanned by @kbd{M-# a}.
29770 Another way that modes can get out of date is if you add a local
29771 mode annotation to a formula that has another formula after it.
29772 In this example, we have used the @kbd{d s} command while the
29773 first of the two embedded formulas is active.  But the second
29774 formula has not changed its style to match, even though by the
29775 rules of reading annotations the @samp{(sci 0)} applies to it, too.
29777 @example
29778 % [calc-mode: float-format: (sci 0)]
29779 1.23e2
29781 456.
29782 @end example
29784 We would have to go down to the other formula and press @kbd{M-# u}
29785 on it in order to get it to notice the new annotation.
29787 Two more mode-recording modes selectable by @kbd{m R} are @code{Save}
29788 (which works even outside of Embedded Mode), in which mode settings
29789 are recorded permanently in your Emacs startup file @file{~/.emacs}
29790 rather than by annotating the current document, and no-recording
29791 mode (where there is no symbol like @code{Save} or @code{Local} in
29792 the mode line), in which mode-changing commands do not leave any
29793 annotations at all.
29795 When Embedded Mode is not enabled, mode-recording modes except
29796 for @code{Save} have no effect.
29798 @node Customizing Embedded Mode, , Mode Settings in Embedded Mode, Embedded Mode
29799 @section Customizing Embedded Mode
29801 @noindent
29802 You can modify Embedded Mode's behavior by setting various Lisp
29803 variables described here.  Use @kbd{M-x set-variable} or
29804 @kbd{M-x edit-options} to adjust a variable on the fly, or
29805 put a suitable @code{setq} statement in your @file{~/.emacs}
29806 file to set a variable permanently.  (Another possibility would
29807 be to use a file-local variable annotation at the end of the
29808 file; @pxref{File Variables, , Local Variables in Files, emacs, the
29809 Emacs manual}.)
29811 While none of these variables will be buffer-local by default, you
29812 can make any of them local to any embedded-mode buffer.  (Their
29813 values in the @samp{*Calculator*} buffer are never used.)
29815 @vindex calc-embedded-open-formula
29816 The @code{calc-embedded-open-formula} variable holds a regular
29817 expression for the opening delimiter of a formula.  @xref{Regexp Search,
29818 , Regular Expression Search, emacs, the Emacs manual}, to see
29819 how regular expressions work.  Basically, a regular expression is a
29820 pattern that Calc can search for.  A regular expression that considers
29821 blank lines, @samp{$}, and @samp{$$} to be opening delimiters is
29822 @code{"\\`\\|^\n\\|\\$\\$?"}.  Just in case the meaning of this
29823 regular expression is not completely plain, let's go through it
29824 in detail.
29826 The surrounding @samp{" "} marks quote the text between them as a
29827 Lisp string.  If you left them off, @code{set-variable} or
29828 @code{edit-options} would try to read the regular expression as a
29829 Lisp program.
29831 The most obvious property of this regular expression is that it
29832 contains indecently many backslashes.  There are actually two levels
29833 of backslash usage going on here.  First, when Lisp reads a quoted
29834 string, all pairs of characters beginning with a backslash are
29835 interpreted as special characters.  Here, @code{\n} changes to a
29836 new-line character, and @code{\\} changes to a single backslash.
29837 So the actual regular expression seen by Calc is
29838 @samp{\`\|^ @r{(newline)} \|\$\$?}.
29840 Regular expressions also consider pairs beginning with backslash
29841 to have special meanings.  Sometimes the backslash is used to quote
29842 a character that otherwise would have a special meaning in a regular
29843 expression, like @samp{$}, which normally means ``end-of-line,''
29844 or @samp{?}, which means that the preceding item is optional.  So
29845 @samp{\$\$?} matches either one or two dollar signs.
29847 The other codes in this regular expression are @samp{^}, which matches
29848 ``beginning-of-line,'' @samp{\|}, which means ``or,'' and @samp{\`},
29849 which matches ``beginning-of-buffer.''  So the whole pattern means
29850 that a formula begins at the beginning of the buffer, or on a newline
29851 that occurs at the beginning of a line (i.e., a blank line), or at
29852 one or two dollar signs.
29854 The default value of @code{calc-embedded-open-formula} looks just
29855 like this example, with several more alternatives added on to
29856 recognize various other common kinds of delimiters.
29858 By the way, the reason to use @samp{^\n} rather than @samp{^$}
29859 or @samp{\n\n}, which also would appear to match blank lines,
29860 is that the former expression actually ``consumes'' only one
29861 newline character as @emph{part of} the delimiter, whereas the
29862 latter expressions consume zero or two newlines, respectively.
29863 The former choice gives the most natural behavior when Calc
29864 must operate on a whole formula including its delimiters.
29866 See the Emacs manual for complete details on regular expressions.
29867 But just for your convenience, here is a list of all characters
29868 which must be quoted with backslash (like @samp{\$}) to avoid
29869 some special interpretation:  @samp{. * + ? [ ] ^ $ \}.  (Note
29870 the backslash in this list; for example, to match @samp{\[} you
29871 must use @code{"\\\\\\["}.  An exercise for the reader is to
29872 account for each of these six backslashes!)
29874 @vindex calc-embedded-close-formula
29875 The @code{calc-embedded-close-formula} variable holds a regular
29876 expression for the closing delimiter of a formula.  A closing
29877 regular expression to match the above example would be
29878 @code{"\\'\\|\n$\\|\\$\\$?"}.  This is almost the same as the
29879 other one, except it now uses @samp{\'} (``end-of-buffer'') and
29880 @samp{\n$} (newline occurring at end of line, yet another way
29881 of describing a blank line that is more appropriate for this
29882 case).
29884 @vindex calc-embedded-open-word
29885 @vindex calc-embedded-close-word
29886 The @code{calc-embedded-open-word} and @code{calc-embedded-close-word}
29887 variables are similar expressions used when you type @kbd{M-# w}
29888 instead of @kbd{M-# e} to enable Embedded mode.
29890 @vindex calc-embedded-open-plain
29891 The @code{calc-embedded-open-plain} variable is a string which
29892 begins a ``plain'' formula written in front of the formatted
29893 formula when @kbd{d p} mode is turned on.  Note that this is an
29894 actual string, not a regular expression, because Calc must be able
29895 to write this string into a buffer as well as to recognize it.
29896 The default string is @code{"%%% "} (note the trailing space).
29898 @vindex calc-embedded-close-plain
29899 The @code{calc-embedded-close-plain} variable is a string which
29900 ends a ``plain'' formula.  The default is @code{" %%%\n"}.  Without
29901 the trailing newline here, the first line of a ``big'' mode formula
29902 that followed might be shifted over with respect to the other lines.
29904 @vindex calc-embedded-open-new-formula
29905 The @code{calc-embedded-open-new-formula} variable is a string
29906 which is inserted at the front of a new formula when you type
29907 @kbd{M-# f}.  Its default value is @code{"\n\n"}.  If this
29908 string begins with a newline character and the @kbd{M-# f} is
29909 typed at the beginning of a line, @kbd{M-# f} will skip this
29910 first newline to avoid introducing unnecessary blank lines in
29911 the file.
29913 @vindex calc-embedded-close-new-formula
29914 The @code{calc-embedded-close-new-formula} variable is the corresponding
29915 string which is inserted at the end of a new formula.  Its default
29916 value is also @code{"\n\n"}.  The final newline is omitted by
29917 @w{@kbd{M-# f}} if typed at the end of a line.  (It follows that if
29918 @kbd{M-# f} is typed on a blank line, both a leading opening
29919 newline and a trailing closing newline are omitted.)
29921 @vindex calc-embedded-announce-formula
29922 The @code{calc-embedded-announce-formula} variable is a regular
29923 expression which is sure to be followed by an embedded formula.
29924 The @kbd{M-# a} command searches for this pattern as well as for
29925 @samp{=>} and @samp{:=} operators.  Note that @kbd{M-# a} will
29926 not activate just anything surrounded by formula delimiters; after
29927 all, blank lines are considered formula delimiters by default!
29928 But if your language includes a delimiter which can only occur
29929 actually in front of a formula, you can take advantage of it here.
29930 The default pattern is @code{"%Embed\n\\(% .*\n\\)*"}, which
29931 checks for @samp{%Embed} followed by any number of lines beginning
29932 with @samp{%} and a space.  This last is important to make Calc
29933 consider mode annotations part of the pattern, so that the formula's
29934 opening delimiter really is sure to follow the pattern.
29936 @vindex calc-embedded-open-mode
29937 The @code{calc-embedded-open-mode} variable is a string (not a
29938 regular expression) which should precede a mode annotation.
29939 Calc never scans for this string; Calc always looks for the
29940 annotation itself.  But this is the string that is inserted before
29941 the opening bracket when Calc adds an annotation on its own.
29942 The default is @code{"% "}.
29944 @vindex calc-embedded-close-mode
29945 The @code{calc-embedded-close-mode} variable is a string which
29946 follows a mode annotation written by Calc.  Its default value
29947 is simply a newline, @code{"\n"}.  If you change this, it is a
29948 good idea still to end with a newline so that mode annotations
29949 will appear on lines by themselves.
29951 @node Programming, Installation, Embedded Mode, Top
29952 @chapter Programming
29954 @noindent
29955 There are several ways to ``program'' the Emacs Calculator, depending
29956 on the nature of the problem you need to solve.
29958 @enumerate
29959 @item
29960 @dfn{Keyboard macros} allow you to record a sequence of keystrokes
29961 and play them back at a later time.  This is just the standard Emacs
29962 keyboard macro mechanism, dressed up with a few more features such
29963 as loops and conditionals.
29965 @item
29966 @dfn{Algebraic definitions} allow you to use any formula to define a
29967 new function.  This function can then be used in algebraic formulas or
29968 as an interactive command.
29970 @item
29971 @dfn{Rewrite rules} are discussed in the section on algebra commands.
29972 @xref{Rewrite Rules}.  If you put your rewrite rules in the variable
29973 @code{EvalRules}, they will be applied automatically to all Calc
29974 results in just the same way as an internal ``rule'' is applied to
29975 evaluate @samp{sqrt(9)} to 3 and so on.  @xref{Automatic Rewrites}.
29977 @item
29978 @dfn{Lisp} is the programming language that Calc (and most of Emacs)
29979 is written in.  If the above techniques aren't powerful enough, you
29980 can write Lisp functions to do anything that built-in Calc commands
29981 can do.  Lisp code is also somewhat faster than keyboard macros or
29982 rewrite rules.
29983 @end enumerate
29985 @kindex z
29986 Programming features are available through the @kbd{z} and @kbd{Z}
29987 prefix keys.  New commands that you define are two-key sequences
29988 beginning with @kbd{z}.  Commands for managing these definitions
29989 use the shift-@kbd{Z} prefix.  (The @kbd{Z T} (@code{calc-timing})
29990 command is described elsewhere; @pxref{Troubleshooting Commands}.
29991 The @kbd{Z C} (@code{calc-user-define-composition}) command is also
29992 described elsewhere; @pxref{User-Defined Compositions}.)
29994 @menu
29995 * Creating User Keys::
29996 * Keyboard Macros::
29997 * Invocation Macros::
29998 * Algebraic Definitions::
29999 * Lisp Definitions::
30000 @end menu
30002 @node Creating User Keys, Keyboard Macros, Programming, Programming
30003 @section Creating User Keys
30005 @noindent
30006 @kindex Z D
30007 @pindex calc-user-define
30008 Any Calculator command may be bound to a key using the @kbd{Z D}
30009 (@code{calc-user-define}) command.  Actually, it is bound to a two-key
30010 sequence beginning with the lower-case @kbd{z} prefix.
30012 The @kbd{Z D} command first prompts for the key to define.  For example,
30013 press @kbd{Z D a} to define the new key sequence @kbd{z a}.  You are then
30014 prompted for the name of the Calculator command that this key should
30015 run.  For example, the @code{calc-sincos} command is not normally
30016 available on a key.  Typing @kbd{Z D s sincos @key{RET}} programs the
30017 @kbd{z s} key sequence to run @code{calc-sincos}.  This definition will remain
30018 in effect for the rest of this Emacs session, or until you redefine
30019 @kbd{z s} to be something else.
30021 You can actually bind any Emacs command to a @kbd{z} key sequence by
30022 backspacing over the @samp{calc-} when you are prompted for the command name.
30024 As with any other prefix key, you can type @kbd{z ?} to see a list of
30025 all the two-key sequences you have defined that start with @kbd{z}.
30026 Initially, no @kbd{z} sequences (except @kbd{z ?} itself) are defined.
30028 User keys are typically letters, but may in fact be any key.
30029 (@key{META}-keys are not permitted, nor are a terminal's special
30030 function keys which generate multi-character sequences when pressed.)
30031 You can define different commands on the shifted and unshifted versions
30032 of a letter if you wish.
30034 @kindex Z U
30035 @pindex calc-user-undefine
30036 The @kbd{Z U} (@code{calc-user-undefine}) command unbinds a user key.
30037 For example, the key sequence @kbd{Z U s} will undefine the @code{sincos}
30038 key we defined above.
30040 @kindex Z P
30041 @pindex calc-user-define-permanent
30042 @cindex Storing user definitions
30043 @cindex Permanent user definitions
30044 @cindex @file{.emacs} file, user-defined commands
30045 The @kbd{Z P} (@code{calc-user-define-permanent}) command makes a key
30046 binding permanent so that it will remain in effect even in future Emacs
30047 sessions.  (It does this by adding a suitable bit of Lisp code into
30048 your @file{.emacs} file.)  For example, @kbd{Z P s} would register
30049 our @code{sincos} command permanently.  If you later wish to unregister
30050 this command you must edit your @file{.emacs} file by hand.
30051 (@xref{General Mode Commands}, for a way to tell Calc to use a
30052 different file instead of @file{.emacs}.)
30054 The @kbd{Z P} command also saves the user definition, if any, for the
30055 command bound to the key.  After @kbd{Z F} and @kbd{Z C}, a given user
30056 key could invoke a command, which in turn calls an algebraic function,
30057 which might have one or more special display formats.  A single @kbd{Z P}
30058 command will save all of these definitions.
30060 To save a command or function without its key binding (or if there is
30061 no key binding for the command or function), type @kbd{'} (the apostrophe)
30062 when prompted for a key.  Then, type the function name, or backspace
30063 to change the @samp{calcFunc-} prefix to @samp{calc-} and enter a
30064 command name.  (If the command you give implies a function, the function
30065 will be saved, and if the function has any display formats, those will
30066 be saved, but not the other way around:  Saving a function will not save
30067 any commands or key bindings associated with the function.)
30069 @kindex Z E
30070 @pindex calc-user-define-edit
30071 @cindex Editing user definitions
30072 The @kbd{Z E} (@code{calc-user-define-edit}) command edits the definition
30073 of a user key.  This works for keys that have been defined by either
30074 keyboard macros or formulas; further details are contained in the relevant
30075 following sections.
30077 @node Keyboard Macros, Invocation Macros, Creating User Keys, Programming
30078 @section Programming with Keyboard Macros
30080 @noindent
30081 @kindex X
30082 @cindex Programming with keyboard macros
30083 @cindex Keyboard macros
30084 The easiest way to ``program'' the Emacs Calculator is to use standard
30085 keyboard macros.  Press @w{@kbd{C-x (}} to begin recording a macro.  From
30086 this point on, keystrokes you type will be saved away as well as
30087 performing their usual functions.  Press @kbd{C-x )} to end recording.
30088 Press shift-@kbd{X} (or the standard Emacs key sequence @kbd{C-x e}) to
30089 execute your keyboard macro by replaying the recorded keystrokes.
30090 @xref{Keyboard Macros, , , emacs, the Emacs Manual}, for further
30091 information.@refill
30093 When you use @kbd{X} to invoke a keyboard macro, the entire macro is
30094 treated as a single command by the undo and trail features.  The stack
30095 display buffer is not updated during macro execution, but is instead
30096 fixed up once the macro completes.  Thus, commands defined with keyboard
30097 macros are convenient and efficient.  The @kbd{C-x e} command, on the
30098 other hand, invokes the keyboard macro with no special treatment: Each
30099 command in the macro will record its own undo information and trail entry,
30100 and update the stack buffer accordingly.  If your macro uses features
30101 outside of Calc's control to operate on the contents of the Calc stack
30102 buffer, or if it includes Undo, Redo, or last-arguments commands, you
30103 must use @kbd{C-x e} to make sure the buffer and undo list are up-to-date
30104 at all times.  You could also consider using @kbd{K} (@code{calc-keep-args})
30105 instead of @kbd{M-@key{RET}} (@code{calc-last-args}).
30107 Calc extends the standard Emacs keyboard macros in several ways.
30108 Keyboard macros can be used to create user-defined commands.  Keyboard
30109 macros can include conditional and iteration structures, somewhat
30110 analogous to those provided by a traditional programmable calculator.
30112 @menu
30113 * Naming Keyboard Macros::
30114 * Conditionals in Macros::
30115 * Loops in Macros::
30116 * Local Values in Macros::
30117 * Queries in Macros::
30118 @end menu
30120 @node Naming Keyboard Macros, Conditionals in Macros, Keyboard Macros, Keyboard Macros
30121 @subsection Naming Keyboard Macros
30123 @noindent
30124 @kindex Z K
30125 @pindex calc-user-define-kbd-macro
30126 Once you have defined a keyboard macro, you can bind it to a @kbd{z}
30127 key sequence with the @kbd{Z K} (@code{calc-user-define-kbd-macro}) command.
30128 This command prompts first for a key, then for a command name.  For
30129 example, if you type @kbd{C-x ( n @key{TAB} n @key{TAB} C-x )} you will
30130 define a keyboard macro which negates the top two numbers on the stack
30131 (@key{TAB} swaps the top two stack elements).  Now you can type
30132 @kbd{Z K n @key{RET}} to define this keyboard macro onto the @kbd{z n} key
30133 sequence.  The default command name (if you answer the second prompt with
30134 just the @key{RET} key as in this example) will be something like
30135 @samp{calc-User-n}.  The keyboard macro will now be available as both
30136 @kbd{z n} and @kbd{M-x calc-User-n}.  You can backspace and enter a more
30137 descriptive command name if you wish.@refill
30139 Macros defined by @kbd{Z K} act like single commands; they are executed
30140 in the same way as by the @kbd{X} key.  If you wish to define the macro
30141 as a standard no-frills Emacs macro (to be executed as if by @kbd{C-x e}),
30142 give a negative prefix argument to @kbd{Z K}.
30144 Once you have bound your keyboard macro to a key, you can use
30145 @kbd{Z P} to register it permanently with Emacs.  @xref{Creating User Keys}.
30147 @cindex Keyboard macros, editing
30148 The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
30149 been defined by a keyboard macro tries to use the @code{edit-kbd-macro}
30150 command to edit the macro.  This command may be found in the
30151 @file{macedit} package, a copy of which comes with Calc.  It decomposes
30152 the macro definition into full Emacs command names, like @code{calc-pop}
30153 and @code{calc-add}.  Type @kbd{M-# M-#} to finish editing and update
30154 the definition stored on the key, or, to cancel the edit, type
30155 @kbd{M-# x}.@refill
30157 If you give a negative numeric prefix argument to @kbd{Z E}, the keyboard
30158 macro is edited in spelled-out keystroke form.  For example, the editing
30159 buffer might contain the nine characters @w{@samp{1 RET 2 +}}.  When you press
30160 @kbd{M-# M-#}, the @code{read-kbd-macro} feature of the @file{macedit}
30161 package is used to reinterpret these key names.  The
30162 notations @code{RET}, @code{LFD}, @code{TAB}, @code{SPC}, @code{DEL}, and
30163 @code{NUL} must be written in all uppercase, as must the prefixes @code{C-}
30164 and @code{M-}.  Spaces and line breaks are ignored.  Other characters are
30165 copied verbatim into the keyboard macro.  Basically, the notation is the
30166 same as is used in all of this manual's examples, except that the manual
30167 takes some liberties with spaces:  When we say @kbd{' [1 2 3] RET}, we take
30168 it for granted that it is clear we really mean @kbd{' [1 SPC 2 SPC 3] RET},
30169 which is what @code{read-kbd-macro} wants to see.@refill
30171 If @file{macedit} is not available, @kbd{Z E} edits the keyboard macro
30172 in ``raw'' form; the editing buffer simply contains characters like
30173 @samp{1^M2+} (here @samp{^M} represents the carriage-return character).
30174 Editing in this mode, you will have to use @kbd{C-q} to enter new
30175 control characters into the buffer.@refill
30177 @kindex M-# m
30178 @pindex read-kbd-macro
30179 The @kbd{M-# m} (@code{read-kbd-macro}) command reads an Emacs ``region''
30180 of spelled-out keystrokes and defines it as the current keyboard macro.
30181 It is a convenient way to define a keyboard macro that has been stored
30182 in a file, or to define a macro without executing it at the same time.
30183 The @kbd{M-# m} command works only if @file{macedit} is present.
30185 @node Conditionals in Macros, Loops in Macros, Naming Keyboard Macros, Keyboard Macros
30186 @subsection Conditionals in Keyboard Macros
30188 @noindent
30189 @kindex Z [
30190 @kindex Z ]
30191 @pindex calc-kbd-if
30192 @pindex calc-kbd-else
30193 @pindex calc-kbd-else-if
30194 @pindex calc-kbd-end-if
30195 @cindex Conditional structures
30196 The @kbd{Z [} (@code{calc-kbd-if}) and @kbd{Z ]} (@code{calc-kbd-end-if})
30197 commands allow you to put simple tests in a keyboard macro.  When Calc
30198 sees the @kbd{Z [}, it pops an object from the stack and, if the object is
30199 a non-zero value, continues executing keystrokes.  But if the object is
30200 zero, or if it is not provably nonzero, Calc skips ahead to the matching
30201 @kbd{Z ]} keystroke.  @xref{Logical Operations}, for a set of commands for
30202 performing tests which conveniently produce 1 for true and 0 for false.
30204 For example, @kbd{@key{RET} 0 a < Z [ n Z ]} implements an absolute-value
30205 function in the form of a keyboard macro.  This macro duplicates the
30206 number on the top of the stack, pushes zero and compares using @kbd{a <}
30207 (@code{calc-less-than}), then, if the number was less than zero,
30208 executes @kbd{n} (@code{calc-change-sign}).  Otherwise, the change-sign
30209 command is skipped.
30211 To program this macro, type @kbd{C-x (}, type the above sequence of
30212 keystrokes, then type @kbd{C-x )}.  Note that the keystrokes will be
30213 executed while you are making the definition as well as when you later
30214 re-execute the macro by typing @kbd{X}.  Thus you should make sure a
30215 suitable number is on the stack before defining the macro so that you
30216 don't get a stack-underflow error during the definition process.
30218 Conditionals can be nested arbitrarily.  However, there should be exactly
30219 one @kbd{Z ]} for each @kbd{Z [} in a keyboard macro.
30221 @kindex Z :
30222 The @kbd{Z :} (@code{calc-kbd-else}) command allows you to choose between
30223 two keystroke sequences.  The general format is @kbd{@var{cond} Z [
30224 @var{then-part} Z : @var{else-part} Z ]}.  If @var{cond} is true
30225 (i.e., if the top of stack contains a non-zero number after @var{cond}
30226 has been executed), the @var{then-part} will be executed and the
30227 @var{else-part} will be skipped.  Otherwise, the @var{then-part} will
30228 be skipped and the @var{else-part} will be executed.
30230 @kindex Z |
30231 The @kbd{Z |} (@code{calc-kbd-else-if}) command allows you to choose
30232 between any number of alternatives.  For example,
30233 @kbd{@var{cond1} Z [ @var{part1} Z : @var{cond2} Z | @var{part2} Z :
30234 @var{part3} Z ]} will execute @var{part1} if @var{cond1} is true,
30235 otherwise it will execute @var{part2} if @var{cond2} is true, otherwise
30236 it will execute @var{part3}.
30238 More precisely, @kbd{Z [} pops a number and conditionally skips to the
30239 next matching @kbd{Z :} or @kbd{Z ]} key.  @w{@kbd{Z ]}} has no effect when
30240 actually executed.  @kbd{Z :} skips to the next matching @kbd{Z ]}.
30241 @kbd{Z |} pops a number and conditionally skips to the next matching
30242 @kbd{Z :} or @kbd{Z ]}; thus, @kbd{Z [} and @kbd{Z |} are functionally
30243 equivalent except that @kbd{Z [} participates in nesting but @kbd{Z |}
30244 does not.
30246 Calc's conditional and looping constructs work by scanning the
30247 keyboard macro for occurrences of character sequences like @samp{Z:}
30248 and @samp{Z]}.  One side-effect of this is that if you use these
30249 constructs you must be careful that these character pairs do not
30250 occur by accident in other parts of the macros.  Since Calc rarely
30251 uses shift-@kbd{Z} for any purpose except as a prefix character, this
30252 is not likely to be a problem.  Another side-effect is that it will
30253 not work to define your own custom key bindings for these commands.
30254 Only the standard shift-@kbd{Z} bindings will work correctly.
30256 @kindex Z C-g
30257 If Calc gets stuck while skipping characters during the definition of a
30258 macro, type @kbd{Z C-g} to cancel the definition.  (Typing plain @kbd{C-g}
30259 actually adds a @kbd{C-g} keystroke to the macro.)
30261 @node Loops in Macros, Local Values in Macros, Conditionals in Macros, Keyboard Macros
30262 @subsection Loops in Keyboard Macros
30264 @noindent
30265 @kindex Z <
30266 @kindex Z >
30267 @pindex calc-kbd-repeat
30268 @pindex calc-kbd-end-repeat
30269 @cindex Looping structures
30270 @cindex Iterative structures
30271 The @kbd{Z <} (@code{calc-kbd-repeat}) and @kbd{Z >}
30272 (@code{calc-kbd-end-repeat}) commands pop a number from the stack,
30273 which must be an integer, then repeat the keystrokes between the brackets
30274 the specified number of times.  If the integer is zero or negative, the
30275 body is skipped altogether.  For example, @kbd{1 @key{TAB} Z < 2 * Z >}
30276 computes two to a nonnegative integer power.  First, we push 1 on the
30277 stack and then swap the integer argument back to the top.  The @kbd{Z <}
30278 pops that argument leaving the 1 back on top of the stack.  Then, we
30279 repeat a multiply-by-two step however many times.@refill
30281 Once again, the keyboard macro is executed as it is being entered.
30282 In this case it is especially important to set up reasonable initial
30283 conditions before making the definition:  Suppose the integer 1000 just
30284 happened to be sitting on the stack before we typed the above definition!
30285 Another approach is to enter a harmless dummy definition for the macro,
30286 then go back and edit in the real one with a @kbd{Z E} command.  Yet
30287 another approach is to type the macro as written-out keystroke names
30288 in a buffer, then use @kbd{M-# m} (@code{read-kbd-macro}) to read the
30289 macro.
30291 @kindex Z /
30292 @pindex calc-break
30293 The @kbd{Z /} (@code{calc-kbd-break}) command allows you to break out
30294 of a keyboard macro loop prematurely.  It pops an object from the stack;
30295 if that object is true (a non-zero number), control jumps out of the
30296 innermost enclosing @kbd{Z <} @dots{} @kbd{Z >} loop and continues
30297 after the @kbd{Z >}.  If the object is false, the @kbd{Z /} has no
30298 effect.  Thus @kbd{@var{cond} Z /} is similar to @samp{if (@var{cond}) break;}
30299 in the C language.@refill
30301 @kindex Z (
30302 @kindex Z )
30303 @pindex calc-kbd-for
30304 @pindex calc-kbd-end-for
30305 The @kbd{Z (} (@code{calc-kbd-for}) and @kbd{Z )} (@code{calc-kbd-end-for})
30306 commands are similar to @kbd{Z <} and @kbd{Z >}, except that they make the
30307 value of the counter available inside the loop.  The general layout is
30308 @kbd{@var{init} @var{final} Z ( @var{body} @var{step} Z )}.  The @kbd{Z (}
30309 command pops initial and final values from the stack.  It then creates
30310 a temporary internal counter and initializes it with the value @var{init}.
30311 The @kbd{Z (} command then repeatedly pushes the counter value onto the
30312 stack and executes @var{body} and @var{step}, adding @var{step} to the
30313 counter each time until the loop finishes.@refill
30315 @cindex Summations (by keyboard macros)
30316 By default, the loop finishes when the counter becomes greater than (or
30317 less than) @var{final}, assuming @var{initial} is less than (greater
30318 than) @var{final}.  If @var{initial} is equal to @var{final}, the body
30319 executes exactly once.  The body of the loop always executes at least
30320 once.  For example, @kbd{0 1 10 Z ( 2 ^ + 1 Z )} computes the sum of the
30321 squares of the integers from 1 to 10, in steps of 1.
30323 If you give a numeric prefix argument of 1 to @kbd{Z (}, the loop is
30324 forced to use upward-counting conventions.  In this case, if @var{initial}
30325 is greater than @var{final} the body will not be executed at all.
30326 Note that @var{step} may still be negative in this loop; the prefix
30327 argument merely constrains the loop-finished test.  Likewise, a prefix
30328 argument of @i{-1} forces downward-counting conventions.
30330 @kindex Z @{
30331 @kindex Z @}
30332 @pindex calc-kbd-loop
30333 @pindex calc-kbd-end-loop
30334 The @kbd{Z @{} (@code{calc-kbd-loop}) and @kbd{Z @}}
30335 (@code{calc-kbd-end-loop}) commands are similar to @kbd{Z <} and
30336 @kbd{Z >}, except that they do not pop a count from the stack---they
30337 effectively create an infinite loop.  Every @kbd{Z @{} @dots{} @kbd{Z @}}
30338 loop ought to include at least one @kbd{Z /} to make sure the loop
30339 doesn't run forever.  (If any error message occurs which causes Emacs
30340 to beep, the keyboard macro will also be halted; this is a standard
30341 feature of Emacs.  You can also generally press @kbd{C-g} to halt a
30342 running keyboard macro, although not all versions of Unix support
30343 this feature.)
30345 The conditional and looping constructs are not actually tied to
30346 keyboard macros, but they are most often used in that context.
30347 For example, the keystrokes @kbd{10 Z < 23 @key{RET} Z >} push
30348 ten copies of 23 onto the stack.  This can be typed ``live'' just
30349 as easily as in a macro definition.
30351 @xref{Conditionals in Macros}, for some additional notes about
30352 conditional and looping commands.
30354 @node Local Values in Macros, Queries in Macros, Loops in Macros, Keyboard Macros
30355 @subsection Local Values in Macros
30357 @noindent
30358 @cindex Local variables
30359 @cindex Restoring saved modes
30360 Keyboard macros sometimes want to operate under known conditions
30361 without affecting surrounding conditions.  For example, a keyboard
30362 macro may wish to turn on Fraction Mode, or set a particular
30363 precision, independent of the user's normal setting for those
30364 modes.
30366 @kindex Z `
30367 @kindex Z '
30368 @pindex calc-kbd-push
30369 @pindex calc-kbd-pop
30370 Macros also sometimes need to use local variables.  Assignments to
30371 local variables inside the macro should not affect any variables
30372 outside the macro.  The @kbd{Z `} (@code{calc-kbd-push}) and @kbd{Z '}
30373 (@code{calc-kbd-pop}) commands give you both of these capabilities.
30375 When you type @kbd{Z `} (with a backquote or accent grave character),
30376 the values of various mode settings are saved away.  The ten ``quick''
30377 variables @code{q0} through @code{q9} are also saved.  When
30378 you type @w{@kbd{Z '}} (with an apostrophe), these values are restored.
30379 Pairs of @kbd{Z `} and @kbd{Z '} commands may be nested.
30381 If a keyboard macro halts due to an error in between a @kbd{Z `} and
30382 a @kbd{Z '}, the saved values will be restored correctly even though
30383 the macro never reaches the @kbd{Z '} command.  Thus you can use
30384 @kbd{Z `} and @kbd{Z '} without having to worry about what happens
30385 in exceptional conditions.
30387 If you type @kbd{Z `} ``live'' (not in a keyboard macro), Calc puts
30388 you into a ``recursive edit.''  You can tell you are in a recursive
30389 edit because there will be extra square brackets in the mode line,
30390 as in @samp{[(Calculator)]}.  These brackets will go away when you
30391 type the matching @kbd{Z '} command.  The modes and quick variables
30392 will be saved and restored in just the same way as if actual keyboard
30393 macros were involved.
30395 The modes saved by @kbd{Z `} and @kbd{Z '} are the current precision
30396 and binary word size, the angular mode (Deg, Rad, or HMS), the
30397 simplification mode, Algebraic mode, Symbolic mode, Infinite mode,
30398 Matrix or Scalar mode, Fraction mode, and the current complex mode
30399 (Polar or Rectangular).  The ten ``quick'' variables' values (or lack
30400 thereof) are also saved.
30402 Most mode-setting commands act as toggles, but with a numeric prefix
30403 they force the mode either on (positive prefix) or off (negative
30404 or zero prefix).  Since you don't know what the environment might
30405 be when you invoke your macro, it's best to use prefix arguments
30406 for all mode-setting commands inside the macro.
30408 In fact, @kbd{C-u Z `} is like @kbd{Z `} except that it sets the modes
30409 listed above to their default values.  As usual, the matching @kbd{Z '}
30410 will restore the modes to their settings from before the @kbd{C-u Z `}.
30411 Also, @w{@kbd{Z `}} with a negative prefix argument resets algebraic mode
30412 to its default (off) but leaves the other modes the same as they were
30413 outside the construct.
30415 The contents of the stack and trail, values of non-quick variables, and
30416 other settings such as the language mode and the various display modes,
30417 are @emph{not} affected by @kbd{Z `} and @kbd{Z '}.
30419 @node Queries in Macros, , Local Values in Macros, Keyboard Macros
30420 @subsection Queries in Keyboard Macros
30422 @noindent
30423 @kindex Z =
30424 @pindex calc-kbd-report
30425 The @kbd{Z =} (@code{calc-kbd-report}) command displays an informative
30426 message including the value on the top of the stack.  You are prompted
30427 to enter a string.  That string, along with the top-of-stack value,
30428 is displayed unless @kbd{m w} (@code{calc-working}) has been used
30429 to turn such messages off.
30431 @kindex Z #
30432 @pindex calc-kbd-query
30433 The @kbd{Z #} (@code{calc-kbd-query}) command displays a prompt message
30434 (which you enter during macro definition), then does an algebraic entry
30435 which takes its input from the keyboard, even during macro execution.
30436 This command allows your keyboard macros to accept numbers or formulas
30437 as interactive input.  All the normal conventions of algebraic input,
30438 including the use of @kbd{$} characters, are supported.
30440 @xref{Kbd Macro Query, , , emacs, the Emacs Manual}, for a description of
30441 @kbd{C-x q} (@code{kbd-macro-query}), the standard Emacs way to accept
30442 keyboard input during a keyboard macro.  In particular, you can use
30443 @kbd{C-x q} to enter a recursive edit, which allows the user to perform
30444 any Calculator operations interactively before pressing @kbd{C-M-c} to
30445 return control to the keyboard macro.
30447 @node Invocation Macros, Algebraic Definitions, Keyboard Macros, Programming
30448 @section Invocation Macros
30450 @kindex M-# z
30451 @kindex Z I
30452 @pindex calc-user-invocation
30453 @pindex calc-user-define-invocation
30454 Calc provides one special keyboard macro, called up by @kbd{M-# z}
30455 (@code{calc-user-invocation}), that is intended to allow you to define
30456 your own special way of starting Calc.  To define this ``invocation
30457 macro,'' create the macro in the usual way with @kbd{C-x (} and
30458 @kbd{C-x )}, then type @kbd{Z I} (@code{calc-user-define-invocation}).
30459 There is only one invocation macro, so you don't need to type any
30460 additional letters after @kbd{Z I}.  From now on, you can type
30461 @kbd{M-# z} at any time to execute your invocation macro.
30463 For example, suppose you find yourself often grabbing rectangles of
30464 numbers into Calc and multiplying their columns.  You can do this
30465 by typing @kbd{M-# r} to grab, and @kbd{V R : *} to multiply columns.
30466 To make this into an invocation macro, just type @kbd{C-x ( M-# r
30467 V R : * C-x )}, then @kbd{Z I}.  Then, to multiply a rectangle of data,
30468 just mark the data in its buffer in the usual way and type @kbd{M-# z}.
30470 Invocation macros are treated like regular Emacs keyboard macros;
30471 all the special features described above for @kbd{Z K}-style macros
30472 do not apply.  @kbd{M-# z} is just like @kbd{C-x e}, except that it
30473 uses the macro that was last stored by @kbd{Z I}.  (In fact, the
30474 macro does not even have to have anything to do with Calc!)
30476 The @kbd{m m} command saves the last invocation macro defined by
30477 @kbd{Z I} along with all the other Calc mode settings.
30478 @xref{General Mode Commands}.
30480 @node Algebraic Definitions, Lisp Definitions, Invocation Macros, Programming
30481 @section Programming with Formulas
30483 @noindent
30484 @kindex Z F
30485 @pindex calc-user-define-formula
30486 @cindex Programming with algebraic formulas
30487 Another way to create a new Calculator command uses algebraic formulas.
30488 The @kbd{Z F} (@code{calc-user-define-formula}) command stores the
30489 formula at the top of the stack as the definition for a key.  This
30490 command prompts for five things: The key, the command name, the function
30491 name, the argument list, and the behavior of the command when given
30492 non-numeric arguments.
30494 For example, suppose we type @kbd{' a+2b @key{RET}} to push the formula
30495 @samp{a + 2*b} onto the stack.  We now type @kbd{Z F m} to define this
30496 formula on the @kbd{z m} key sequence.  The next prompt is for a command
30497 name, beginning with @samp{calc-}, which should be the long (@kbd{M-x}) form
30498 for the new command.  If you simply press @key{RET}, a default name like
30499 @code{calc-User-m} will be constructed.  In our example, suppose we enter
30500 @kbd{spam @key{RET}} to define the new command as @code{calc-spam}.
30502 If you want to give the formula a long-style name only, you can press
30503 @key{SPC} or @key{RET} when asked which single key to use.  For example
30504 @kbd{Z F @key{RET} spam @key{RET}} defines the new command as
30505 @kbd{M-x calc-spam}, with no keyboard equivalent.
30507 The third prompt is for a function name.  The default is to use the same
30508 name as the command name but with @samp{calcFunc-} in place of
30509 @samp{calc-}.  This is the name you will use if you want to enter your
30510 new function in an algebraic formula.  Suppose we enter @kbd{yow @key{RET}}.
30511 Then the new function can be invoked by pushing two numbers on the
30512 stack and typing @kbd{z m} or @kbd{x spam}, or by entering the algebraic
30513 formula @samp{yow(x,y)}.@refill
30515 The fourth prompt is for the function's argument list.  This is used to
30516 associate values on the stack with the variables that appear in the formula.
30517 The default is a list of all variables which appear in the formula, sorted
30518 into alphabetical order.  In our case, the default would be @samp{(a b)}.
30519 This means that, when the user types @kbd{z m}, the Calculator will remove
30520 two numbers from the stack, substitute these numbers for @samp{a} and
30521 @samp{b} (respectively) in the formula, then simplify the formula and
30522 push the result on the stack.  In other words, @kbd{10 @key{RET} 100 z m}
30523 would replace the 10 and 100 on the stack with the number 210, which is
30524 @cite{a + 2 b} with @cite{a=10} and @cite{b=100}.  Likewise, the formula
30525 @samp{yow(10, 100)} will be evaluated by substituting @cite{a=10} and
30526 @cite{b=100} in the definition.
30528 You can rearrange the order of the names before pressing @key{RET} to
30529 control which stack positions go to which variables in the formula.  If
30530 you remove a variable from the argument list, that variable will be left
30531 in symbolic form by the command.  Thus using an argument list of @samp{(b)}
30532 for our function would cause @kbd{10 z m} to replace the 10 on the stack
30533 with the formula @samp{a + 20}.  If we had used an argument list of
30534 @samp{(b a)}, the result with inputs 10 and 100 would have been 120.
30536 You can also put a nameless function on the stack instead of just a
30537 formula, as in @samp{<a, b : a + 2 b>}.  @xref{Specifying Operators}.
30538 In this example, the command will be defined by the formula @samp{a + 2 b}
30539 using the argument list @samp{(a b)}.
30541 The final prompt is a y-or-n question concerning what to do if symbolic
30542 arguments are given to your function.  If you answer @kbd{y}, then
30543 executing @kbd{z m} (using the original argument list @samp{(a b)}) with
30544 arguments @cite{10} and @cite{x} will leave the function in symbolic
30545 form, i.e., @samp{yow(10,x)}.  On the other hand, if you answer @kbd{n},
30546 then the formula will always be expanded, even for non-constant
30547 arguments: @samp{10 + 2 x}.  If you never plan to feed algebraic
30548 formulas to your new function, it doesn't matter how you answer this
30549 question.@refill
30551 If you answered @kbd{y} to this question you can still cause a function
30552 call to be expanded by typing @kbd{a "} (@code{calc-expand-formula}).
30553 Also, Calc will expand the function if necessary when you take a
30554 derivative or integral or solve an equation involving the function.
30556 @kindex Z G
30557 @pindex calc-get-user-defn
30558 Once you have defined a formula on a key, you can retrieve this formula
30559 with the @kbd{Z G} (@code{calc-user-define-get-defn}) command.  Press a
30560 key, and this command pushes the formula that was used to define that
30561 key onto the stack.  Actually, it pushes a nameless function that
30562 specifies both the argument list and the defining formula.  You will get
30563 an error message if the key is undefined, or if the key was not defined
30564 by a @kbd{Z F} command.@refill
30566 The @kbd{Z E} (@code{calc-user-define-edit}) command on a key that has
30567 been defined by a formula uses a variant of the @code{calc-edit} command
30568 to edit the defining formula.  Press @kbd{M-# M-#} to finish editing and
30569 store the new formula back in the definition, or @kbd{M-# x} to
30570 cancel the edit.  (The argument list and other properties of the
30571 definition are unchanged; to adjust the argument list, you can use
30572 @kbd{Z G} to grab the function onto the stack, edit with @kbd{`}, and
30573 then re-execute the @kbd{Z F} command.)
30575 As usual, the @kbd{Z P} command records your definition permanently.
30576 In this case it will permanently record all three of the relevant
30577 definitions: the key, the command, and the function.
30579 You may find it useful to turn off the default simplifications with
30580 @kbd{m O} (@code{calc-no-simplify-mode}) when entering a formula to be
30581 used as a function definition.  For example, the formula @samp{deriv(a^2,v)}
30582 which might be used to define a new function @samp{dsqr(a,v)} will be
30583 ``simplified'' to 0 immediately upon entry since @code{deriv} considers
30584 @cite{a} to be constant with respect to @cite{v}.  Turning off
30585 default simplifications cures this problem:  The definition will be stored
30586 in symbolic form without ever activating the @code{deriv} function.  Press
30587 @kbd{m D} to turn the default simplifications back on afterwards.
30589 @node Lisp Definitions, , Algebraic Definitions, Programming
30590 @section Programming with Lisp
30592 @noindent
30593 The Calculator can be programmed quite extensively in Lisp.  All you
30594 do is write a normal Lisp function definition, but with @code{defmath}
30595 in place of @code{defun}.  This has the same form as @code{defun}, but it
30596 automagically replaces calls to standard Lisp functions like @code{+} and
30597 @code{zerop} with calls to the corresponding functions in Calc's own library.
30598 Thus you can write natural-looking Lisp code which operates on all of the
30599 standard Calculator data types.  You can then use @kbd{Z D} if you wish to
30600 bind your new command to a @kbd{z}-prefix key sequence.  The @kbd{Z E} command
30601 will not edit a Lisp-based definition.
30603 Emacs Lisp is described in the GNU Emacs Lisp Reference Manual.  This section
30604 assumes a familiarity with Lisp programming concepts; if you do not know
30605 Lisp, you may find keyboard macros or rewrite rules to be an easier way
30606 to program the Calculator.
30608 This section first discusses ways to write commands, functions, or
30609 small programs to be executed inside of Calc.  Then it discusses how
30610 your own separate programs are able to call Calc from the outside.
30611 Finally, there is a list of internal Calc functions and data structures
30612 for the true Lisp enthusiast.
30614 @menu
30615 * Defining Functions::
30616 * Defining Simple Commands::
30617 * Defining Stack Commands::
30618 * Argument Qualifiers::
30619 * Example Definitions::
30621 * Calling Calc from Your Programs::
30622 * Internals::
30623 @end menu
30625 @node Defining Functions, Defining Simple Commands, Lisp Definitions, Lisp Definitions
30626 @subsection Defining New Functions
30628 @noindent
30629 @findex defmath
30630 The @code{defmath} function (actually a Lisp macro) is like @code{defun}
30631 except that code in the body of the definition can make use of the full
30632 range of Calculator data types.  The prefix @samp{calcFunc-} is added
30633 to the specified name to get the actual Lisp function name.  As a simple
30634 example,
30636 @example
30637 (defmath myfact (n)
30638   (if (> n 0)
30639       (* n (myfact (1- n)))
30640     1))
30641 @end example
30643 @noindent
30644 This actually expands to the code,
30646 @example
30647 (defun calcFunc-myfact (n)
30648   (if (math-posp n)
30649       (math-mul n (calcFunc-myfact (math-add n -1)))
30650     1))
30651 @end example
30653 @noindent
30654 This function can be used in algebraic expressions, e.g., @samp{myfact(5)}.
30656 The @samp{myfact} function as it is defined above has the bug that an
30657 expression @samp{myfact(a+b)} will be simplified to 1 because the
30658 formula @samp{a+b} is not considered to be @code{posp}.  A robust
30659 factorial function would be written along the following lines:
30661 @smallexample
30662 (defmath myfact (n)
30663   (if (> n 0)
30664       (* n (myfact (1- n)))
30665     (if (= n 0)
30666         1
30667       nil)))    ; this could be simplified as: (and (= n 0) 1)
30668 @end smallexample
30670 If a function returns @code{nil}, it is left unsimplified by the Calculator
30671 (except that its arguments will be simplified).  Thus, @samp{myfact(a+1+2)}
30672 will be simplified to @samp{myfact(a+3)} but no further.  Beware that every
30673 time the Calculator reexamines this formula it will attempt to resimplify
30674 it, so your function ought to detect the returning-@code{nil} case as
30675 efficiently as possible.
30677 The following standard Lisp functions are treated by @code{defmath}:
30678 @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^} or
30679 @code{expt}, @code{=}, @code{<}, @code{>}, @code{<=}, @code{>=},
30680 @code{/=}, @code{1+}, @code{1-}, @code{logand}, @code{logior}, @code{logxor},
30681 @code{logandc2}, @code{lognot}.  Also, @code{~=} is an abbreviation for
30682 @code{math-nearly-equal}, which is useful in implementing Taylor series.@refill
30684 For other functions @var{func}, if a function by the name
30685 @samp{calcFunc-@var{func}} exists it is used, otherwise if a function by the
30686 name @samp{math-@var{func}} exists it is used, otherwise if @var{func} itself
30687 is defined as a function it is used, otherwise @samp{calcFunc-@var{func}} is
30688 used on the assumption that this is a to-be-defined math function.  Also, if
30689 the function name is quoted as in @samp{('integerp a)} the function name is
30690 always used exactly as written (but not quoted).@refill
30692 Variable names have @samp{var-} prepended to them unless they appear in
30693 the function's argument list or in an enclosing @code{let}, @code{let*},
30694 @code{for}, or @code{foreach} form,
30695 or their names already contain a @samp{-} character.  Thus a reference to
30696 @samp{foo} is the same as a reference to @samp{var-foo}.@refill
30698 A few other Lisp extensions are available in @code{defmath} definitions:
30700 @itemize @bullet
30701 @item
30702 The @code{elt} function accepts any number of index variables.
30703 Note that Calc vectors are stored as Lisp lists whose first
30704 element is the symbol @code{vec}; thus, @samp{(elt v 2)} yields
30705 the second element of vector @code{v}, and @samp{(elt m i j)}
30706 yields one element of a Calc matrix.
30708 @item
30709 The @code{setq} function has been extended to act like the Common
30710 Lisp @code{setf} function.  (The name @code{setf} is recognized as
30711 a synonym of @code{setq}.)  Specifically, the first argument of
30712 @code{setq} can be an @code{nth}, @code{elt}, @code{car}, or @code{cdr} form,
30713 in which case the effect is to store into the specified
30714 element of a list.  Thus, @samp{(setq (elt m i j) x)} stores @cite{x}
30715 into one element of a matrix.
30717 @item
30718 A @code{for} looping construct is available.  For example,
30719 @samp{(for ((i 0 10)) body)} executes @code{body} once for each
30720 binding of @cite{i} from zero to 10.  This is like a @code{let}
30721 form in that @cite{i} is temporarily bound to the loop count
30722 without disturbing its value outside the @code{for} construct.
30723 Nested loops, as in @samp{(for ((i 0 10) (j 0 (1- i) 2)) body)},
30724 are also available.  For each value of @cite{i} from zero to 10,
30725 @cite{j} counts from 0 to @cite{i-1} in steps of two.  Note that
30726 @code{for} has the same general outline as @code{let*}, except
30727 that each element of the header is a list of three or four
30728 things, not just two.
30730 @item
30731 The @code{foreach} construct loops over elements of a list.
30732 For example, @samp{(foreach ((x (cdr v))) body)} executes
30733 @code{body} with @cite{x} bound to each element of Calc vector
30734 @cite{v} in turn.  The purpose of @code{cdr} here is to skip over
30735 the initial @code{vec} symbol in the vector.
30737 @item
30738 The @code{break} function breaks out of the innermost enclosing
30739 @code{while}, @code{for}, or @code{foreach} loop.  If given a
30740 value, as in @samp{(break x)}, this value is returned by the
30741 loop.  (Lisp loops otherwise always return @code{nil}.)
30743 @item
30744 The @code{return} function prematurely returns from the enclosing
30745 function.  For example, @samp{(return (+ x y))} returns @cite{x+y}
30746 as the value of a function.  You can use @code{return} anywhere
30747 inside the body of the function.
30748 @end itemize
30750 Non-integer numbers (and extremely large integers) cannot be included
30751 directly into a @code{defmath} definition.  This is because the Lisp
30752 reader will fail to parse them long before @code{defmath} ever gets control.
30753 Instead, use the notation, @samp{:"3.1415"}.  In fact, any algebraic
30754 formula can go between the quotes.  For example,
30756 @smallexample
30757 (defmath sqexp (x)     ; sqexp(x) == sqrt(exp(x)) == exp(x*0.5)
30758   (and (numberp x)
30759        (exp :"x * 0.5")))
30760 @end smallexample
30762 expands to
30764 @smallexample
30765 (defun calcFunc-sqexp (x)
30766   (and (math-numberp x)
30767        (calcFunc-exp (math-mul x '(float 5 -1)))))
30768 @end smallexample
30770 Note the use of @code{numberp} as a guard to ensure that the argument is
30771 a number first, returning @code{nil} if not.  The exponential function
30772 could itself have been included in the expression, if we had preferred:
30773 @samp{:"exp(x * 0.5)"}.  As another example, the multiplication-and-recursion
30774 step of @code{myfact} could have been written
30776 @example
30777 :"n * myfact(n-1)"
30778 @end example
30780 If a file named @file{.emacs} exists in your home directory, Emacs reads
30781 and executes the Lisp forms in this file as it starts up.  While it may
30782 seem like a good idea to put your favorite @code{defmath} commands here,
30783 this has the unfortunate side-effect that parts of the Calculator must be
30784 loaded in to process the @code{defmath} commands whether or not you will
30785 actually use the Calculator!  A better effect can be had by writing
30787 @example
30788 (put 'calc-define 'thing '(progn
30789  (defmath ... )
30790  (defmath ... )
30792 @end example
30794 @noindent
30795 @vindex calc-define
30796 The @code{put} function adds a @dfn{property} to a symbol.  Each Lisp
30797 symbol has a list of properties associated with it.  Here we add a
30798 property with a name of @code{thing} and a @samp{(progn ...)} form as
30799 its value.  When Calc starts up, and at the start of every Calc command,
30800 the property list for the symbol @code{calc-define} is checked and the
30801 values of any properties found are evaluated as Lisp forms.  The
30802 properties are removed as they are evaluated.  The property names
30803 (like @code{thing}) are not used; you should choose something like the
30804 name of your project so as not to conflict with other properties.
30806 The net effect is that you can put the above code in your @file{.emacs}
30807 file and it will not be executed until Calc is loaded.  Or, you can put
30808 that same code in another file which you load by hand either before or
30809 after Calc itself is loaded.
30811 The properties of @code{calc-define} are evaluated in the same order
30812 that they were added.  They can assume that the Calc modules @file{calc.el},
30813 @file{calc-ext.el}, and @file{calc-macs.el} have been fully loaded, and
30814 that the @samp{*Calculator*} buffer will be the current buffer.
30816 If your @code{calc-define} property only defines algebraic functions,
30817 you can be sure that it will have been evaluated before Calc tries to
30818 call your function, even if the file defining the property is loaded
30819 after Calc is loaded.  But if the property defines commands or key
30820 sequences, it may not be evaluated soon enough.  (Suppose it defines the
30821 new command @code{tweak-calc}; the user can load your file, then type
30822 @kbd{M-x tweak-calc} before Calc has had chance to do anything.)  To
30823 protect against this situation, you can put
30825 @example
30826 (run-hooks 'calc-check-defines)
30827 @end example
30829 @findex calc-check-defines
30830 @noindent
30831 at the end of your file.  The @code{calc-check-defines} function is what
30832 looks for and evaluates properties on @code{calc-define}; @code{run-hooks}
30833 has the advantage that it is quietly ignored if @code{calc-check-defines}
30834 is not yet defined because Calc has not yet been loaded.
30836 Examples of things that ought to be enclosed in a @code{calc-define}
30837 property are @code{defmath} calls, @code{define-key} calls that modify
30838 the Calc key map, and any calls that redefine things defined inside Calc.
30839 Ordinary @code{defun}s need not be enclosed with @code{calc-define}.
30841 @node Defining Simple Commands, Defining Stack Commands, Defining Functions, Lisp Definitions
30842 @subsection Defining New Simple Commands
30844 @noindent
30845 @findex interactive
30846 If a @code{defmath} form contains an @code{interactive} clause, it defines
30847 a Calculator command.  Actually such a @code{defmath} results in @emph{two}
30848 function definitions:  One, a @samp{calcFunc-} function as was just described,
30849 with the @code{interactive} clause removed.  Two, a @samp{calc-} function
30850 with a suitable @code{interactive} clause and some sort of wrapper to make
30851 the command work in the Calc environment.
30853 In the simple case, the @code{interactive} clause has the same form as
30854 for normal Emacs Lisp commands:
30856 @smallexample
30857 (defmath increase-precision (delta)
30858   "Increase precision by DELTA."     ; This is the "documentation string"
30859   (interactive "p")                  ; Register this as a M-x-able command
30860   (setq calc-internal-prec (+ calc-internal-prec delta)))
30861 @end smallexample
30863 This expands to the pair of definitions,
30865 @smallexample
30866 (defun calc-increase-precision (delta)
30867   "Increase precision by DELTA."
30868   (interactive "p")
30869   (calc-wrapper
30870    (setq calc-internal-prec (math-add calc-internal-prec delta))))
30872 (defun calcFunc-increase-precision (delta)
30873   "Increase precision by DELTA."
30874   (setq calc-internal-prec (math-add calc-internal-prec delta)))
30875 @end smallexample
30877 @noindent
30878 where in this case the latter function would never really be used!  Note
30879 that since the Calculator stores small integers as plain Lisp integers,
30880 the @code{math-add} function will work just as well as the native
30881 @code{+} even when the intent is to operate on native Lisp integers.
30883 @findex calc-wrapper
30884 The @samp{calc-wrapper} call invokes a macro which surrounds the body of
30885 the function with code that looks roughly like this:
30887 @smallexample
30888 (let ((calc-command-flags nil))
30889   (unwind-protect
30890       (save-excursion
30891         (calc-select-buffer)
30892         @emph{body of function}
30893         @emph{renumber stack}
30894         @emph{clear} Working @emph{message})
30895     @emph{realign cursor and window}
30896     @emph{clear Inverse, Hyperbolic, and Keep Args flags}
30897     @emph{update Emacs mode line}))
30898 @end smallexample
30900 @findex calc-select-buffer
30901 The @code{calc-select-buffer} function selects the @samp{*Calculator*}
30902 buffer if necessary, say, because the command was invoked from inside
30903 the @samp{*Calc Trail*} window.
30905 @findex calc-set-command-flag
30906 You can call, for example, @code{(calc-set-command-flag 'no-align)} to set
30907 the above-mentioned command flags.  The following command flags are
30908 recognized by Calc routines:
30910 @table @code
30911 @item renum-stack
30912 Stack line numbers @samp{1:}, @samp{2:}, and so on must be renumbered
30913 after this command completes.  This is set by routines like
30914 @code{calc-push}.
30916 @item clear-message
30917 Calc should call @samp{(message "")} if this command completes normally
30918 (to clear a ``Working@dots{}'' message out of the echo area).
30920 @item no-align
30921 Do not move the cursor back to the @samp{.} top-of-stack marker.
30923 @item position-point
30924 Use the variables @code{calc-position-point-line} and
30925 @code{calc-position-point-column} to position the cursor after
30926 this command finishes.
30928 @item keep-flags
30929 Do not clear @code{calc-inverse-flag}, @code{calc-hyperbolic-flag},
30930 and @code{calc-keep-args-flag} at the end of this command.
30932 @item do-edit
30933 Switch to buffer @samp{*Calc Edit*} after this command.
30935 @item hold-trail
30936 Do not move trail pointer to end of trail when something is recorded
30937 there.
30938 @end table
30940 @kindex Y
30941 @kindex Y ?
30942 @vindex calc-Y-help-msgs
30943 Calc reserves a special prefix key, shift-@kbd{Y}, for user-written
30944 extensions to Calc.  There are no built-in commands that work with
30945 this prefix key; you must call @code{define-key} from Lisp (probably
30946 from inside a @code{calc-define} property) to add to it.  Initially only
30947 @kbd{Y ?} is defined; it takes help messages from a list of strings
30948 (initially @code{nil}) in the variable @code{calc-Y-help-msgs}.  All
30949 other undefined keys except for @kbd{Y} are reserved for use by
30950 future versions of Calc.
30952 If you are writing a Calc enhancement which you expect to give to
30953 others, it is best to minimize the number of @kbd{Y}-key sequences
30954 you use.  In fact, if you have more than one key sequence you should
30955 consider defining three-key sequences with a @kbd{Y}, then a key that
30956 stands for your package, then a third key for the particular command
30957 within your package.
30959 Users may wish to install several Calc enhancements, and it is possible
30960 that several enhancements will choose to use the same key.  In the
30961 example below, a variable @code{inc-prec-base-key} has been defined
30962 to contain the key that identifies the @code{inc-prec} package.  Its
30963 value is initially @code{"P"}, but a user can change this variable
30964 if necessary without having to modify the file.
30966 Here is a complete file, @file{inc-prec.el}, which makes a @kbd{Y P I}
30967 command that increases the precision, and a @kbd{Y P D} command that
30968 decreases the precision.
30970 @smallexample
30971 ;;; Increase and decrease Calc precision.  Dave Gillespie, 5/31/91.
30972 ;;; (Include copyright or copyleft stuff here.)
30974 (defvar inc-prec-base-key "P"
30975   "Base key for inc-prec.el commands.")
30977 (put 'calc-define 'inc-prec '(progn
30979 (define-key calc-mode-map (format "Y%sI" inc-prec-base-key)
30980             'increase-precision)
30981 (define-key calc-mode-map (format "Y%sD" inc-prec-base-key)
30982             'decrease-precision)
30984 (setq calc-Y-help-msgs
30985       (cons (format "%s + Inc-prec, Dec-prec" inc-prec-base-key)
30986             calc-Y-help-msgs))
30988 (defmath increase-precision (delta)
30989   "Increase precision by DELTA."
30990   (interactive "p")
30991   (setq calc-internal-prec (+ calc-internal-prec delta)))
30993 (defmath decrease-precision (delta)
30994   "Decrease precision by DELTA."
30995   (interactive "p")
30996   (setq calc-internal-prec (- calc-internal-prec delta)))
30998 ))  ; end of calc-define property
31000 (run-hooks 'calc-check-defines)
31001 @end smallexample
31003 @node Defining Stack Commands, Argument Qualifiers, Defining Simple Commands, Lisp Definitions
31004 @subsection Defining New Stack-Based Commands
31006 @noindent
31007 To define a new computational command which takes and/or leaves arguments
31008 on the stack, a special form of @code{interactive} clause is used.
31010 @example
31011 (interactive @var{num} @var{tag})
31012 @end example
31014 @noindent
31015 where @var{num} is an integer, and @var{tag} is a string.  The effect is
31016 to pop @var{num} values off the stack, resimplify them by calling
31017 @code{calc-normalize}, and hand them to your function according to the
31018 function's argument list.  Your function may include @code{&optional} and
31019 @code{&rest} parameters, so long as calling the function with @var{num}
31020 parameters is legal.
31022 Your function must return either a number or a formula in a form
31023 acceptable to Calc, or a list of such numbers or formulas.  These value(s)
31024 are pushed onto the stack when the function completes.  They are also
31025 recorded in the Calc Trail buffer on a line beginning with @var{tag},
31026 a string of (normally) four characters or less.  If you omit @var{tag}
31027 or use @code{nil} as a tag, the result is not recorded in the trail.
31029 As an example, the definition
31031 @smallexample
31032 (defmath myfact (n)
31033   "Compute the factorial of the integer at the top of the stack."
31034   (interactive 1 "fact")
31035   (if (> n 0)
31036       (* n (myfact (1- n)))
31037     (and (= n 0) 1)))
31038 @end smallexample
31040 @noindent
31041 is a version of the factorial function shown previously which can be used
31042 as a command as well as an algebraic function.  It expands to
31044 @smallexample
31045 (defun calc-myfact ()
31046   "Compute the factorial of the integer at the top of the stack."
31047   (interactive)
31048   (calc-slow-wrapper
31049    (calc-enter-result 1 "fact"
31050      (cons 'calcFunc-myfact (calc-top-list-n 1)))))
31052 (defun calcFunc-myfact (n)
31053   "Compute the factorial of the integer at the top of the stack."
31054   (if (math-posp n)
31055       (math-mul n (calcFunc-myfact (math-add n -1)))
31056     (and (math-zerop n) 1)))
31057 @end smallexample
31059 @findex calc-slow-wrapper
31060 The @code{calc-slow-wrapper} function is a version of @code{calc-wrapper}
31061 that automatically puts up a @samp{Working...} message before the
31062 computation begins.  (This message can be turned off by the user
31063 with an @kbd{m w} (@code{calc-working}) command.)
31065 @findex calc-top-list-n
31066 The @code{calc-top-list-n} function returns a list of the specified number
31067 of values from the top of the stack.  It resimplifies each value by
31068 calling @code{calc-normalize}.  If its argument is zero it returns an
31069 empty list.  It does not actually remove these values from the stack.
31071 @findex calc-enter-result
31072 The @code{calc-enter-result} function takes an integer @var{num} and string
31073 @var{tag} as described above, plus a third argument which is either a
31074 Calculator data object or a list of such objects.  These objects are
31075 resimplified and pushed onto the stack after popping the specified number
31076 of values from the stack.  If @var{tag} is non-@code{nil}, the values
31077 being pushed are also recorded in the trail.
31079 Note that if @code{calcFunc-myfact} returns @code{nil} this represents
31080 ``leave the function in symbolic form.''  To return an actual empty list,
31081 in the sense that @code{calc-enter-result} will push zero elements back
31082 onto the stack, you should return the special value @samp{'(nil)}, a list
31083 containing the single symbol @code{nil}.
31085 The @code{interactive} declaration can actually contain a limited
31086 Emacs-style code string as well which comes just before @var{num} and
31087 @var{tag}.  Currently the only Emacs code supported is @samp{"p"}, as in
31089 @example
31090 (defmath foo (a b &optional c)
31091   (interactive "p" 2 "foo")
31092   @var{body})
31093 @end example
31095 In this example, the command @code{calc-foo} will evaluate the expression
31096 @samp{foo(a,b)} if executed with no argument, or @samp{foo(a,b,n)} if
31097 executed with a numeric prefix argument of @cite{n}.
31099 The other code string allowed is @samp{"m"} (unrelated to the usual @samp{"m"}
31100 code as used with @code{defun}).  It uses the numeric prefix argument as the
31101 number of objects to remove from the stack and pass to the function.
31102 In this case, the integer @var{num} serves as a default number of
31103 arguments to be used when no prefix is supplied.
31105 @node Argument Qualifiers, Example Definitions, Defining Stack Commands, Lisp Definitions
31106 @subsection Argument Qualifiers
31108 @noindent
31109 Anywhere a parameter name can appear in the parameter list you can also use
31110 an @dfn{argument qualifier}.  Thus the general form of a definition is:
31112 @example
31113 (defmath @var{name} (@var{param} @var{param...}
31114                &optional @var{param} @var{param...}
31115                &rest @var{param})
31116   @var{body})
31117 @end example
31119 @noindent
31120 where each @var{param} is either a symbol or a list of the form
31122 @example
31123 (@var{qual} @var{param})
31124 @end example
31126 The following qualifiers are recognized:
31128 @table @samp
31129 @item complete
31130 @findex complete
31131 The argument must not be an incomplete vector, interval, or complex number.
31132 (This is rarely needed since the Calculator itself will never call your
31133 function with an incomplete argument.  But there is nothing stopping your
31134 own Lisp code from calling your function with an incomplete argument.)@refill
31136 @item integer
31137 @findex integer
31138 The argument must be an integer.  If it is an integer-valued float
31139 it will be accepted but converted to integer form.  Non-integers and
31140 formulas are rejected.
31142 @item natnum
31143 @findex natnum
31144 Like @samp{integer}, but the argument must be non-negative.
31146 @item fixnum
31147 @findex fixnum
31148 Like @samp{integer}, but the argument must fit into a native Lisp integer,
31149 which on most systems means less than 2^23 in absolute value.  The
31150 argument is converted into Lisp-integer form if necessary.
31152 @item float
31153 @findex float
31154 The argument is converted to floating-point format if it is a number or
31155 vector.  If it is a formula it is left alone.  (The argument is never
31156 actually rejected by this qualifier.)
31158 @item @var{pred}
31159 The argument must satisfy predicate @var{pred}, which is one of the
31160 standard Calculator predicates.  @xref{Predicates}.
31162 @item not-@var{pred}
31163 The argument must @emph{not} satisfy predicate @var{pred}.
31164 @end table
31166 For example,
31168 @example
31169 (defmath foo (a (constp (not-matrixp b)) &optional (float c)
31170               &rest (integer d))
31171   @var{body})
31172 @end example
31174 @noindent
31175 expands to
31177 @example
31178 (defun calcFunc-foo (a b &optional c &rest d)
31179   (and (math-matrixp b)
31180        (math-reject-arg b 'not-matrixp))
31181   (or (math-constp b)
31182       (math-reject-arg b 'constp))
31183   (and c (setq c (math-check-float c)))
31184   (setq d (mapcar 'math-check-integer d))
31185   @var{body})
31186 @end example
31188 @noindent
31189 which performs the necessary checks and conversions before executing the
31190 body of the function.
31192 @node Example Definitions, Calling Calc from Your Programs, Argument Qualifiers, Lisp Definitions
31193 @subsection Example Definitions
31195 @noindent
31196 This section includes some Lisp programming examples on a larger scale.
31197 These programs make use of some of the Calculator's internal functions;
31198 @pxref{Internals}.
31200 @menu
31201 * Bit Counting Example::
31202 * Sine Example::
31203 @end menu
31205 @node Bit Counting Example, Sine Example, Example Definitions, Example Definitions
31206 @subsubsection Bit-Counting
31208 @noindent
31209 @c @starindex
31210 @tindex bcount
31211 Calc does not include a built-in function for counting the number of
31212 ``one'' bits in a binary integer.  It's easy to invent one using @kbd{b u}
31213 to convert the integer to a set, and @kbd{V #} to count the elements of
31214 that set; let's write a function that counts the bits without having to
31215 create an intermediate set.
31217 @smallexample
31218 (defmath bcount ((natnum n))
31219   (interactive 1 "bcnt")
31220   (let ((count 0))
31221     (while (> n 0)
31222       (if (oddp n)
31223           (setq count (1+ count)))
31224       (setq n (lsh n -1)))
31225     count))
31226 @end smallexample
31228 @noindent
31229 When this is expanded by @code{defmath}, it will become the following
31230 Emacs Lisp function:
31232 @smallexample
31233 (defun calcFunc-bcount (n)
31234   (setq n (math-check-natnum n))
31235   (let ((count 0))
31236     (while (math-posp n)
31237       (if (math-oddp n)
31238           (setq count (math-add count 1)))
31239       (setq n (calcFunc-lsh n -1)))
31240     count))
31241 @end smallexample
31243 If the input numbers are large, this function involves a fair amount
31244 of arithmetic.  A binary right shift is essentially a division by two;
31245 recall that Calc stores integers in decimal form so bit shifts must
31246 involve actual division.
31248 To gain a bit more efficiency, we could divide the integer into
31249 @i{n}-bit chunks, each of which can be handled quickly because
31250 they fit into Lisp integers.  It turns out that Calc's arithmetic
31251 routines are especially fast when dividing by an integer less than
31252 1000, so we can set @i{n = 9} bits and use repeated division by 512:
31254 @smallexample
31255 (defmath bcount ((natnum n))
31256   (interactive 1 "bcnt")
31257   (let ((count 0))
31258     (while (not (fixnump n))
31259       (let ((qr (idivmod n 512)))
31260         (setq count (+ count (bcount-fixnum (cdr qr)))
31261               n (car qr))))
31262     (+ count (bcount-fixnum n))))
31264 (defun bcount-fixnum (n)
31265   (let ((count 0))
31266     (while (> n 0)
31267       (setq count (+ count (logand n 1))
31268             n (lsh n -1)))
31269     count))
31270 @end smallexample
31272 @noindent
31273 Note that the second function uses @code{defun}, not @code{defmath}.
31274 Because this function deals only with native Lisp integers (``fixnums''),
31275 it can use the actual Emacs @code{+} and related functions rather
31276 than the slower but more general Calc equivalents which @code{defmath}
31277 uses.
31279 The @code{idivmod} function does an integer division, returning both
31280 the quotient and the remainder at once.  Again, note that while it
31281 might seem that @samp{(logand n 511)} and @samp{(lsh n -9)} are
31282 more efficient ways to split off the bottom nine bits of @code{n},
31283 actually they are less efficient because each operation is really
31284 a division by 512 in disguise; @code{idivmod} allows us to do the
31285 same thing with a single division by 512.
31287 @node Sine Example, , Bit Counting Example, Example Definitions
31288 @subsubsection The Sine Function
31290 @noindent
31291 @c @starindex
31292 @tindex mysin
31293 A somewhat limited sine function could be defined as follows, using the
31294 well-known Taylor series expansion for @c{$\sin x$}
31295 @samp{sin(x)}:
31297 @smallexample
31298 (defmath mysin ((float (anglep x)))
31299   (interactive 1 "mysn")
31300   (setq x (to-radians x))    ; Convert from current angular mode.
31301   (let ((sum x)              ; Initial term of Taylor expansion of sin.
31302         newsum
31303         (nfact 1)            ; "nfact" equals "n" factorial at all times.
31304         (xnegsqr :"-(x^2)")) ; "xnegsqr" equals -x^2.
31305     (for ((n 3 100 2))       ; Upper limit of 100 is a good precaution.
31306       (working "mysin" sum)  ; Display "Working" message, if enabled.
31307       (setq nfact (* nfact (1- n) n)
31308             x (* x xnegsqr)
31309             newsum (+ sum (/ x nfact)))
31310       (if (~= newsum sum)    ; If newsum is "nearly equal to" sum,
31311           (break))           ;  then we are done.
31312       (setq sum newsum))
31313     sum))
31314 @end smallexample
31316 The actual @code{sin} function in Calc works by first reducing the problem
31317 to a sine or cosine of a nonnegative number less than @c{$\pi \over 4$}
31318 @cite{pi/4}.  This
31319 ensures that the Taylor series will converge quickly.  Also, the calculation
31320 is carried out with two extra digits of precision to guard against cumulative
31321 round-off in @samp{sum}.  Finally, complex arguments are allowed and handled
31322 by a separate algorithm.
31324 @smallexample
31325 (defmath mysin ((float (scalarp x)))
31326   (interactive 1 "mysn")
31327   (setq x (to-radians x))    ; Convert from current angular mode.
31328   (with-extra-prec 2         ; Evaluate with extra precision.
31329     (cond ((complexp x)
31330            (mysin-complex x))
31331           ((< x 0)
31332            (- (mysin-raw (- x)))    ; Always call mysin-raw with x >= 0.
31333           (t (mysin-raw x))))))
31335 (defmath mysin-raw (x)
31336   (cond ((>= x 7)
31337          (mysin-raw (% x (two-pi))))     ; Now x < 7.
31338         ((> x (pi-over-2))
31339          (- (mysin-raw (- x (pi)))))     ; Now -pi/2 <= x <= pi/2.
31340         ((> x (pi-over-4))
31341          (mycos-raw (- x (pi-over-2))))  ; Now -pi/2 <= x <= pi/4.
31342         ((< x (- (pi-over-4)))
31343          (- (mycos-raw (+ x (pi-over-2)))))  ; Now -pi/4 <= x <= pi/4,
31344         (t (mysin-series x))))           ; so the series will be efficient.
31345 @end smallexample
31347 @noindent
31348 where @code{mysin-complex} is an appropriate function to handle complex
31349 numbers, @code{mysin-series} is the routine to compute the sine Taylor
31350 series as before, and @code{mycos-raw} is a function analogous to
31351 @code{mysin-raw} for cosines.
31353 The strategy is to ensure that @cite{x} is nonnegative before calling
31354 @code{mysin-raw}.  This function then recursively reduces its argument
31355 to a suitable range, namely, plus-or-minus @c{$\pi \over 4$}
31356 @cite{pi/4}.  Note that each
31357 test, and particularly the first comparison against 7, is designed so
31358 that small roundoff errors cannnot produce an infinite loop.  (Suppose
31359 we compared with @samp{(two-pi)} instead; if due to roundoff problems
31360 the modulo operator ever returned @samp{(two-pi)} exactly, an infinite
31361 recursion could result!)  We use modulo only for arguments that will
31362 clearly get reduced, knowing that the next rule will catch any reductions
31363 that this rule misses.
31365 If a program is being written for general use, it is important to code
31366 it carefully as shown in this second example.  For quick-and-dirty programs,
31367 when you know that your own use of the sine function will never encounter
31368 a large argument, a simpler program like the first one shown is fine.
31370 @node Calling Calc from Your Programs, Internals, Example Definitions, Lisp Definitions
31371 @subsection Calling Calc from Your Lisp Programs
31373 @noindent
31374 A later section (@pxref{Internals}) gives a full description of
31375 Calc's internal Lisp functions.  It's not hard to call Calc from
31376 inside your programs, but the number of these functions can be daunting.
31377 So Calc provides one special ``programmer-friendly'' function called
31378 @code{calc-eval} that can be made to do just about everything you
31379 need.  It's not as fast as the low-level Calc functions, but it's
31380 much simpler to use!
31382 It may seem that @code{calc-eval} itself has a daunting number of
31383 options, but they all stem from one simple operation.
31385 In its simplest manifestation, @samp{(calc-eval "1+2")} parses the
31386 string @code{"1+2"} as if it were a Calc algebraic entry and returns
31387 the result formatted as a string: @code{"3"}.
31389 Since @code{calc-eval} is on the list of recommended @code{autoload}
31390 functions, you don't need to make any special preparations to load
31391 Calc before calling @code{calc-eval} the first time.  Calc will be
31392 loaded and initialized for you.
31394 All the Calc modes that are currently in effect will be used when
31395 evaluating the expression and formatting the result.
31397 @ifinfo
31398 @example
31400 @end example
31401 @end ifinfo
31402 @subsubsection Additional Arguments to @code{calc-eval}
31404 @noindent
31405 If the input string parses to a list of expressions, Calc returns
31406 the results separated by @code{", "}.  You can specify a different
31407 separator by giving a second string argument to @code{calc-eval}:
31408 @samp{(calc-eval "1+2,3+4" ";")} returns @code{"3;7"}.
31410 The ``separator'' can also be any of several Lisp symbols which
31411 request other behaviors from @code{calc-eval}.  These are discussed
31412 one by one below.
31414 You can give additional arguments to be substituted for
31415 @samp{$}, @samp{$$}, and so on in the main expression.  For
31416 example, @samp{(calc-eval "$/$$" nil "7" "1+1")} evaluates the
31417 expression @code{"7/(1+1)"} to yield the result @code{"3.5"}
31418 (assuming Fraction mode is not in effect).  Note the @code{nil}
31419 used as a placeholder for the item-separator argument.
31421 @ifinfo
31422 @example
31424 @end example
31425 @end ifinfo
31426 @subsubsection Error Handling
31428 @noindent
31429 If @code{calc-eval} encounters an error, it returns a list containing
31430 the character position of the error, plus a suitable message as a
31431 string.  Note that @samp{1 / 0} is @emph{not} an error by Calc's
31432 standards; it simply returns the string @code{"1 / 0"} which is the
31433 division left in symbolic form.  But @samp{(calc-eval "1/")} will
31434 return the list @samp{(2 "Expected a number")}.
31436 If you bind the variable @code{calc-eval-error} to @code{t}
31437 using a @code{let} form surrounding the call to @code{calc-eval},
31438 errors instead call the Emacs @code{error} function which aborts
31439 to the Emacs command loop with a beep and an error message.
31441 If you bind this variable to the symbol @code{string}, error messages
31442 are returned as strings instead of lists.  The character position is
31443 ignored.
31445 As a courtesy to other Lisp code which may be using Calc, be sure
31446 to bind @code{calc-eval-error} using @code{let} rather than changing
31447 it permanently with @code{setq}.
31449 @ifinfo
31450 @example
31452 @end example
31453 @end ifinfo
31454 @subsubsection Numbers Only
31456 @noindent
31457 Sometimes it is preferable to treat @samp{1 / 0} as an error
31458 rather than returning a symbolic result.  If you pass the symbol
31459 @code{num} as the second argument to @code{calc-eval}, results
31460 that are not constants are treated as errors.  The error message
31461 reported is the first @code{calc-why} message if there is one,
31462 or otherwise ``Number expected.''
31464 A result is ``constant'' if it is a number, vector, or other
31465 object that does not include variables or function calls.  If it
31466 is a vector, the components must themselves be constants.
31468 @ifinfo
31469 @example
31471 @end example
31472 @end ifinfo
31473 @subsubsection Default Modes
31475 @noindent
31476 If the first argument to @code{calc-eval} is a list whose first
31477 element is a formula string, then @code{calc-eval} sets all the
31478 various Calc modes to their default values while the formula is
31479 evaluated and formatted.  For example, the precision is set to 12
31480 digits, digit grouping is turned off, and the normal language
31481 mode is used.
31483 This same principle applies to the other options discussed below.
31484 If the first argument would normally be @var{x}, then it can also
31485 be the list @samp{(@var{x})} to use the default mode settings.
31487 If there are other elements in the list, they are taken as
31488 variable-name/value pairs which override the default mode
31489 settings.  Look at the documentation at the front of the
31490 @file{calc.el} file to find the names of the Lisp variables for
31491 the various modes.  The mode settings are restored to their
31492 original values when @code{calc-eval} is done.
31494 For example, @samp{(calc-eval '("$+$$" calc-internal-prec 8) 'num a b)}
31495 computes the sum of two numbers, requiring a numeric result, and
31496 using default mode settings except that the precision is 8 instead
31497 of the default of 12.
31499 It's usually best to use this form of @code{calc-eval} unless your
31500 program actually considers the interaction with Calc's mode settings
31501 to be a feature.  This will avoid all sorts of potential ``gotchas'';
31502 consider what happens with @samp{(calc-eval "sqrt(2)" 'num)}
31503 when the user has left Calc in symbolic mode or no-simplify mode.
31505 As another example, @samp{(equal (calc-eval '("$<$$") nil a b) "1")}
31506 checks if the number in string @cite{a} is less than the one in
31507 string @cite{b}.  Without using a list, the integer 1 might
31508 come out in a variety of formats which would be hard to test for
31509 conveniently: @code{"1"}, @code{"8#1"}, @code{"00001"}.  (But
31510 see ``Predicates'' mode, below.)
31512 @ifinfo
31513 @example
31515 @end example
31516 @end ifinfo
31517 @subsubsection Raw Numbers
31519 @noindent
31520 Normally all input and output for @code{calc-eval} is done with strings.
31521 You can do arithmetic with, say, @samp{(calc-eval "$+$$" nil a b)}
31522 in place of @samp{(+ a b)}, but this is very inefficient since the
31523 numbers must be converted to and from string format as they are passed
31524 from one @code{calc-eval} to the next.
31526 If the separator is the symbol @code{raw}, the result will be returned
31527 as a raw Calc data structure rather than a string.  You can read about
31528 how these objects look in the following sections, but usually you can
31529 treat them as ``black box'' objects with no important internal
31530 structure.
31532 There is also a @code{rawnum} symbol, which is a combination of
31533 @code{raw} (returning a raw Calc object) and @code{num} (signalling
31534 an error if that object is not a constant).
31536 You can pass a raw Calc object to @code{calc-eval} in place of a
31537 string, either as the formula itself or as one of the @samp{$}
31538 arguments.  Thus @samp{(calc-eval "$+$$" 'raw a b)} is an
31539 addition function that operates on raw Calc objects.  Of course
31540 in this case it would be easier to call the low-level @code{math-add}
31541 function in Calc, if you can remember its name.
31543 In particular, note that a plain Lisp integer is acceptable to Calc
31544 as a raw object.  (All Lisp integers are accepted on input, but
31545 integers of more than six decimal digits are converted to ``big-integer''
31546 form for output.  @xref{Data Type Formats}.)
31548 When it comes time to display the object, just use @samp{(calc-eval a)}
31549 to format it as a string.
31551 It is an error if the input expression evaluates to a list of
31552 values.  The separator symbol @code{list} is like @code{raw}
31553 except that it returns a list of one or more raw Calc objects.
31555 Note that a Lisp string is not a valid Calc object, nor is a list
31556 containing a string.  Thus you can still safely distinguish all the
31557 various kinds of error returns discussed above.
31559 @ifinfo
31560 @example
31562 @end example
31563 @end ifinfo
31564 @subsubsection Predicates
31566 @noindent
31567 If the separator symbol is @code{pred}, the result of the formula is
31568 treated as a true/false value; @code{calc-eval} returns @code{t} or
31569 @code{nil}, respectively.  A value is considered ``true'' if it is a
31570 non-zero number, or false if it is zero or if it is not a number.
31572 For example, @samp{(calc-eval "$<$$" 'pred a b)} tests whether
31573 one value is less than another.
31575 As usual, it is also possible for @code{calc-eval} to return one of
31576 the error indicators described above.  Lisp will interpret such an
31577 indicator as ``true'' if you don't check for it explicitly.  If you
31578 wish to have an error register as ``false'', use something like
31579 @samp{(eq (calc-eval ...) t)}.
31581 @ifinfo
31582 @example
31584 @end example
31585 @end ifinfo
31586 @subsubsection Variable Values
31588 @noindent
31589 Variables in the formula passed to @code{calc-eval} are not normally
31590 replaced by their values.  If you wish this, you can use the
31591 @code{evalv} function (@pxref{Algebraic Manipulation}).  For example,
31592 if 4 is stored in Calc variable @code{a} (i.e., in Lisp variable
31593 @code{var-a}), then @samp{(calc-eval "a+pi")} will return the
31594 formula @code{"a + pi"}, but @samp{(calc-eval "evalv(a+pi)")}
31595 will return @code{"7.14159265359"}.
31597 To store in a Calc variable, just use @code{setq} to store in the
31598 corresponding Lisp variable.  (This is obtained by prepending
31599 @samp{var-} to the Calc variable name.)  Calc routines will
31600 understand either string or raw form values stored in variables,
31601 although raw data objects are much more efficient.  For example,
31602 to increment the Calc variable @code{a}:
31604 @example
31605 (setq var-a (calc-eval "evalv(a+1)" 'raw))
31606 @end example
31608 @ifinfo
31609 @example
31611 @end example
31612 @end ifinfo
31613 @subsubsection Stack Access
31615 @noindent
31616 If the separator symbol is @code{push}, the formula argument is
31617 evaluated (with possible @samp{$} expansions, as usual).  The
31618 result is pushed onto the Calc stack.  The return value is @code{nil}
31619 (unless there is an error from evaluating the formula, in which
31620 case the return value depends on @code{calc-eval-error} in the
31621 usual way).
31623 If the separator symbol is @code{pop}, the first argument to
31624 @code{calc-eval} must be an integer instead of a string.  That
31625 many values are popped from the stack and thrown away.  A negative
31626 argument deletes the entry at that stack level.  The return value
31627 is the number of elements remaining in the stack after popping;
31628 @samp{(calc-eval 0 'pop)} is a good way to measure the size of
31629 the stack.
31631 If the separator symbol is @code{top}, the first argument to
31632 @code{calc-eval} must again be an integer.  The value at that
31633 stack level is formatted as a string and returned.  Thus
31634 @samp{(calc-eval 1 'top)} returns the top-of-stack value.  If the
31635 integer is out of range, @code{nil} is returned.
31637 The separator symbol @code{rawtop} is just like @code{top} except
31638 that the stack entry is returned as a raw Calc object instead of
31639 as a string.
31641 In all of these cases the first argument can be made a list in
31642 order to force the default mode settings, as described above.
31643 Thus @samp{(calc-eval '(2 calc-number-radix 16) 'top)} returns the
31644 second-to-top stack entry, formatted as a string using the default
31645 instead of current display modes, except that the radix is
31646 hexadecimal instead of decimal.
31648 It is, of course, polite to put the Calc stack back the way you
31649 found it when you are done, unless the user of your program is
31650 actually expecting it to affect the stack.
31652 Note that you do not actually have to switch into the @samp{*Calculator*}
31653 buffer in order to use @code{calc-eval}; it temporarily switches into
31654 the stack buffer if necessary.
31656 @ifinfo
31657 @example
31659 @end example
31660 @end ifinfo
31661 @subsubsection Keyboard Macros
31663 @noindent
31664 If the separator symbol is @code{macro}, the first argument must be a
31665 string of characters which Calc can execute as a sequence of keystrokes.
31666 This switches into the Calc buffer for the duration of the macro.
31667 For example, @samp{(calc-eval "vx5\rVR+" 'macro)} pushes the
31668 vector @samp{[1,2,3,4,5]} on the stack and then replaces it
31669 with the sum of those numbers.  Note that @samp{\r} is the Lisp
31670 notation for the carriage-return, @key{RET}, character.
31672 If your keyboard macro wishes to pop the stack, @samp{\C-d} is
31673 safer than @samp{\177} (the @key{DEL} character) because some
31674 installations may have switched the meanings of @key{DEL} and
31675 @kbd{C-h}.  Calc always interprets @kbd{C-d} as a synonym for
31676 ``pop-stack'' regardless of key mapping.
31678 If you provide a third argument to @code{calc-eval}, evaluation
31679 of the keyboard macro will leave a record in the Trail using
31680 that argument as a tag string.  Normally the Trail is unaffected.
31682 The return value in this case is always @code{nil}.
31684 @ifinfo
31685 @example
31687 @end example
31688 @end ifinfo
31689 @subsubsection Lisp Evaluation
31691 @noindent
31692 Finally, if the separator symbol is @code{eval}, then the Lisp
31693 @code{eval} function is called on the first argument, which must
31694 be a Lisp expression rather than a Calc formula.  Remember to
31695 quote the expression so that it is not evaluated until inside
31696 @code{calc-eval}.
31698 The difference from plain @code{eval} is that @code{calc-eval}
31699 switches to the Calc buffer before evaluating the expression.
31700 For example, @samp{(calc-eval '(setq calc-internal-prec 17) 'eval)}
31701 will correctly affect the buffer-local Calc precision variable.
31703 An alternative would be @samp{(calc-eval '(calc-precision 17) 'eval)}.
31704 This is evaluating a call to the function that is normally invoked
31705 by the @kbd{p} key, giving it 17 as its ``numeric prefix argument.''
31706 Note that this function will leave a message in the echo area as
31707 a side effect.  Also, all Calc functions switch to the Calc buffer
31708 automatically if not invoked from there, so the above call is
31709 also equivalent to @samp{(calc-precision 17)} by itself.
31710 In all cases, Calc uses @code{save-excursion} to switch back to
31711 your original buffer when it is done.
31713 As usual the first argument can be a list that begins with a Lisp
31714 expression to use default instead of current mode settings.
31716 The result of @code{calc-eval} in this usage is just the result
31717 returned by the evaluated Lisp expression.
31719 @ifinfo
31720 @example
31722 @end example
31723 @end ifinfo
31724 @subsubsection Example
31726 @noindent
31727 @findex convert-temp
31728 Here is a sample Emacs command that uses @code{calc-eval}.  Suppose
31729 you have a document with lots of references to temperatures on the
31730 Fahrenheit scale, say ``98.6 F'', and you wish to convert these
31731 references to Centigrade.  The following command does this conversion.
31732 Place the Emacs cursor right after the letter ``F'' and invoke the
31733 command to change ``98.6 F'' to ``37 C''.  Or, if the temperature is
31734 already in Centigrade form, the command changes it back to Fahrenheit.
31736 @example
31737 (defun convert-temp ()
31738   (interactive)
31739   (save-excursion
31740     (re-search-backward "[^-.0-9]\\([-.0-9]+\\) *\\([FC]\\)")
31741     (let* ((top1 (match-beginning 1))
31742            (bot1 (match-end 1))
31743            (number (buffer-substring top1 bot1))
31744            (top2 (match-beginning 2))
31745            (bot2 (match-end 2))
31746            (type (buffer-substring top2 bot2)))
31747       (if (equal type "F")
31748           (setq type "C"
31749                 number (calc-eval "($ - 32)*5/9" nil number))
31750         (setq type "F"
31751               number (calc-eval "$*9/5 + 32" nil number)))
31752       (goto-char top2)
31753       (delete-region top2 bot2)
31754       (insert-before-markers type)
31755       (goto-char top1)
31756       (delete-region top1 bot1)
31757       (if (string-match "\\.$" number)   ; change "37." to "37"
31758           (setq number (substring number 0 -1)))
31759       (insert number))))
31760 @end example
31762 Note the use of @code{insert-before-markers} when changing between
31763 ``F'' and ``C'', so that the character winds up before the cursor
31764 instead of after it.
31766 @node Internals, , Calling Calc from Your Programs, Lisp Definitions
31767 @subsection Calculator Internals
31769 @noindent
31770 This section describes the Lisp functions defined by the Calculator that
31771 may be of use to user-written Calculator programs (as described in the
31772 rest of this chapter).  These functions are shown by their names as they
31773 conventionally appear in @code{defmath}.  Their full Lisp names are
31774 generally gotten by prepending @samp{calcFunc-} or @samp{math-} to their
31775 apparent names.  (Names that begin with @samp{calc-} are already in
31776 their full Lisp form.)  You can use the actual full names instead if you
31777 prefer them, or if you are calling these functions from regular Lisp.
31779 The functions described here are scattered throughout the various
31780 Calc component files.  Note that @file{calc.el} includes @code{autoload}s
31781 for only a few component files; when Calc wants to call an advanced
31782 function it calls @samp{(calc-extensions)} first; this function
31783 autoloads @file{calc-ext.el}, which in turn autoloads all the functions
31784 in the remaining component files.
31786 Because @code{defmath} itself uses the extensions, user-written code
31787 generally always executes with the extensions already loaded, so
31788 normally you can use any Calc function and be confident that it will
31789 be autoloaded for you when necessary.  If you are doing something
31790 special, check carefully to make sure each function you are using is
31791 from @file{calc.el} or its components, and call @samp{(calc-extensions)}
31792 before using any function based in @file{calc-ext.el} if you can't
31793 prove this file will already be loaded.
31795 @menu
31796 * Data Type Formats::
31797 * Interactive Lisp Functions::
31798 * Stack Lisp Functions::
31799 * Predicates::
31800 * Computational Lisp Functions::
31801 * Vector Lisp Functions::
31802 * Symbolic Lisp Functions::
31803 * Formatting Lisp Functions::
31804 * Hooks::
31805 @end menu
31807 @node Data Type Formats, Interactive Lisp Functions, Internals, Internals
31808 @subsubsection Data Type Formats
31810 @noindent
31811 Integers are stored in either of two ways, depending on their magnitude.
31812 Integers less than one million in absolute value are stored as standard
31813 Lisp integers.  This is the only storage format for Calc data objects
31814 which is not a Lisp list.
31816 Large integers are stored as lists of the form @samp{(bigpos @var{d0}
31817 @var{d1} @var{d2} @dots{})} for positive integers 1000000 or more, or
31818 @samp{(bigneg @var{d0} @var{d1} @var{d2} @dots{})} for negative integers
31819 @i{-1000000} or less.  Each @var{d} is a base-1000 ``digit,'' a Lisp integer
31820 from 0 to 999.  The least significant digit is @var{d0}; the last digit,
31821 @var{dn}, which is always nonzero, is the most significant digit.  For
31822 example, the integer @i{-12345678} is stored as @samp{(bigneg 678 345 12)}.
31824 The distinction between small and large integers is entirely hidden from
31825 the user.  In @code{defmath} definitions, the Lisp predicate @code{integerp}
31826 returns true for either kind of integer, and in general both big and small
31827 integers are accepted anywhere the word ``integer'' is used in this manual.
31828 If the distinction must be made, native Lisp integers are called @dfn{fixnums}
31829 and large integers are called @dfn{bignums}.
31831 Fractions are stored as a list of the form, @samp{(frac @var{n} @var{d})}
31832 where @var{n} is an integer (big or small) numerator, @var{d} is an
31833 integer denominator greater than one, and @var{n} and @var{d} are relatively
31834 prime.  Note that fractions where @var{d} is one are automatically converted
31835 to plain integers by all math routines; fractions where @var{d} is negative
31836 are normalized by negating the numerator and denominator.
31838 Floating-point numbers are stored in the form, @samp{(float @var{mant}
31839 @var{exp})}, where @var{mant} (the ``mantissa'') is an integer less than
31840 @samp{10^@var{p}} in absolute value (@var{p} represents the current
31841 precision), and @var{exp} (the ``exponent'') is a fixnum.  The value of
31842 the float is @samp{@var{mant} * 10^@var{exp}}.  For example, the number
31843 @i{-3.14} is stored as @samp{(float -314 -2) = -314*10^-2}.  Other constraints
31844 are that the number 0.0 is always stored as @samp{(float 0 0)}, and,
31845 except for the 0.0 case, the rightmost base-10 digit of @var{mant} is
31846 always nonzero.  (If the rightmost digit is zero, the number is
31847 rearranged by dividing @var{mant} by ten and incrementing @var{exp}.)@refill
31849 Rectangular complex numbers are stored in the form @samp{(cplx @var{re}
31850 @var{im})}, where @var{re} and @var{im} are each real numbers, either
31851 integers, fractions, or floats.  The value is @samp{@var{re} + @var{im}i}.
31852 The @var{im} part is nonzero; complex numbers with zero imaginary
31853 components are converted to real numbers automatically.@refill
31855 Polar complex numbers are stored in the form @samp{(polar @var{r}
31856 @var{theta})}, where @var{r} is a positive real value and @var{theta}
31857 is a real value or HMS form representing an angle.  This angle is
31858 usually normalized to lie in the interval @samp{(-180 ..@: 180)} degrees,
31859 or @samp{(-pi ..@: pi)} radians, according to the current angular mode.
31860 If the angle is 0 the value is converted to a real number automatically.
31861 (If the angle is 180 degrees, the value is usually also converted to a
31862 negative real number.)@refill
31864 Hours-minutes-seconds forms are stored as @samp{(hms @var{h} @var{m}
31865 @var{s})}, where @var{h} is an integer or an integer-valued float (i.e.,
31866 a float with @samp{@var{exp} >= 0}), @var{m} is an integer or integer-valued
31867 float in the range @w{@samp{[0 ..@: 60)}}, and @var{s} is any real number
31868 in the range @samp{[0 ..@: 60)}.@refill
31870 Date forms are stored as @samp{(date @var{n})}, where @var{n} is
31871 a real number that counts days since midnight on the morning of
31872 January 1, 1 AD.  If @var{n} is an integer, this is a pure date
31873 form.  If @var{n} is a fraction or float, this is a date/time form.
31875 Modulo forms are stored as @samp{(mod @var{n} @var{m})}, where @var{m} is a
31876 positive real number or HMS form, and @var{n} is a real number or HMS
31877 form in the range @samp{[0 ..@: @var{m})}.
31879 Error forms are stored as @samp{(sdev @var{x} @var{sigma})}, where @var{x}
31880 is the mean value and @var{sigma} is the standard deviation.  Each
31881 component is either a number, an HMS form, or a symbolic object
31882 (a variable or function call).  If @var{sigma} is zero, the value is
31883 converted to a plain real number.  If @var{sigma} is negative or
31884 complex, it is automatically normalized to be a positive real.
31886 Interval forms are stored as @samp{(intv @var{mask} @var{lo} @var{hi})},
31887 where @var{mask} is one of the integers 0, 1, 2, or 3, and @var{lo} and
31888 @var{hi} are real numbers, HMS forms, or symbolic objects.  The @var{mask}
31889 is a binary integer where 1 represents the fact that the interval is
31890 closed on the high end, and 2 represents the fact that it is closed on
31891 the low end.  (Thus 3 represents a fully closed interval.)  The interval
31892 @w{@samp{(intv 3 @var{x} @var{x})}} is converted to the plain number @var{x};
31893 intervals @samp{(intv @var{mask} @var{x} @var{x})} for any other @var{mask}
31894 represent empty intervals.  If @var{hi} is less than @var{lo}, the interval
31895 is converted to a standard empty interval by replacing @var{hi} with @var{lo}.
31897 Vectors are stored as @samp{(vec @var{v1} @var{v2} @dots{})}, where @var{v1}
31898 is the first element of the vector, @var{v2} is the second, and so on.
31899 An empty vector is stored as @samp{(vec)}.  A matrix is simply a vector
31900 where all @var{v}'s are themselves vectors of equal lengths.  Note that
31901 Calc vectors are unrelated to the Emacs Lisp ``vector'' type, which is
31902 generally unused by Calc data structures.
31904 Variables are stored as @samp{(var @var{name} @var{sym})}, where
31905 @var{name} is a Lisp symbol whose print name is used as the visible name
31906 of the variable, and @var{sym} is a Lisp symbol in which the variable's
31907 value is actually stored.  Thus, @samp{(var pi var-pi)} represents the
31908 special constant @samp{pi}.  Almost always, the form is @samp{(var
31909 @var{v} var-@var{v})}.  If the variable name was entered with @code{#}
31910 signs (which are converted to hyphens internally), the form is
31911 @samp{(var @var{u} @var{v})}, where @var{u} is a symbol whose name
31912 contains @code{#} characters, and @var{v} is a symbol that contains
31913 @code{-} characters instead.  The value of a variable is the Calc
31914 object stored in its @var{sym} symbol's value cell.  If the symbol's
31915 value cell is void or if it contains @code{nil}, the variable has no
31916 value.  Special constants have the form @samp{(special-const
31917 @var{value})} stored in their value cell, where @var{value} is a formula
31918 which is evaluated when the constant's value is requested.  Variables
31919 which represent units are not stored in any special way; they are units
31920 only because their names appear in the units table.  If the value
31921 cell contains a string, it is parsed to get the variable's value when
31922 the variable is used.@refill
31924 A Lisp list with any other symbol as the first element is a function call.
31925 The symbols @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, @code{^},
31926 and @code{|} represent special binary operators; these lists are always
31927 of the form @samp{(@var{op} @var{lhs} @var{rhs})} where @var{lhs} is the
31928 sub-formula on the lefthand side and @var{rhs} is the sub-formula on the
31929 right.  The symbol @code{neg} represents unary negation; this list is always
31930 of the form @samp{(neg @var{arg})}.  Any other symbol @var{func} represents a
31931 function that would be displayed in function-call notation; the symbol
31932 @var{func} is in general always of the form @samp{calcFunc-@var{name}}.
31933 The function cell of the symbol @var{func} should contain a Lisp function
31934 for evaluating a call to @var{func}.  This function is passed the remaining
31935 elements of the list (themselves already evaluated) as arguments; such
31936 functions should return @code{nil} or call @code{reject-arg} to signify
31937 that they should be left in symbolic form, or they should return a Calc
31938 object which represents their value, or a list of such objects if they
31939 wish to return multiple values.  (The latter case is allowed only for
31940 functions which are the outer-level call in an expression whose value is
31941 about to be pushed on the stack; this feature is considered obsolete
31942 and is not used by any built-in Calc functions.)@refill
31944 @node Interactive Lisp Functions, Stack Lisp Functions, Data Type Formats, Internals
31945 @subsubsection Interactive Functions
31947 @noindent
31948 The functions described here are used in implementing interactive Calc
31949 commands.  Note that this list is not exhaustive!  If there is an
31950 existing command that behaves similarly to the one you want to define,
31951 you may find helpful tricks by checking the source code for that command.
31953 @defun calc-set-command-flag flag
31954 Set the command flag @var{flag}.  This is generally a Lisp symbol, but
31955 may in fact be anything.  The effect is to add @var{flag} to the list
31956 stored in the variable @code{calc-command-flags}, unless it is already
31957 there.  @xref{Defining Simple Commands}.
31958 @end defun
31960 @defun calc-clear-command-flag flag
31961 If @var{flag} appears among the list of currently-set command flags,
31962 remove it from that list.
31963 @end defun
31965 @defun calc-record-undo rec
31966 Add the ``undo record'' @var{rec} to the list of steps to take if the
31967 current operation should need to be undone.  Stack push and pop functions
31968 automatically call @code{calc-record-undo}, so the kinds of undo records
31969 you might need to create take the form @samp{(set @var{sym} @var{value})},
31970 which says that the Lisp variable @var{sym} was changed and had previously
31971 contained @var{value}; @samp{(store @var{var} @var{value})} which says that
31972 the Calc variable @var{var} (a string which is the name of the symbol that
31973 contains the variable's value) was stored and its previous value was
31974 @var{value} (either a Calc data object, or @code{nil} if the variable was
31975 previously void); or @samp{(eval @var{undo} @var{redo} @var{args} @dots{})},
31976 which means that to undo requires calling the function @samp{(@var{undo}
31977 @var{args} @dots{})} and, if the undo is later redone, calling
31978 @samp{(@var{redo} @var{args} @dots{})}.@refill
31979 @end defun
31981 @defun calc-record-why msg args
31982 Record the error or warning message @var{msg}, which is normally a string.
31983 This message will be replayed if the user types @kbd{w} (@code{calc-why});
31984 if the message string begins with a @samp{*}, it is considered important
31985 enough to display even if the user doesn't type @kbd{w}.  If one or more
31986 @var{args} are present, the displayed message will be of the form,
31987 @samp{@var{msg}: @var{arg1}, @var{arg2}, @dots{}}, where the arguments are
31988 formatted on the assumption that they are either strings or Calc objects of
31989 some sort.  If @var{msg} is a symbol, it is the name of a Calc predicate
31990 (such as @code{integerp} or @code{numvecp}) which the arguments did not
31991 satisfy; it is expanded to a suitable string such as ``Expected an
31992 integer.''  The @code{reject-arg} function calls @code{calc-record-why}
31993 automatically; @pxref{Predicates}.@refill
31994 @end defun
31996 @defun calc-is-inverse
31997 This predicate returns true if the current command is inverse,
31998 i.e., if the Inverse (@kbd{I} key) flag was set.
31999 @end defun
32001 @defun calc-is-hyperbolic
32002 This predicate is the analogous function for the @kbd{H} key.
32003 @end defun
32005 @node Stack Lisp Functions, Predicates, Interactive Lisp Functions, Internals
32006 @subsubsection Stack-Oriented Functions
32008 @noindent
32009 The functions described here perform various operations on the Calc
32010 stack and trail.  They are to be used in interactive Calc commands.
32012 @defun calc-push-list vals n
32013 Push the Calc objects in list @var{vals} onto the stack at stack level
32014 @var{n}.  If @var{n} is omitted it defaults to 1, so that the elements
32015 are pushed at the top of the stack.  If @var{n} is greater than 1, the
32016 elements will be inserted into the stack so that the last element will
32017 end up at level @var{n}, the next-to-last at level @var{n}+1, etc.
32018 The elements of @var{vals} are assumed to be valid Calc objects, and
32019 are not evaluated, rounded, or renormalized in any way.  If @var{vals}
32020 is an empty list, nothing happens.@refill
32022 The stack elements are pushed without any sub-formula selections.
32023 You can give an optional third argument to this function, which must
32024 be a list the same size as @var{vals} of selections.  Each selection
32025 must be @code{eq} to some sub-formula of the corresponding formula
32026 in @var{vals}, or @code{nil} if that formula should have no selection.
32027 @end defun
32029 @defun calc-top-list n m
32030 Return a list of the @var{n} objects starting at level @var{m} of the
32031 stack.  If @var{m} is omitted it defaults to 1, so that the elements are
32032 taken from the top of the stack.  If @var{n} is omitted, it also
32033 defaults to 1, so that the top stack element (in the form of a
32034 one-element list) is returned.  If @var{m} is greater than 1, the
32035 @var{m}th stack element will be at the end of the list, the @var{m}+1st
32036 element will be next-to-last, etc.  If @var{n} or @var{m} are out of
32037 range, the command is aborted with a suitable error message.  If @var{n}
32038 is zero, the function returns an empty list.  The stack elements are not
32039 evaluated, rounded, or renormalized.@refill
32041 If any stack elements contain selections, and selections have not
32042 been disabled by the @kbd{j e} (@code{calc-enable-selections}) command,
32043 this function returns the selected portions rather than the entire
32044 stack elements.  It can be given a third ``selection-mode'' argument
32045 which selects other behaviors.  If it is the symbol @code{t}, then
32046 a selection in any of the requested stack elements produces an
32047 ``illegal operation on selections'' error.  If it is the symbol @code{full},
32048 the whole stack entry is always returned regardless of selections.
32049 If it is the symbol @code{sel}, the selected portion is always returned,
32050 or @code{nil} if there is no selection.  (This mode ignores the @kbd{j e}
32051 command.)  If the symbol is @code{entry}, the complete stack entry in
32052 list form is returned; the first element of this list will be the whole
32053 formula, and the third element will be the selection (or @code{nil}).
32054 @end defun
32056 @defun calc-pop-stack n m
32057 Remove the specified elements from the stack.  The parameters @var{n}
32058 and @var{m} are defined the same as for @code{calc-top-list}.  The return
32059 value of @code{calc-pop-stack} is uninteresting.
32061 If there are any selected sub-formulas among the popped elements, and
32062 @kbd{j e} has not been used to disable selections, this produces an
32063 error without changing the stack.  If you supply an optional third
32064 argument of @code{t}, the stack elements are popped even if they
32065 contain selections.
32066 @end defun
32068 @defun calc-record-list vals tag
32069 This function records one or more results in the trail.  The @var{vals}
32070 are a list of strings or Calc objects.  The @var{tag} is the four-character
32071 tag string to identify the values.  If @var{tag} is omitted, a blank tag
32072 will be used.
32073 @end defun
32075 @defun calc-normalize n
32076 This function takes a Calc object and ``normalizes'' it.  At the very
32077 least this involves re-rounding floating-point values according to the
32078 current precision and other similar jobs.  Also, unless the user has
32079 selected no-simplify mode (@pxref{Simplification Modes}), this involves
32080 actually evaluating a formula object by executing the function calls
32081 it contains, and possibly also doing algebraic simplification, etc.
32082 @end defun
32084 @defun calc-top-list-n n m
32085 This function is identical to @code{calc-top-list}, except that it calls
32086 @code{calc-normalize} on the values that it takes from the stack.  They
32087 are also passed through @code{check-complete}, so that incomplete
32088 objects will be rejected with an error message.  All computational
32089 commands should use this in preference to @code{calc-top-list}; the only
32090 standard Calc commands that operate on the stack without normalizing
32091 are stack management commands like @code{calc-enter} and @code{calc-roll-up}.
32092 This function accepts the same optional selection-mode argument as
32093 @code{calc-top-list}.
32094 @end defun
32096 @defun calc-top-n m
32097 This function is a convenient form of @code{calc-top-list-n} in which only
32098 a single element of the stack is taken and returned, rather than a list
32099 of elements.  This also accepts an optional selection-mode argument.
32100 @end defun
32102 @defun calc-enter-result n tag vals
32103 This function is a convenient interface to most of the above functions.
32104 The @var{vals} argument should be either a single Calc object, or a list
32105 of Calc objects; the object or objects are normalized, and the top @var{n}
32106 stack entries are replaced by the normalized objects.  If @var{tag} is
32107 non-@code{nil}, the normalized objects are also recorded in the trail.
32108 A typical stack-based computational command would take the form,
32110 @smallexample
32111 (calc-enter-result @var{n} @var{tag} (cons 'calcFunc-@var{func}
32112                                (calc-top-list-n @var{n})))
32113 @end smallexample
32115 If any of the @var{n} stack elements replaced contain sub-formula
32116 selections, and selections have not been disabled by @kbd{j e},
32117 this function takes one of two courses of action.  If @var{n} is
32118 equal to the number of elements in @var{vals}, then each element of
32119 @var{vals} is spliced into the corresponding selection; this is what
32120 happens when you use the @key{TAB} key, or when you use a unary
32121 arithmetic operation like @code{sqrt}.  If @var{vals} has only one
32122 element but @var{n} is greater than one, there must be only one
32123 selection among the top @var{n} stack elements; the element from
32124 @var{vals} is spliced into that selection.  This is what happens when
32125 you use a binary arithmetic operation like @kbd{+}.  Any other
32126 combination of @var{n} and @var{vals} is an error when selections
32127 are present.
32128 @end defun
32130 @defun calc-unary-op tag func arg
32131 This function implements a unary operator that allows a numeric prefix
32132 argument to apply the operator over many stack entries.  If the prefix
32133 argument @var{arg} is @code{nil}, this uses @code{calc-enter-result}
32134 as outlined above.  Otherwise, it maps the function over several stack
32135 elements; @pxref{Prefix Arguments}.  For example,@refill
32137 @smallexample
32138 (defun calc-zeta (arg)
32139   (interactive "P")
32140   (calc-unary-op "zeta" 'calcFunc-zeta arg))
32141 @end smallexample
32142 @end defun
32144 @defun calc-binary-op tag func arg ident unary
32145 This function implements a binary operator, analogously to
32146 @code{calc-unary-op}.  The optional @var{ident} and @var{unary}
32147 arguments specify the behavior when the prefix argument is zero or
32148 one, respectively.  If the prefix is zero, the value @var{ident}
32149 is pushed onto the stack, if specified, otherwise an error message
32150 is displayed.  If the prefix is one, the unary function @var{unary}
32151 is applied to the top stack element, or, if @var{unary} is not
32152 specified, nothing happens.  When the argument is two or more,
32153 the binary function @var{func} is reduced across the top @var{arg}
32154 stack elements; when the argument is negative, the function is
32155 mapped between the next-to-top @i{-@var{arg}} stack elements and the
32156 top element.@refill
32157 @end defun
32159 @defun calc-stack-size
32160 Return the number of elements on the stack as an integer.  This count
32161 does not include elements that have been temporarily hidden by stack
32162 truncation; @pxref{Truncating the Stack}.
32163 @end defun
32165 @defun calc-cursor-stack-index n
32166 Move the point to the @var{n}th stack entry.  If @var{n} is zero, this
32167 will be the @samp{.} line.  If @var{n} is from 1 to the current stack size,
32168 this will be the beginning of the first line of that stack entry's display.
32169 If line numbers are enabled, this will move to the first character of the
32170 line number, not the stack entry itself.@refill
32171 @end defun
32173 @defun calc-substack-height n
32174 Return the number of lines between the beginning of the @var{n}th stack
32175 entry and the bottom of the buffer.  If @var{n} is zero, this
32176 will be one (assuming no stack truncation).  If all stack entries are
32177 one line long (i.e., no matrices are displayed), the return value will
32178 be equal @var{n}+1 as long as @var{n} is in range.  (Note that in Big
32179 mode, the return value includes the blank lines that separate stack
32180 entries.)@refill
32181 @end defun
32183 @defun calc-refresh
32184 Erase the @code{*Calculator*} buffer and reformat its contents from memory.
32185 This must be called after changing any parameter, such as the current
32186 display radix, which might change the appearance of existing stack
32187 entries.  (During a keyboard macro invoked by the @kbd{X} key, refreshing
32188 is suppressed, but a flag is set so that the entire stack will be refreshed
32189 rather than just the top few elements when the macro finishes.)@refill
32190 @end defun
32192 @node Predicates, Computational Lisp Functions, Stack Lisp Functions, Internals
32193 @subsubsection Predicates
32195 @noindent
32196 The functions described here are predicates, that is, they return a
32197 true/false value where @code{nil} means false and anything else means
32198 true.  These predicates are expanded by @code{defmath}, for example,
32199 from @code{zerop} to @code{math-zerop}.  In many cases they correspond
32200 to native Lisp functions by the same name, but are extended to cover
32201 the full range of Calc data types.
32203 @defun zerop x
32204 Returns true if @var{x} is numerically zero, in any of the Calc data
32205 types.  (Note that for some types, such as error forms and intervals,
32206 it never makes sense to return true.)  In @code{defmath}, the expression
32207 @samp{(= x 0)} will automatically be converted to @samp{(math-zerop x)},
32208 and @samp{(/= x 0)} will be converted to @samp{(not (math-zerop x))}.
32209 @end defun
32211 @defun negp x
32212 Returns true if @var{x} is negative.  This accepts negative real numbers
32213 of various types, negative HMS and date forms, and intervals in which
32214 all included values are negative.  In @code{defmath}, the expression
32215 @samp{(< x 0)} will automatically be converted to @samp{(math-negp x)},
32216 and @samp{(>= x 0)} will be converted to @samp{(not (math-negp x))}.
32217 @end defun
32219 @defun posp x
32220 Returns true if @var{x} is positive (and non-zero).  For complex
32221 numbers, none of these three predicates will return true.
32222 @end defun
32224 @defun looks-negp x
32225 Returns true if @var{x} is ``negative-looking.''  This returns true if
32226 @var{x} is a negative number, or a formula with a leading minus sign
32227 such as @samp{-a/b}.  In other words, this is an object which can be
32228 made simpler by calling @code{(- @var{x})}.
32229 @end defun
32231 @defun integerp x
32232 Returns true if @var{x} is an integer of any size.
32233 @end defun
32235 @defun fixnump x
32236 Returns true if @var{x} is a native Lisp integer.
32237 @end defun
32239 @defun natnump x
32240 Returns true if @var{x} is a nonnegative integer of any size.
32241 @end defun
32243 @defun fixnatnump x
32244 Returns true if @var{x} is a nonnegative Lisp integer.
32245 @end defun
32247 @defun num-integerp x
32248 Returns true if @var{x} is numerically an integer, i.e., either a
32249 true integer or a float with no significant digits to the right of
32250 the decimal point.
32251 @end defun
32253 @defun messy-integerp x
32254 Returns true if @var{x} is numerically, but not literally, an integer.
32255 A value is @code{num-integerp} if it is @code{integerp} or
32256 @code{messy-integerp} (but it is never both at once).
32257 @end defun
32259 @defun num-natnump x
32260 Returns true if @var{x} is numerically a nonnegative integer.
32261 @end defun
32263 @defun evenp x
32264 Returns true if @var{x} is an even integer.
32265 @end defun
32267 @defun looks-evenp x
32268 Returns true if @var{x} is an even integer, or a formula with a leading
32269 multiplicative coefficient which is an even integer.
32270 @end defun
32272 @defun oddp x
32273 Returns true if @var{x} is an odd integer.
32274 @end defun
32276 @defun ratp x
32277 Returns true if @var{x} is a rational number, i.e., an integer or a
32278 fraction.
32279 @end defun
32281 @defun realp x
32282 Returns true if @var{x} is a real number, i.e., an integer, fraction,
32283 or floating-point number.
32284 @end defun
32286 @defun anglep x
32287 Returns true if @var{x} is a real number or HMS form.
32288 @end defun
32290 @defun floatp x
32291 Returns true if @var{x} is a float, or a complex number, error form,
32292 interval, date form, or modulo form in which at least one component
32293 is a float.
32294 @end defun
32296 @defun complexp x
32297 Returns true if @var{x} is a rectangular or polar complex number
32298 (but not a real number).
32299 @end defun
32301 @defun rect-complexp x
32302 Returns true if @var{x} is a rectangular complex number.
32303 @end defun
32305 @defun polar-complexp x
32306 Returns true if @var{x} is a polar complex number.
32307 @end defun
32309 @defun numberp x
32310 Returns true if @var{x} is a real number or a complex number.
32311 @end defun
32313 @defun scalarp x
32314 Returns true if @var{x} is a real or complex number or an HMS form.
32315 @end defun
32317 @defun vectorp x
32318 Returns true if @var{x} is a vector (this simply checks if its argument
32319 is a list whose first element is the symbol @code{vec}).
32320 @end defun
32322 @defun numvecp x
32323 Returns true if @var{x} is a number or vector.
32324 @end defun
32326 @defun matrixp x
32327 Returns true if @var{x} is a matrix, i.e., a vector of one or more vectors,
32328 all of the same size.
32329 @end defun
32331 @defun square-matrixp x
32332 Returns true if @var{x} is a square matrix.
32333 @end defun
32335 @defun objectp x
32336 Returns true if @var{x} is any numeric Calc object, including real and
32337 complex numbers, HMS forms, date forms, error forms, intervals, and
32338 modulo forms.  (Note that error forms and intervals may include formulas
32339 as their components; see @code{constp} below.)
32340 @end defun
32342 @defun objvecp x
32343 Returns true if @var{x} is an object or a vector.  This also accepts
32344 incomplete objects, but it rejects variables and formulas (except as
32345 mentioned above for @code{objectp}).
32346 @end defun
32348 @defun primp x
32349 Returns true if @var{x} is a ``primitive'' or ``atomic'' Calc object,
32350 i.e., one whose components cannot be regarded as sub-formulas.  This
32351 includes variables, and all @code{objectp} types except error forms
32352 and intervals.
32353 @end defun
32355 @defun constp x
32356 Returns true if @var{x} is constant, i.e., a real or complex number,
32357 HMS form, date form, or error form, interval, or vector all of whose
32358 components are @code{constp}.
32359 @end defun
32361 @defun lessp x y
32362 Returns true if @var{x} is numerically less than @var{y}.  Returns false
32363 if @var{x} is greater than or equal to @var{y}, or if the order is
32364 undefined or cannot be determined.  Generally speaking, this works
32365 by checking whether @samp{@var{x} - @var{y}} is @code{negp}.  In
32366 @code{defmath}, the expression @samp{(< x y)} will automatically be
32367 converted to @samp{(lessp x y)}; expressions involving @code{>}, @code{<=},
32368 and @code{>=} are similarly converted in terms of @code{lessp}.@refill
32369 @end defun
32371 @defun beforep x y
32372 Returns true if @var{x} comes before @var{y} in a canonical ordering
32373 of Calc objects.  If @var{x} and @var{y} are both real numbers, this
32374 will be the same as @code{lessp}.  But whereas @code{lessp} considers
32375 other types of objects to be unordered, @code{beforep} puts any two
32376 objects into a definite, consistent order.  The @code{beforep}
32377 function is used by the @kbd{V S} vector-sorting command, and also
32378 by @kbd{a s} to put the terms of a product into canonical order:
32379 This allows @samp{x y + y x} to be simplified easily to @samp{2 x y}.
32380 @end defun
32382 @defun equal x y
32383 This is the standard Lisp @code{equal} predicate; it returns true if
32384 @var{x} and @var{y} are structurally identical.  This is the usual way
32385 to compare numbers for equality, but note that @code{equal} will treat
32386 0 and 0.0 as different.
32387 @end defun
32389 @defun math-equal x y
32390 Returns true if @var{x} and @var{y} are numerically equal, either because
32391 they are @code{equal}, or because their difference is @code{zerop}.  In
32392 @code{defmath}, the expression @samp{(= x y)} will automatically be
32393 converted to @samp{(math-equal x y)}.
32394 @end defun
32396 @defun equal-int x n
32397 Returns true if @var{x} and @var{n} are numerically equal, where @var{n}
32398 is a fixnum which is not a multiple of 10.  This will automatically be
32399 used by @code{defmath} in place of the more general @code{math-equal}
32400 whenever possible.@refill
32401 @end defun
32403 @defun nearly-equal x y
32404 Returns true if @var{x} and @var{y}, as floating-point numbers, are
32405 equal except possibly in the last decimal place.  For example,
32406 314.159 and 314.166 are considered nearly equal if the current
32407 precision is 6 (since they differ by 7 units), but not if the current
32408 precision is 7 (since they differ by 70 units).  Most functions which
32409 use series expansions use @code{with-extra-prec} to evaluate the
32410 series with 2 extra digits of precision, then use @code{nearly-equal}
32411 to decide when the series has converged; this guards against cumulative
32412 error in the series evaluation without doing extra work which would be
32413 lost when the result is rounded back down to the current precision.
32414 In @code{defmath}, this can be written @samp{(~= @var{x} @var{y})}.
32415 The @var{x} and @var{y} can be numbers of any kind, including complex.
32416 @end defun
32418 @defun nearly-zerop x y
32419 Returns true if @var{x} is nearly zero, compared to @var{y}.  This
32420 checks whether @var{x} plus @var{y} would by be @code{nearly-equal}
32421 to @var{y} itself, to within the current precision, in other words,
32422 if adding @var{x} to @var{y} would have a negligible effect on @var{y}
32423 due to roundoff error.  @var{X} may be a real or complex number, but
32424 @var{y} must be real.
32425 @end defun
32427 @defun is-true x
32428 Return true if the formula @var{x} represents a true value in
32429 Calc, not Lisp, terms.  It tests if @var{x} is a non-zero number
32430 or a provably non-zero formula.
32431 @end defun
32433 @defun reject-arg val pred
32434 Abort the current function evaluation due to unacceptable argument values.
32435 This calls @samp{(calc-record-why @var{pred} @var{val})}, then signals a
32436 Lisp error which @code{normalize} will trap.  The net effect is that the
32437 function call which led here will be left in symbolic form.@refill
32438 @end defun
32440 @defun inexact-value
32441 If Symbolic Mode is enabled, this will signal an error that causes
32442 @code{normalize} to leave the formula in symbolic form, with the message
32443 ``Inexact result.''  (This function has no effect when not in Symbolic Mode.)
32444 Note that if your function calls @samp{(sin 5)} in Symbolic Mode, the
32445 @code{sin} function will call @code{inexact-value}, which will cause your
32446 function to be left unsimplified.  You may instead wish to call
32447 @samp{(normalize (list 'calcFunc-sin 5))}, which in Symbolic Mode will
32448 return the formula @samp{sin(5)} to your function.@refill
32449 @end defun
32451 @defun overflow
32452 This signals an error that will be reported as a floating-point overflow.
32453 @end defun
32455 @defun underflow
32456 This signals a floating-point underflow.
32457 @end defun
32459 @node Computational Lisp Functions, Vector Lisp Functions, Predicates, Internals
32460 @subsubsection Computational Functions
32462 @noindent
32463 The functions described here do the actual computational work of the
32464 Calculator.  In addition to these, note that any function described in
32465 the main body of this manual may be called from Lisp; for example, if
32466 the documentation refers to the @code{calc-sqrt} [@code{sqrt}] command,
32467 this means @code{calc-sqrt} is an interactive stack-based square-root
32468 command and @code{sqrt} (which @code{defmath} expands to @code{calcFunc-sqrt})
32469 is the actual Lisp function for taking square roots.@refill
32471 The functions @code{math-add}, @code{math-sub}, @code{math-mul},
32472 @code{math-div}, @code{math-mod}, and @code{math-neg} are not included
32473 in this list, since @code{defmath} allows you to write native Lisp
32474 @code{+}, @code{-}, @code{*}, @code{/}, @code{%}, and unary @code{-},
32475 respectively, instead.@refill
32477 @defun normalize val
32478 (Full form: @code{math-normalize}.)
32479 Reduce the value @var{val} to standard form.  For example, if @var{val}
32480 is a fixnum, it will be converted to a bignum if it is too large, and
32481 if @var{val} is a bignum it will be normalized by clipping off trailing
32482 (i.e., most-significant) zero digits and converting to a fixnum if it is
32483 small.  All the various data types are similarly converted to their standard
32484 forms.  Variables are left alone, but function calls are actually evaluated
32485 in formulas.  For example, normalizing @samp{(+ 2 (calcFunc-abs -4))} will
32486 return 6.@refill
32488 If a function call fails, because the function is void or has the wrong
32489 number of parameters, or because it returns @code{nil} or calls
32490 @code{reject-arg} or @code{inexact-result}, @code{normalize} returns
32491 the formula still in symbolic form.@refill
32493 If the current Simplification Mode is ``none'' or ``numeric arguments
32494 only,'' @code{normalize} will act appropriately.  However, the more
32495 powerful simplification modes (like algebraic simplification) are
32496 not handled by @code{normalize}.  They are handled by @code{calc-normalize},
32497 which calls @code{normalize} and possibly some other routines, such
32498 as @code{simplify} or @code{simplify-units}.  Programs generally will
32499 never call @code{calc-normalize} except when popping or pushing values
32500 on the stack.@refill
32501 @end defun
32503 @defun evaluate-expr expr
32504 Replace all variables in @var{expr} that have values with their values,
32505 then use @code{normalize} to simplify the result.  This is what happens
32506 when you press the @kbd{=} key interactively.@refill
32507 @end defun
32509 @defmac with-extra-prec n body
32510 Evaluate the Lisp forms in @var{body} with precision increased by @var{n}
32511 digits.  This is a macro which expands to
32513 @smallexample
32514 (math-normalize
32515   (let ((calc-internal-prec (+ calc-internal-prec @var{n})))
32516     @var{body}))
32517 @end smallexample
32519 The surrounding call to @code{math-normalize} causes a floating-point
32520 result to be rounded down to the original precision afterwards.  This
32521 is important because some arithmetic operations assume a number's
32522 mantissa contains no more digits than the current precision allows.
32523 @end defmac
32525 @defun make-frac n d
32526 Build a fraction @samp{@var{n}:@var{d}}.  This is equivalent to calling
32527 @samp{(normalize (list 'frac @var{n} @var{d}))}, but more efficient.
32528 @end defun
32530 @defun make-float mant exp
32531 Build a floating-point value out of @var{mant} and @var{exp}, both
32532 of which are arbitrary integers.  This function will return a
32533 properly normalized float value, or signal an overflow or underflow
32534 if @var{exp} is out of range.
32535 @end defun
32537 @defun make-sdev x sigma
32538 Build an error form out of @var{x} and the absolute value of @var{sigma}.
32539 If @var{sigma} is zero, the result is the number @var{x} directly.
32540 If @var{sigma} is negative or complex, its absolute value is used.
32541 If @var{x} or @var{sigma} is not a valid type of object for use in
32542 error forms, this calls @code{reject-arg}.
32543 @end defun
32545 @defun make-intv mask lo hi
32546 Build an interval form out of @var{mask} (which is assumed to be an
32547 integer from 0 to 3), and the limits @var{lo} and @var{hi}.  If
32548 @var{lo} is greater than @var{hi}, an empty interval form is returned.
32549 This calls @code{reject-arg} if @var{lo} or @var{hi} is unsuitable.
32550 @end defun
32552 @defun sort-intv mask lo hi
32553 Build an interval form, similar to @code{make-intv}, except that if
32554 @var{lo} is less than @var{hi} they are simply exchanged, and the
32555 bits of @var{mask} are swapped accordingly.
32556 @end defun
32558 @defun make-mod n m
32559 Build a modulo form out of @var{n} and the modulus @var{m}.  Since modulo
32560 forms do not allow formulas as their components, if @var{n} or @var{m}
32561 is not a real number or HMS form the result will be a formula which
32562 is a call to @code{makemod}, the algebraic version of this function.
32563 @end defun
32565 @defun float x
32566 Convert @var{x} to floating-point form.  Integers and fractions are
32567 converted to numerically equivalent floats; components of complex
32568 numbers, vectors, HMS forms, date forms, error forms, intervals, and
32569 modulo forms are recursively floated.  If the argument is a variable
32570 or formula, this calls @code{reject-arg}.
32571 @end defun
32573 @defun compare x y
32574 Compare the numbers @var{x} and @var{y}, and return @i{-1} if
32575 @samp{(lessp @var{x} @var{y})}, 1 if @samp{(lessp @var{y} @var{x})},
32576 0 if @samp{(math-equal @var{x} @var{y})}, or 2 if the order is
32577 undefined or cannot be determined.@refill
32578 @end defun
32580 @defun numdigs n
32581 Return the number of digits of integer @var{n}, effectively
32582 @samp{ceil(log10(@var{n}))}, but much more efficient.  Zero is
32583 considered to have zero digits.
32584 @end defun
32586 @defun scale-int x n
32587 Shift integer @var{x} left @var{n} decimal digits, or right @i{-@var{n}}
32588 digits with truncation toward zero.
32589 @end defun
32591 @defun scale-rounding x n
32592 Like @code{scale-int}, except that a right shift rounds to the nearest
32593 integer rather than truncating.
32594 @end defun
32596 @defun fixnum n
32597 Return the integer @var{n} as a fixnum, i.e., a native Lisp integer.
32598 If @var{n} is outside the permissible range for Lisp integers (usually
32599 24 binary bits) the result is undefined.
32600 @end defun
32602 @defun sqr x
32603 Compute the square of @var{x}; short for @samp{(* @var{x} @var{x})}.
32604 @end defun
32606 @defun quotient x y
32607 Divide integer @var{x} by integer @var{y}; return an integer quotient
32608 and discard the remainder.  If @var{x} or @var{y} is negative, the
32609 direction of rounding is undefined.
32610 @end defun
32612 @defun idiv x y
32613 Perform an integer division; if @var{x} and @var{y} are both nonnegative
32614 integers, this uses the @code{quotient} function, otherwise it computes
32615 @samp{floor(@var{x}/@var{y})}.  Thus the result is well-defined but
32616 slower than for @code{quotient}.
32617 @end defun
32619 @defun imod x y
32620 Divide integer @var{x} by integer @var{y}; return the integer remainder
32621 and discard the quotient.  Like @code{quotient}, this works only for
32622 integer arguments and is not well-defined for negative arguments.
32623 For a more well-defined result, use @samp{(% @var{x} @var{y})}.
32624 @end defun
32626 @defun idivmod x y
32627 Divide integer @var{x} by integer @var{y}; return a cons cell whose
32628 @code{car} is @samp{(quotient @var{x} @var{y})} and whose @code{cdr}
32629 is @samp{(imod @var{x} @var{y})}.@refill
32630 @end defun
32632 @defun pow x y
32633 Compute @var{x} to the power @var{y}.  In @code{defmath} code, this can
32634 also be written @samp{(^ @var{x} @var{y})} or
32635 @w{@samp{(expt @var{x} @var{y})}}.@refill
32636 @end defun
32638 @defun abs-approx x
32639 Compute a fast approximation to the absolute value of @var{x}.  For
32640 example, for a rectangular complex number the result is the sum of
32641 the absolute values of the components.
32642 @end defun
32644 @findex two-pi
32645 @findex pi-over-2
32646 @findex pi-over-4
32647 @findex pi-over-180
32648 @findex sqrt-two-pi
32649 @findex sqrt-e
32650 @findex e
32651 @findex ln-2
32652 @findex ln-10
32653 @defun pi
32654 The function @samp{(pi)} computes @samp{pi} to the current precision.
32655 Other related constant-generating functions are @code{two-pi},
32656 @code{pi-over-2}, @code{pi-over-4}, @code{pi-over-180}, @code{sqrt-two-pi},
32657 @code{e}, @code{sqrt-e}, @code{ln-2}, and @code{ln-10}.  Each function
32658 returns a floating-point value in the current precision, and each uses
32659 caching so that all calls after the first are essentially free.@refill
32660 @end defun
32662 @defmac math-defcache @var{func} @var{initial} @var{form}
32663 This macro, usually used as a top-level call like @code{defun} or
32664 @code{defvar}, defines a new cached constant analogous to @code{pi}, etc.
32665 It defines a function @code{func} which returns the requested value;
32666 if @var{initial} is non-@code{nil} it must be a @samp{(float @dots{})}
32667 form which serves as an initial value for the cache.  If @var{func}
32668 is called when the cache is empty or does not have enough digits to
32669 satisfy the current precision, the Lisp expression @var{form} is evaluated
32670 with the current precision increased by four, and the result minus its
32671 two least significant digits is stored in the cache.  For example,
32672 calling @samp{(pi)} with a precision of 30 computes @samp{pi} to 34
32673 digits, rounds it down to 32 digits for future use, then rounds it
32674 again to 30 digits for use in the present request.@refill
32675 @end defmac
32677 @findex half-circle
32678 @findex quarter-circle
32679 @defun full-circle symb
32680 If the current angular mode is Degrees or HMS, this function returns the
32681 integer 360.  In Radians mode, this function returns either the
32682 corresponding value in radians to the current precision, or the formula
32683 @samp{2*pi}, depending on the Symbolic Mode.  There are also similar
32684 function @code{half-circle} and @code{quarter-circle}.
32685 @end defun
32687 @defun power-of-2 n
32688 Compute two to the integer power @var{n}, as a (potentially very large)
32689 integer.  Powers of two are cached, so only the first call for a
32690 particular @var{n} is expensive.
32691 @end defun
32693 @defun integer-log2 n
32694 Compute the base-2 logarithm of @var{n}, which must be an integer which
32695 is a power of two.  If @var{n} is not a power of two, this function will
32696 return @code{nil}.
32697 @end defun
32699 @defun div-mod a b m
32700 Divide @var{a} by @var{b}, modulo @var{m}.  This returns @code{nil} if
32701 there is no solution, or if any of the arguments are not integers.@refill
32702 @end defun
32704 @defun pow-mod a b m
32705 Compute @var{a} to the power @var{b}, modulo @var{m}.  If @var{a},
32706 @var{b}, and @var{m} are integers, this uses an especially efficient
32707 algorithm.  Otherwise, it simply computes @samp{(% (^ a b) m)}.
32708 @end defun
32710 @defun isqrt n
32711 Compute the integer square root of @var{n}.  This is the square root
32712 of @var{n} rounded down toward zero, i.e., @samp{floor(sqrt(@var{n}))}.
32713 If @var{n} is itself an integer, the computation is especially efficient.
32714 @end defun
32716 @defun to-hms a ang
32717 Convert the argument @var{a} into an HMS form.  If @var{ang} is specified,
32718 it is the angular mode in which to interpret @var{a}, either @code{deg}
32719 or @code{rad}.  Otherwise, the current angular mode is used.  If @var{a}
32720 is already an HMS form it is returned as-is.
32721 @end defun
32723 @defun from-hms a ang
32724 Convert the HMS form @var{a} into a real number.  If @var{ang} is specified,
32725 it is the angular mode in which to express the result, otherwise the
32726 current angular mode is used.  If @var{a} is already a real number, it
32727 is returned as-is.
32728 @end defun
32730 @defun to-radians a
32731 Convert the number or HMS form @var{a} to radians from the current
32732 angular mode.
32733 @end defun
32735 @defun from-radians a
32736 Convert the number @var{a} from radians to the current angular mode.
32737 If @var{a} is a formula, this returns the formula @samp{deg(@var{a})}.
32738 @end defun
32740 @defun to-radians-2 a
32741 Like @code{to-radians}, except that in Symbolic Mode a degrees to
32742 radians conversion yields a formula like @samp{@var{a}*pi/180}.
32743 @end defun
32745 @defun from-radians-2 a
32746 Like @code{from-radians}, except that in Symbolic Mode a radians to
32747 degrees conversion yields a formula like @samp{@var{a}*180/pi}.
32748 @end defun
32750 @defun random-digit
32751 Produce a random base-1000 digit in the range 0 to 999.
32752 @end defun
32754 @defun random-digits n
32755 Produce a random @var{n}-digit integer; this will be an integer
32756 in the interval @samp{[0, 10^@var{n})}.
32757 @end defun
32759 @defun random-float
32760 Produce a random float in the interval @samp{[0, 1)}.
32761 @end defun
32763 @defun prime-test n iters
32764 Determine whether the integer @var{n} is prime.  Return a list which has
32765 one of these forms: @samp{(nil @var{f})} means the number is non-prime
32766 because it was found to be divisible by @var{f}; @samp{(nil)} means it
32767 was found to be non-prime by table look-up (so no factors are known);
32768 @samp{(nil unknown)} means it is definitely non-prime but no factors
32769 are known because @var{n} was large enough that Fermat's probabilistic
32770 test had to be used; @samp{(t)} means the number is definitely prime;
32771 and @samp{(maybe @var{i} @var{p})} means that Fermat's test, after @var{i}
32772 iterations, is @var{p} percent sure that the number is prime.  The
32773 @var{iters} parameter is the number of Fermat iterations to use, in the
32774 case that this is necessary.  If @code{prime-test} returns ``maybe,''
32775 you can call it again with the same @var{n} to get a greater certainty;
32776 @code{prime-test} remembers where it left off.@refill
32777 @end defun
32779 @defun to-simple-fraction f
32780 If @var{f} is a floating-point number which can be represented exactly
32781 as a small rational number. return that number, else return @var{f}.
32782 For example, 0.75 would be converted to 3:4.  This function is very
32783 fast.
32784 @end defun
32786 @defun to-fraction f tol
32787 Find a rational approximation to floating-point number @var{f} to within
32788 a specified tolerance @var{tol}; this corresponds to the algebraic
32789 function @code{frac}, and can be rather slow.
32790 @end defun
32792 @defun quarter-integer n
32793 If @var{n} is an integer or integer-valued float, this function
32794 returns zero.  If @var{n} is a half-integer (i.e., an integer plus
32795 @i{1:2} or 0.5), it returns 2.  If @var{n} is a quarter-integer,
32796 it returns 1 or 3.  If @var{n} is anything else, this function
32797 returns @code{nil}.
32798 @end defun
32800 @node Vector Lisp Functions, Symbolic Lisp Functions, Computational Lisp Functions, Internals
32801 @subsubsection Vector Functions
32803 @noindent
32804 The functions described here perform various operations on vectors and
32805 matrices.
32807 @defun math-concat x y
32808 Do a vector concatenation; this operation is written @samp{@var{x} | @var{y}}
32809 in a symbolic formula.  @xref{Building Vectors}.
32810 @end defun
32812 @defun vec-length v
32813 Return the length of vector @var{v}.  If @var{v} is not a vector, the
32814 result is zero.  If @var{v} is a matrix, this returns the number of
32815 rows in the matrix.
32816 @end defun
32818 @defun mat-dimens m
32819 Determine the dimensions of vector or matrix @var{m}.  If @var{m} is not
32820 a vector, the result is an empty list.  If @var{m} is a plain vector
32821 but not a matrix, the result is a one-element list containing the length
32822 of the vector.  If @var{m} is a matrix with @var{r} rows and @var{c} columns,
32823 the result is the list @samp{(@var{r} @var{c})}.  Higher-order tensors
32824 produce lists of more than two dimensions.  Note that the object
32825 @samp{[[1, 2, 3], [4, 5]]} is a vector of vectors not all the same size,
32826 and is treated by this and other Calc routines as a plain vector of two
32827 elements.@refill
32828 @end defun
32830 @defun dimension-error
32831 Abort the current function with a message of ``Dimension error.''
32832 The Calculator will leave the function being evaluated in symbolic
32833 form; this is really just a special case of @code{reject-arg}.
32834 @end defun
32836 @defun build-vector args
32837 Return a Calc vector with the zero-or-more @var{args} as elements.
32838 For example, @samp{(build-vector 1 2 3)} returns the Calc vector
32839 @samp{[1, 2, 3]}, stored internally as the list @samp{(vec 1 2 3)}.
32840 @end defun
32842 @defun make-vec obj dims
32843 Return a Calc vector or matrix all of whose elements are equal to
32844 @var{obj}.  For example, @samp{(make-vec 27 3 4)} returns a 3x4 matrix
32845 filled with 27's.
32846 @end defun
32848 @defun row-matrix v
32849 If @var{v} is a plain vector, convert it into a row matrix, i.e.,
32850 a matrix whose single row is @var{v}.  If @var{v} is already a matrix,
32851 leave it alone.
32852 @end defun
32854 @defun col-matrix v
32855 If @var{v} is a plain vector, convert it into a column matrix, i.e., a
32856 matrix with each element of @var{v} as a separate row.  If @var{v} is
32857 already a matrix, leave it alone.
32858 @end defun
32860 @defun map-vec f v
32861 Map the Lisp function @var{f} over the Calc vector @var{v}.  For example,
32862 @samp{(map-vec 'math-floor v)} returns a vector of the floored components
32863 of vector @var{v}.
32864 @end defun
32866 @defun map-vec-2 f a b
32867 Map the Lisp function @var{f} over the two vectors @var{a} and @var{b}.
32868 If @var{a} and @var{b} are vectors of equal length, the result is a
32869 vector of the results of calling @samp{(@var{f} @var{ai} @var{bi})}
32870 for each pair of elements @var{ai} and @var{bi}.  If either @var{a} or
32871 @var{b} is a scalar, it is matched with each value of the other vector.
32872 For example, @samp{(map-vec-2 'math-add v 1)} returns the vector @var{v}
32873 with each element increased by one.  Note that using @samp{'+} would not
32874 work here, since @code{defmath} does not expand function names everywhere,
32875 just where they are in the function position of a Lisp expression.@refill
32876 @end defun
32878 @defun reduce-vec f v
32879 Reduce the function @var{f} over the vector @var{v}.  For example, if
32880 @var{v} is @samp{[10, 20, 30, 40]}, this calls @samp{(f (f (f 10 20) 30) 40)}.
32881 If @var{v} is a matrix, this reduces over the rows of @var{v}.
32882 @end defun
32884 @defun reduce-cols f m
32885 Reduce the function @var{f} over the columns of matrix @var{m}.  For
32886 example, if @var{m} is @samp{[[1, 2], [3, 4], [5, 6]]}, the result
32887 is a vector of the two elements @samp{(f (f 1 3) 5)} and @samp{(f (f 2 4) 6)}.
32888 @end defun
32890 @defun mat-row m n
32891 Return the @var{n}th row of matrix @var{m}.  This is equivalent to
32892 @samp{(elt m n)}.  For a slower but safer version, use @code{mrow}.
32893 (@xref{Extracting Elements}.)
32894 @end defun
32896 @defun mat-col m n
32897 Return the @var{n}th column of matrix @var{m}, in the form of a vector.
32898 The arguments are not checked for correctness.
32899 @end defun
32901 @defun mat-less-row m n
32902 Return a copy of matrix @var{m} with its @var{n}th row deleted.  The
32903 number @var{n} must be in range from 1 to the number of rows in @var{m}.
32904 @end defun
32906 @defun mat-less-col m n
32907 Return a copy of matrix @var{m} with its @var{n}th column deleted.
32908 @end defun
32910 @defun transpose m
32911 Return the transpose of matrix @var{m}.
32912 @end defun
32914 @defun flatten-vector v
32915 Flatten nested vector @var{v} into a vector of scalars.  For example,
32916 if @var{v} is @samp{[[1, 2, 3], [4, 5]]} the result is @samp{[1, 2, 3, 4, 5]}.
32917 @end defun
32919 @defun copy-matrix m
32920 If @var{m} is a matrix, return a copy of @var{m}.  This maps
32921 @code{copy-sequence} over the rows of @var{m}; in Lisp terms, each
32922 element of the result matrix will be @code{eq} to the corresponding
32923 element of @var{m}, but none of the @code{cons} cells that make up
32924 the structure of the matrix will be @code{eq}.  If @var{m} is a plain
32925 vector, this is the same as @code{copy-sequence}.@refill
32926 @end defun
32928 @defun swap-rows m r1 r2
32929 Exchange rows @var{r1} and @var{r2} of matrix @var{m} in-place.  In
32930 other words, unlike most of the other functions described here, this
32931 function changes @var{m} itself rather than building up a new result
32932 matrix.  The return value is @var{m}, i.e., @samp{(eq (swap-rows m 1 2) m)}
32933 is true, with the side effect of exchanging the first two rows of
32934 @var{m}.@refill
32935 @end defun
32937 @node Symbolic Lisp Functions, Formatting Lisp Functions, Vector Lisp Functions, Internals
32938 @subsubsection Symbolic Functions
32940 @noindent
32941 The functions described here operate on symbolic formulas in the
32942 Calculator.
32944 @defun calc-prepare-selection num
32945 Prepare a stack entry for selection operations.  If @var{num} is
32946 omitted, the stack entry containing the cursor is used; otherwise,
32947 it is the number of the stack entry to use.  This function stores
32948 useful information about the current stack entry into a set of
32949 variables.  @code{calc-selection-cache-num} contains the number of
32950 the stack entry involved (equal to @var{num} if you specified it);
32951 @code{calc-selection-cache-entry} contains the stack entry as a
32952 list (such as @code{calc-top-list} would return with @code{entry}
32953 as the selection mode); and @code{calc-selection-cache-comp} contains
32954 a special ``tagged'' composition (@pxref{Formatting Lisp Functions})
32955 which allows Calc to relate cursor positions in the buffer with
32956 their corresponding sub-formulas.
32958 A slight complication arises in the selection mechanism because
32959 formulas may contain small integers.  For example, in the vector
32960 @samp{[1, 2, 1]} the first and last elements are @code{eq} to each
32961 other; selections are recorded as the actual Lisp object that
32962 appears somewhere in the tree of the whole formula, but storing
32963 @code{1} would falsely select both @code{1}'s in the vector.  So
32964 @code{calc-prepare-selection} also checks the stack entry and
32965 replaces any plain integers with ``complex number'' lists of the form
32966 @samp{(cplx @var{n} 0)}.  This list will be displayed the same as a
32967 plain @var{n} and the change will be completely invisible to the
32968 user, but it will guarantee that no two sub-formulas of the stack
32969 entry will be @code{eq} to each other.  Next time the stack entry
32970 is involved in a computation, @code{calc-normalize} will replace
32971 these lists with plain numbers again, again invisibly to the user.
32972 @end defun
32974 @defun calc-encase-atoms x
32975 This modifies the formula @var{x} to ensure that each part of the
32976 formula is a unique atom, using the @samp{(cplx @var{n} 0)} trick
32977 described above.  This function may use @code{setcar} to modify
32978 the formula in-place.
32979 @end defun
32981 @defun calc-find-selected-part
32982 Find the smallest sub-formula of the current formula that contains
32983 the cursor.  This assumes @code{calc-prepare-selection} has been
32984 called already.  If the cursor is not actually on any part of the
32985 formula, this returns @code{nil}.
32986 @end defun
32988 @defun calc-change-current-selection selection
32989 Change the currently prepared stack element's selection to
32990 @var{selection}, which should be @code{eq} to some sub-formula
32991 of the stack element, or @code{nil} to unselect the formula.
32992 The stack element's appearance in the Calc buffer is adjusted
32993 to reflect the new selection.
32994 @end defun
32996 @defun calc-find-nth-part expr n
32997 Return the @var{n}th sub-formula of @var{expr}.  This function is used
32998 by the selection commands, and (unless @kbd{j b} has been used) treats
32999 sums and products as flat many-element formulas.  Thus if @var{expr}
33000 is @samp{((a + b) - c) + d}, calling @code{calc-find-nth-part} with
33001 @var{n} equal to four will return @samp{d}.
33002 @end defun
33004 @defun calc-find-parent-formula expr part
33005 Return the sub-formula of @var{expr} which immediately contains
33006 @var{part}.  If @var{expr} is @samp{a*b + (c+1)*d} and @var{part}
33007 is @code{eq} to the @samp{c+1} term of @var{expr}, then this function
33008 will return @samp{(c+1)*d}.  If @var{part} turns out not to be a
33009 sub-formula of @var{expr}, the function returns @code{nil}.  If
33010 @var{part} is @code{eq} to @var{expr}, the function returns @code{t}.
33011 This function does not take associativity into account.
33012 @end defun
33014 @defun calc-find-assoc-parent-formula expr part
33015 This is the same as @code{calc-find-parent-formula}, except that
33016 (unless @kbd{j b} has been used) it continues widening the selection
33017 to contain a complete level of the formula.  Given @samp{a} from
33018 @samp{((a + b) - c) + d}, @code{calc-find-parent-formula} will
33019 return @samp{a + b} but @code{calc-find-assoc-parent-formula} will
33020 return the whole expression.
33021 @end defun
33023 @defun calc-grow-assoc-formula expr part
33024 This expands sub-formula @var{part} of @var{expr} to encompass a
33025 complete level of the formula.  If @var{part} and its immediate
33026 parent are not compatible associative operators, or if @kbd{j b}
33027 has been used, this simply returns @var{part}.
33028 @end defun
33030 @defun calc-find-sub-formula expr part
33031 This finds the immediate sub-formula of @var{expr} which contains
33032 @var{part}.  It returns an index @var{n} such that
33033 @samp{(calc-find-nth-part @var{expr} @var{n})} would return @var{part}.
33034 If @var{part} is not a sub-formula of @var{expr}, it returns @code{nil}.
33035 If @var{part} is @code{eq} to @var{expr}, it returns @code{t}.  This
33036 function does not take associativity into account.
33037 @end defun
33039 @defun calc-replace-sub-formula expr old new
33040 This function returns a copy of formula @var{expr}, with the
33041 sub-formula that is @code{eq} to @var{old} replaced by @var{new}.
33042 @end defun
33044 @defun simplify expr
33045 Simplify the expression @var{expr} by applying various algebraic rules.
33046 This is what the @w{@kbd{a s}} (@code{calc-simplify}) command uses.  This
33047 always returns a copy of the expression; the structure @var{expr} points
33048 to remains unchanged in memory.
33050 More precisely, here is what @code{simplify} does:  The expression is
33051 first normalized and evaluated by calling @code{normalize}.  If any
33052 @code{AlgSimpRules} have been defined, they are then applied.  Then
33053 the expression is traversed in a depth-first, bottom-up fashion; at
33054 each level, any simplifications that can be made are made until no
33055 further changes are possible.  Once the entire formula has been
33056 traversed in this way, it is compared with the original formula (from
33057 before the call to @code{normalize}) and, if it has changed,
33058 the entire procedure is repeated (starting with @code{normalize})
33059 until no further changes occur.  Usually only two iterations are
33060 needed:@: one to simplify the formula, and another to verify that no
33061 further simplifications were possible.
33062 @end defun
33064 @defun simplify-extended expr
33065 Simplify the expression @var{expr}, with additional rules enabled that
33066 help do a more thorough job, while not being entirely ``safe'' in all
33067 circumstances.  (For example, this mode will simplify @samp{sqrt(x^2)}
33068 to @samp{x}, which is only valid when @var{x} is positive.)  This is
33069 implemented by temporarily binding the variable @code{math-living-dangerously}
33070 to @code{t} (using a @code{let} form) and calling @code{simplify}.
33071 Dangerous simplification rules are written to check this variable
33072 before taking any action.@refill
33073 @end defun
33075 @defun simplify-units expr
33076 Simplify the expression @var{expr}, treating variable names as units
33077 whenever possible.  This works by binding the variable
33078 @code{math-simplifying-units} to @code{t} while calling @code{simplify}.
33079 @end defun
33081 @defmac math-defsimplify funcs body
33082 Register a new simplification rule; this is normally called as a top-level
33083 form, like @code{defun} or @code{defmath}.  If @var{funcs} is a symbol
33084 (like @code{+} or @code{calcFunc-sqrt}), this simplification rule is
33085 applied to the formulas which are calls to the specified function.  Or,
33086 @var{funcs} can be a list of such symbols; the rule applies to all
33087 functions on the list.  The @var{body} is written like the body of a
33088 function with a single argument called @code{expr}.  The body will be
33089 executed with @code{expr} bound to a formula which is a call to one of
33090 the functions @var{funcs}.  If the function body returns @code{nil}, or
33091 if it returns a result @code{equal} to the original @code{expr}, it is
33092 ignored and Calc goes on to try the next simplification rule that applies.
33093 If the function body returns something different, that new formula is
33094 substituted for @var{expr} in the original formula.@refill
33096 At each point in the formula, rules are tried in the order of the
33097 original calls to @code{math-defsimplify}; the search stops after the
33098 first rule that makes a change.  Thus later rules for that same
33099 function will not have a chance to trigger until the next iteration
33100 of the main @code{simplify} loop.
33102 Note that, since @code{defmath} is not being used here, @var{body} must
33103 be written in true Lisp code without the conveniences that @code{defmath}
33104 provides.  If you prefer, you can have @var{body} simply call another
33105 function (defined with @code{defmath}) which does the real work.
33107 The arguments of a function call will already have been simplified
33108 before any rules for the call itself are invoked.  Since a new argument
33109 list is consed up when this happens, this means that the rule's body is
33110 allowed to rearrange the function's arguments destructively if that is
33111 convenient.  Here is a typical example of a simplification rule:
33113 @smallexample
33114 (math-defsimplify calcFunc-arcsinh
33115   (or (and (math-looks-negp (nth 1 expr))
33116            (math-neg (list 'calcFunc-arcsinh
33117                            (math-neg (nth 1 expr)))))
33118       (and (eq (car-safe (nth 1 expr)) 'calcFunc-sinh)
33119            (or math-living-dangerously
33120                (math-known-realp (nth 1 (nth 1 expr))))
33121            (nth 1 (nth 1 expr)))))
33122 @end smallexample
33124 This is really a pair of rules written with one @code{math-defsimplify}
33125 for convenience; the first replaces @samp{arcsinh(-x)} with
33126 @samp{-arcsinh(x)}, and the second, which is safe only for real @samp{x},
33127 replaces @samp{arcsinh(sinh(x))} with @samp{x}.@refill
33128 @end defmac
33130 @defun common-constant-factor expr
33131 Check @var{expr} to see if it is a sum of terms all multiplied by the
33132 same rational value.  If so, return this value.  If not, return @code{nil}.
33133 For example, if called on @samp{6x + 9y + 12z}, it would return 3, since
33134 3 is a common factor of all the terms.
33135 @end defun
33137 @defun cancel-common-factor expr factor
33138 Assuming @var{expr} is a sum with @var{factor} as a common factor,
33139 divide each term of the sum by @var{factor}.  This is done by
33140 destructively modifying parts of @var{expr}, on the assumption that
33141 it is being used by a simplification rule (where such things are
33142 allowed; see above).  For example, consider this built-in rule for
33143 square roots:
33145 @smallexample
33146 (math-defsimplify calcFunc-sqrt
33147   (let ((fac (math-common-constant-factor (nth 1 expr))))
33148     (and fac (not (eq fac 1))
33149          (math-mul (math-normalize (list 'calcFunc-sqrt fac))
33150                    (math-normalize
33151                     (list 'calcFunc-sqrt
33152                           (math-cancel-common-factor
33153                            (nth 1 expr) fac)))))))
33154 @end smallexample
33155 @end defun
33157 @defun frac-gcd a b
33158 Compute a ``rational GCD'' of @var{a} and @var{b}, which must both be
33159 rational numbers.  This is the fraction composed of the GCD of the
33160 numerators of @var{a} and @var{b}, over the GCD of the denominators.
33161 It is used by @code{common-constant-factor}.  Note that the standard
33162 @code{gcd} function uses the LCM to combine the denominators.@refill
33163 @end defun
33165 @defun map-tree func expr many
33166 Try applying Lisp function @var{func} to various sub-expressions of
33167 @var{expr}.  Initially, call @var{func} with @var{expr} itself as an
33168 argument.  If this returns an expression which is not @code{equal} to
33169 @var{expr}, apply @var{func} again until eventually it does return
33170 @var{expr} with no changes.  Then, if @var{expr} is a function call,
33171 recursively apply @var{func} to each of the arguments.  This keeps going
33172 until no changes occur anywhere in the expression; this final expression
33173 is returned by @code{map-tree}.  Note that, unlike simplification rules,
33174 @var{func} functions may @emph{not} make destructive changes to
33175 @var{expr}.  If a third argument @var{many} is provided, it is an
33176 integer which says how many times @var{func} may be applied; the
33177 default, as described above, is infinitely many times.@refill
33178 @end defun
33180 @defun compile-rewrites rules
33181 Compile the rewrite rule set specified by @var{rules}, which should
33182 be a formula that is either a vector or a variable name.  If the latter,
33183 the compiled rules are saved so that later @code{compile-rules} calls
33184 for that same variable can return immediately.  If there are problems
33185 with the rules, this function calls @code{error} with a suitable
33186 message.
33187 @end defun
33189 @defun apply-rewrites expr crules heads
33190 Apply the compiled rewrite rule set @var{crules} to the expression
33191 @var{expr}.  This will make only one rewrite and only checks at the
33192 top level of the expression.  The result @code{nil} if no rules
33193 matched, or if the only rules that matched did not actually change
33194 the expression.  The @var{heads} argument is optional; if is given,
33195 it should be a list of all function names that (may) appear in
33196 @var{expr}.  The rewrite compiler tags each rule with the
33197 rarest-looking function name in the rule; if you specify @var{heads},
33198 @code{apply-rewrites} can use this information to narrow its search
33199 down to just a few rules in the rule set.
33200 @end defun
33202 @defun rewrite-heads expr
33203 Compute a @var{heads} list for @var{expr} suitable for use with
33204 @code{apply-rewrites}, as discussed above.
33205 @end defun
33207 @defun rewrite expr rules many
33208 This is an all-in-one rewrite function.  It compiles the rule set
33209 specified by @var{rules}, then uses @code{map-tree} to apply the
33210 rules throughout @var{expr} up to @var{many} (default infinity)
33211 times.
33212 @end defun
33214 @defun match-patterns pat vec not-flag
33215 Given a Calc vector @var{vec} and an uncompiled pattern set or
33216 pattern set variable @var{pat}, this function returns a new vector
33217 of all elements of @var{vec} which do (or don't, if @var{not-flag} is
33218 non-@code{nil}) match any of the patterns in @var{pat}.
33219 @end defun
33221 @defun deriv expr var value symb
33222 Compute the derivative of @var{expr} with respect to variable @var{var}
33223 (which may actually be any sub-expression).  If @var{value} is specified,
33224 the derivative is evaluated at the value of @var{var}; otherwise, the
33225 derivative is left in terms of @var{var}.  If the expression contains
33226 functions for which no derivative formula is known, new derivative
33227 functions are invented by adding primes to the names; @pxref{Calculus}.
33228 However, if @var{symb} is non-@code{nil}, the presence of undifferentiable
33229 functions in @var{expr} instead cancels the whole differentiation, and
33230 @code{deriv} returns @code{nil} instead.
33232 Derivatives of an @var{n}-argument function can be defined by
33233 adding a @code{math-derivative-@var{n}} property to the property list
33234 of the symbol for the function's derivative, which will be the
33235 function name followed by an apostrophe.  The value of the property
33236 should be a Lisp function; it is called with the same arguments as the
33237 original function call that is being differentiated.  It should return
33238 a formula for the derivative.  For example, the derivative of @code{ln}
33239 is defined by
33241 @smallexample
33242 (put 'calcFunc-ln\' 'math-derivative-1
33243      (function (lambda (u) (math-div 1 u))))
33244 @end smallexample
33246 The two-argument @code{log} function has two derivatives,
33247 @smallexample
33248 (put 'calcFunc-log\' 'math-derivative-2     ; d(log(x,b)) / dx
33249      (function (lambda (x b) ... )))
33250 (put 'calcFunc-log\'2 'math-derivative-2    ; d(log(x,b)) / db
33251      (function (lambda (x b) ... )))
33252 @end smallexample
33253 @end defun
33255 @defun tderiv expr var value symb
33256 Compute the total derivative of @var{expr}.  This is the same as
33257 @code{deriv}, except that variables other than @var{var} are not
33258 assumed to be constant with respect to @var{var}.
33259 @end defun
33261 @defun integ expr var low high
33262 Compute the integral of @var{expr} with respect to @var{var}.
33263 @xref{Calculus}, for further details.
33264 @end defun
33266 @defmac math-defintegral funcs body
33267 Define a rule for integrating a function or functions of one argument;
33268 this macro is very similar in format to @code{math-defsimplify}.
33269 The main difference is that here @var{body} is the body of a function
33270 with a single argument @code{u} which is bound to the argument to the
33271 function being integrated, not the function call itself.  Also, the
33272 variable of integration is available as @code{math-integ-var}.  If
33273 evaluation of the integral requires doing further integrals, the body
33274 should call @samp{(math-integral @var{x})} to find the integral of
33275 @var{x} with respect to @code{math-integ-var}; this function returns
33276 @code{nil} if the integral could not be done.  Some examples:
33278 @smallexample
33279 (math-defintegral calcFunc-conj
33280   (let ((int (math-integral u)))
33281     (and int
33282          (list 'calcFunc-conj int))))
33284 (math-defintegral calcFunc-cos
33285   (and (equal u math-integ-var)
33286        (math-from-radians-2 (list 'calcFunc-sin u))))
33287 @end smallexample
33289 In the @code{cos} example, we define only the integral of @samp{cos(x) dx},
33290 relying on the general integration-by-substitution facility to handle
33291 cosines of more complicated arguments.  An integration rule should return
33292 @code{nil} if it can't do the integral; if several rules are defined for
33293 the same function, they are tried in order until one returns a non-@code{nil}
33294 result.@refill
33295 @end defmac
33297 @defmac math-defintegral-2 funcs body
33298 Define a rule for integrating a function or functions of two arguments.
33299 This is exactly analogous to @code{math-defintegral}, except that @var{body}
33300 is written as the body of a function with two arguments, @var{u} and
33301 @var{v}.@refill
33302 @end defmac
33304 @defun solve-for lhs rhs var full
33305 Attempt to solve the equation @samp{@var{lhs} = @var{rhs}} by isolating
33306 the variable @var{var} on the lefthand side; return the resulting righthand
33307 side, or @code{nil} if the equation cannot be solved.  The variable
33308 @var{var} must appear at least once in @var{lhs} or @var{rhs}.  Note that
33309 the return value is a formula which does not contain @var{var}; this is
33310 different from the user-level @code{solve} and @code{finv} functions,
33311 which return a rearranged equation or a functional inverse, respectively.
33312 If @var{full} is non-@code{nil}, a full solution including dummy signs
33313 and dummy integers will be produced.  User-defined inverses are provided
33314 as properties in a manner similar to derivatives:@refill
33316 @smallexample
33317 (put 'calcFunc-ln 'math-inverse
33318      (function (lambda (x) (list 'calcFunc-exp x))))
33319 @end smallexample
33321 This function can call @samp{(math-solve-get-sign @var{x})} to create
33322 a new arbitrary sign variable, returning @var{x} times that sign, and
33323 @samp{(math-solve-get-int @var{x})} to create a new arbitrary integer
33324 variable multiplied by @var{x}.  These functions simply return @var{x}
33325 if the caller requested a non-``full'' solution.
33326 @end defun
33328 @defun solve-eqn expr var full
33329 This version of @code{solve-for} takes an expression which will
33330 typically be an equation or inequality.  (If it is not, it will be
33331 interpreted as the equation @samp{@var{expr} = 0}.)  It returns an
33332 equation or inequality, or @code{nil} if no solution could be found.
33333 @end defun
33335 @defun solve-system exprs vars full
33336 This function solves a system of equations.  Generally, @var{exprs}
33337 and @var{vars} will be vectors of equal length.
33338 @xref{Solving Systems of Equations}, for other options.
33339 @end defun
33341 @defun expr-contains expr var
33342 Returns a non-@code{nil} value if @var{var} occurs as a subexpression
33343 of @var{expr}.
33345 This function might seem at first to be identical to
33346 @code{calc-find-sub-formula}.  The key difference is that
33347 @code{expr-contains} uses @code{equal} to test for matches, whereas
33348 @code{calc-find-sub-formula} uses @code{eq}.  In the formula
33349 @samp{f(a, a)}, the two @samp{a}s will be @code{equal} but not
33350 @code{eq} to each other.@refill
33351 @end defun
33353 @defun expr-contains-count expr var
33354 Returns the number of occurrences of @var{var} as a subexpression
33355 of @var{expr}, or @code{nil} if there are no occurrences.@refill
33356 @end defun
33358 @defun expr-depends expr var
33359 Returns true if @var{expr} refers to any variable the occurs in @var{var}.
33360 In other words, it checks if @var{expr} and @var{var} have any variables
33361 in common.
33362 @end defun
33364 @defun expr-contains-vars expr
33365 Return true if @var{expr} contains any variables, or @code{nil} if @var{expr}
33366 contains only constants and functions with constant arguments.
33367 @end defun
33369 @defun expr-subst expr old new
33370 Returns a copy of @var{expr}, with all occurrences of @var{old} replaced
33371 by @var{new}.  This treats @code{lambda} forms specially with respect
33372 to the dummy argument variables, so that the effect is always to return
33373 @var{expr} evaluated at @var{old} = @var{new}.@refill
33374 @end defun
33376 @defun multi-subst expr old new
33377 This is like @code{expr-subst}, except that @var{old} and @var{new}
33378 are lists of expressions to be substituted simultaneously.  If one
33379 list is shorter than the other, trailing elements of the longer list
33380 are ignored.
33381 @end defun
33383 @defun expr-weight expr
33384 Returns the ``weight'' of @var{expr}, basically a count of the total
33385 number of objects and function calls that appear in @var{expr}.  For
33386 ``primitive'' objects, this will be one.
33387 @end defun
33389 @defun expr-height expr
33390 Returns the ``height'' of @var{expr}, which is the deepest level to
33391 which function calls are nested.  (Note that @samp{@var{a} + @var{b}}
33392 counts as a function call.)  For primitive objects, this returns zero.@refill
33393 @end defun
33395 @defun polynomial-p expr var
33396 Check if @var{expr} is a polynomial in variable (or sub-expression)
33397 @var{var}.  If so, return the degree of the polynomial, that is, the
33398 highest power of @var{var} that appears in @var{expr}.  For example,
33399 for @samp{(x^2 + 3)^3 + 4} this would return 6.  This function returns
33400 @code{nil} unless @var{expr}, when expanded out by @kbd{a x}
33401 (@code{calc-expand}), would consist of a sum of terms in which @var{var}
33402 appears only raised to nonnegative integer powers.  Note that if
33403 @var{var} does not occur in @var{expr}, then @var{expr} is considered
33404 a polynomial of degree 0.@refill
33405 @end defun
33407 @defun is-polynomial expr var degree loose
33408 Check if @var{expr} is a polynomial in variable or sub-expression
33409 @var{var}, and, if so, return a list representation of the polynomial
33410 where the elements of the list are coefficients of successive powers of
33411 @var{var}: @samp{@var{a} + @var{b} x + @var{c} x^3} would produce the
33412 list @samp{(@var{a} @var{b} 0 @var{c})}, and @samp{(x + 1)^2} would
33413 produce the list @samp{(1 2 1)}.  The highest element of the list will
33414 be non-zero, with the special exception that if @var{expr} is the
33415 constant zero, the returned value will be @samp{(0)}.  Return @code{nil}
33416 if @var{expr} is not a polynomial in @var{var}.  If @var{degree} is
33417 specified, this will not consider polynomials of degree higher than that
33418 value.  This is a good precaution because otherwise an input of
33419 @samp{(x+1)^1000} will cause a huge coefficient list to be built.  If
33420 @var{loose} is non-@code{nil}, then a looser definition of a polynomial
33421 is used in which coefficients are no longer required not to depend on
33422 @var{var}, but are only required not to take the form of polynomials
33423 themselves.  For example, @samp{sin(x) x^2 + cos(x)} is a loose
33424 polynomial with coefficients @samp{((calcFunc-cos x) 0 (calcFunc-sin
33425 x))}.  The result will never be @code{nil} in loose mode, since any
33426 expression can be interpreted as a ``constant'' loose polynomial.@refill
33427 @end defun
33429 @defun polynomial-base expr pred
33430 Check if @var{expr} is a polynomial in any variable that occurs in it;
33431 if so, return that variable.  (If @var{expr} is a multivariate polynomial,
33432 this chooses one variable arbitrarily.)  If @var{pred} is specified, it should
33433 be a Lisp function which is called as @samp{(@var{pred} @var{subexpr})},
33434 and which should return true if @code{mpb-top-expr} (a global name for
33435 the original @var{expr}) is a suitable polynomial in @var{subexpr}.
33436 The default predicate uses @samp{(polynomial-p mpb-top-expr @var{subexpr})};
33437 you can use @var{pred} to specify additional conditions.  Or, you could
33438 have @var{pred} build up a list of every suitable @var{subexpr} that
33439 is found.@refill
33440 @end defun
33442 @defun poly-simplify poly
33443 Simplify polynomial coefficient list @var{poly} by (destructively)
33444 clipping off trailing zeros.
33445 @end defun
33447 @defun poly-mix a ac b bc
33448 Mix two polynomial lists @var{a} and @var{b} (in the form returned by
33449 @code{is-polynomial}) in a linear combination with coefficient expressions
33450 @var{ac} and @var{bc}.  The result is a (not necessarily simplified)
33451 polynomial list representing @samp{@var{ac} @var{a} + @var{bc} @var{b}}.@refill
33452 @end defun
33454 @defun poly-mul a b
33455 Multiply two polynomial coefficient lists @var{a} and @var{b}.  The
33456 result will be in simplified form if the inputs were simplified.
33457 @end defun
33459 @defun build-polynomial-expr poly var
33460 Construct a Calc formula which represents the polynomial coefficient
33461 list @var{poly} applied to variable @var{var}.  The @kbd{a c}
33462 (@code{calc-collect}) command uses @code{is-polynomial} to turn an
33463 expression into a coefficient list, then @code{build-polynomial-expr}
33464 to turn the list back into an expression in regular form.@refill
33465 @end defun
33467 @defun check-unit-name var
33468 Check if @var{var} is a variable which can be interpreted as a unit
33469 name.  If so, return the units table entry for that unit.  This
33470 will be a list whose first element is the unit name (not counting
33471 prefix characters) as a symbol and whose second element is the
33472 Calc expression which defines the unit.  (Refer to the Calc sources
33473 for details on the remaining elements of this list.)  If @var{var}
33474 is not a variable or is not a unit name, return @code{nil}.
33475 @end defun
33477 @defun units-in-expr-p expr sub-exprs
33478 Return true if @var{expr} contains any variables which can be
33479 interpreted as units.  If @var{sub-exprs} is @code{t}, the entire
33480 expression is searched.  If @var{sub-exprs} is @code{nil}, this
33481 checks whether @var{expr} is directly a units expression.@refill
33482 @end defun
33484 @defun single-units-in-expr-p expr
33485 Check whether @var{expr} contains exactly one units variable.  If so,
33486 return the units table entry for the variable.  If @var{expr} does
33487 not contain any units, return @code{nil}.  If @var{expr} contains
33488 two or more units, return the symbol @code{wrong}.
33489 @end defun
33491 @defun to-standard-units expr which
33492 Convert units expression @var{expr} to base units.  If @var{which}
33493 is @code{nil}, use Calc's native base units.  Otherwise, @var{which}
33494 can specify a units system, which is a list of two-element lists,
33495 where the first element is a Calc base symbol name and the second
33496 is an expression to substitute for it.@refill
33497 @end defun
33499 @defun remove-units expr
33500 Return a copy of @var{expr} with all units variables replaced by ones.
33501 This expression is generally normalized before use.
33502 @end defun
33504 @defun extract-units expr
33505 Return a copy of @var{expr} with everything but units variables replaced
33506 by ones.
33507 @end defun
33509 @node Formatting Lisp Functions, Hooks, Symbolic Lisp Functions, Internals
33510 @subsubsection I/O and Formatting Functions
33512 @noindent
33513 The functions described here are responsible for parsing and formatting
33514 Calc numbers and formulas.
33516 @defun calc-eval str sep arg1 arg2 @dots{}
33517 This is the simplest interface to the Calculator from another Lisp program.
33518 @xref{Calling Calc from Your Programs}.
33519 @end defun
33521 @defun read-number str
33522 If string @var{str} contains a valid Calc number, either integer,
33523 fraction, float, or HMS form, this function parses and returns that
33524 number.  Otherwise, it returns @code{nil}.
33525 @end defun
33527 @defun read-expr str
33528 Read an algebraic expression from string @var{str}.  If @var{str} does
33529 not have the form of a valid expression, return a list of the form
33530 @samp{(error @var{pos} @var{msg})} where @var{pos} is an integer index
33531 into @var{str} of the general location of the error, and @var{msg} is
33532 a string describing the problem.@refill
33533 @end defun
33535 @defun read-exprs str
33536 Read a list of expressions separated by commas, and return it as a
33537 Lisp list.  If an error occurs in any expressions, an error list as
33538 shown above is returned instead.
33539 @end defun
33541 @defun calc-do-alg-entry initial prompt no-norm
33542 Read an algebraic formula or formulas using the minibuffer.  All
33543 conventions of regular algebraic entry are observed.  The return value
33544 is a list of Calc formulas; there will be more than one if the user
33545 entered a list of values separated by commas.  The result is @code{nil}
33546 if the user presses Return with a blank line.  If @var{initial} is
33547 given, it is a string which the minibuffer will initially contain.
33548 If @var{prompt} is given, it is the prompt string to use; the default
33549 is ``Algebraic:''.  If @var{no-norm} is @code{t}, the formulas will
33550 be returned exactly as parsed; otherwise, they will be passed through
33551 @code{calc-normalize} first.@refill
33553 To support the use of @kbd{$} characters in the algebraic entry, use
33554 @code{let} to bind @code{calc-dollar-values} to a list of the values
33555 to be substituted for @kbd{$}, @kbd{$$}, and so on, and bind
33556 @code{calc-dollar-used} to 0.  Upon return, @code{calc-dollar-used}
33557 will have been changed to the highest number of consecutive @kbd{$}s
33558 that actually appeared in the input.@refill
33559 @end defun
33561 @defun format-number a
33562 Convert the real or complex number or HMS form @var{a} to string form.
33563 @end defun
33565 @defun format-flat-expr a prec
33566 Convert the arbitrary Calc number or formula @var{a} to string form,
33567 in the style used by the trail buffer and the @code{calc-edit} command.
33568 This is a simple format designed
33569 mostly to guarantee the string is of a form that can be re-parsed by
33570 @code{read-expr}.  Most formatting modes, such as digit grouping,
33571 complex number format, and point character, are ignored to ensure the
33572 result will be re-readable.  The @var{prec} parameter is normally 0; if
33573 you pass a large integer like 1000 instead, the expression will be
33574 surrounded by parentheses unless it is a plain number or variable name.@refill
33575 @end defun
33577 @defun format-nice-expr a width
33578 This is like @code{format-flat-expr} (with @var{prec} equal to 0),
33579 except that newlines will be inserted to keep lines down to the
33580 specified @var{width}, and vectors that look like matrices or rewrite
33581 rules are written in a pseudo-matrix format.  The @code{calc-edit}
33582 command uses this when only one stack entry is being edited.
33583 @end defun
33585 @defun format-value a width
33586 Convert the Calc number or formula @var{a} to string form, using the
33587 format seen in the stack buffer.  Beware the the string returned may
33588 not be re-readable by @code{read-expr}, for example, because of digit
33589 grouping.  Multi-line objects like matrices produce strings that
33590 contain newline characters to separate the lines.  The @var{w}
33591 parameter, if given, is the target window size for which to format
33592 the expressions.  If @var{w} is omitted, the width of the Calculator
33593 window is used.@refill
33594 @end defun
33596 @defun compose-expr a prec
33597 Format the Calc number or formula @var{a} according to the current
33598 language mode, returning a ``composition.''  To learn about the
33599 structure of compositions, see the comments in the Calc source code.
33600 You can specify the format of a given type of function call by putting
33601 a @code{math-compose-@var{lang}} property on the function's symbol,
33602 whose value is a Lisp function that takes @var{a} and @var{prec} as
33603 arguments and returns a composition.  Here @var{lang} is a language
33604 mode name, one of @code{normal}, @code{big}, @code{c}, @code{pascal},
33605 @code{fortran}, @code{tex}, @code{eqn}, @code{math}, or @code{maple}.
33606 In Big mode, Calc actually tries @code{math-compose-big} first, then
33607 tries @code{math-compose-normal}.  If this property does not exist,
33608 or if the function returns @code{nil}, the function is written in the
33609 normal function-call notation for that language.
33610 @end defun
33612 @defun composition-to-string c w
33613 Convert a composition structure returned by @code{compose-expr} into
33614 a string.  Multi-line compositions convert to strings containing
33615 newline characters.  The target window size is given by @var{w}.
33616 The @code{format-value} function basically calls @code{compose-expr}
33617 followed by @code{composition-to-string}.
33618 @end defun
33620 @defun comp-width c
33621 Compute the width in characters of composition @var{c}.
33622 @end defun
33624 @defun comp-height c
33625 Compute the height in lines of composition @var{c}.
33626 @end defun
33628 @defun comp-ascent c
33629 Compute the portion of the height of composition @var{c} which is on or
33630 above the baseline.  For a one-line composition, this will be one.
33631 @end defun
33633 @defun comp-descent c
33634 Compute the portion of the height of composition @var{c} which is below
33635 the baseline.  For a one-line composition, this will be zero.
33636 @end defun
33638 @defun comp-first-char c
33639 If composition @var{c} is a ``flat'' composition, return the first
33640 (leftmost) character of the composition as an integer.  Otherwise,
33641 return @code{nil}.@refill
33642 @end defun
33644 @defun comp-last-char c
33645 If composition @var{c} is a ``flat'' composition, return the last
33646 (rightmost) character, otherwise return @code{nil}.
33647 @end defun
33649 @comment @node Lisp Variables, Hooks, Formatting Lisp Functions, Internals
33650 @comment @subsubsection Lisp Variables
33651 @comment 
33652 @comment @noindent
33653 @comment (This section is currently unfinished.)
33655 @node Hooks, , Formatting Lisp Functions, Internals
33656 @subsubsection Hooks
33658 @noindent
33659 Hooks are variables which contain Lisp functions (or lists of functions)
33660 which are called at various times.  Calc defines a number of hooks
33661 that help you to customize it in various ways.  Calc uses the Lisp
33662 function @code{run-hooks} to invoke the hooks shown below.  Several
33663 other customization-related variables are also described here.
33665 @defvar calc-load-hook
33666 This hook is called at the end of @file{calc.el}, after the file has
33667 been loaded, before any functions in it have been called, but after
33668 @code{calc-mode-map} and similar variables have been set up.
33669 @end defvar
33671 @defvar calc-ext-load-hook
33672 This hook is called at the end of @file{calc-ext.el}.
33673 @end defvar
33675 @defvar calc-start-hook
33676 This hook is called as the last step in a @kbd{M-x calc} command.
33677 At this point, the Calc buffer has been created and initialized if
33678 necessary, the Calc window and trail window have been created,
33679 and the ``Welcome to Calc'' message has been displayed.
33680 @end defvar
33682 @defvar calc-mode-hook
33683 This hook is called when the Calc buffer is being created.  Usually
33684 this will only happen once per Emacs session.  The hook is called
33685 after Emacs has switched to the new buffer, the mode-settings file
33686 has been read if necessary, and all other buffer-local variables
33687 have been set up.  After this hook returns, Calc will perform a
33688 @code{calc-refresh} operation, set up the mode line display, then
33689 evaluate any deferred @code{calc-define} properties that have not
33690 been evaluated yet.
33691 @end defvar
33693 @defvar calc-trail-mode-hook
33694 This hook is called when the Calc Trail buffer is being created.
33695 It is called as the very last step of setting up the Trail buffer.
33696 Like @code{calc-mode-hook}, this will normally happen only once
33697 per Emacs session.
33698 @end defvar
33700 @defvar calc-end-hook
33701 This hook is called by @code{calc-quit}, generally because the user
33702 presses @kbd{q} or @kbd{M-# c} while in Calc.  The Calc buffer will
33703 be the current buffer.  The hook is called as the very first
33704 step, before the Calc window is destroyed.
33705 @end defvar
33707 @defvar calc-window-hook
33708 If this hook exists, it is called to create the Calc window.
33709 Upon return, this new Calc window should be the current window.
33710 (The Calc buffer will already be the current buffer when the
33711 hook is called.)  If the hook is not defined, Calc will
33712 generally use @code{split-window}, @code{set-window-buffer},
33713 and @code{select-window} to create the Calc window.
33714 @end defvar
33716 @defvar calc-trail-window-hook
33717 If this hook exists, it is called to create the Calc Trail window.
33718 The variable @code{calc-trail-buffer} will contain the buffer
33719 which the window should use.  Unlike @code{calc-window-hook},
33720 this hook must @emph{not} switch into the new window.
33721 @end defvar
33723 @defvar calc-edit-mode-hook
33724 This hook is called by @code{calc-edit} (and the other ``edit''
33725 commands) when the temporary editing buffer is being created.
33726 The buffer will have been selected and set up to be in
33727 @code{calc-edit-mode}, but will not yet have been filled with
33728 text.  (In fact it may still have leftover text from a previous
33729 @code{calc-edit} command.)
33730 @end defvar
33732 @defvar calc-mode-save-hook
33733 This hook is called by the @code{calc-save-modes} command,
33734 after Calc's own mode features have been inserted into the
33735 @file{.emacs} buffer and just before the ``End of mode settings''
33736 message is inserted.
33737 @end defvar
33739 @defvar calc-reset-hook
33740 This hook is called after @kbd{M-# 0} (@code{calc-reset}) has
33741 reset all modes.  The Calc buffer will be the current buffer.
33742 @end defvar
33744 @defvar calc-other-modes
33745 This variable contains a list of strings.  The strings are
33746 concatenated at the end of the modes portion of the Calc
33747 mode line (after standard modes such as ``Deg'', ``Inv'' and
33748 ``Hyp'').  Each string should be a short, single word followed
33749 by a space.  The variable is @code{nil} by default.
33750 @end defvar
33752 @defvar calc-mode-map
33753 This is the keymap that is used by Calc mode.  The best time
33754 to adjust it is probably in a @code{calc-mode-hook}.  If the
33755 Calc extensions package (@file{calc-ext.el}) has not yet been
33756 loaded, many of these keys will be bound to @code{calc-missing-key},
33757 which is a command that loads the extensions package and
33758 ``retypes'' the key.  If your @code{calc-mode-hook} rebinds
33759 one of these keys, it will probably be overridden when the
33760 extensions are loaded.
33761 @end defvar
33763 @defvar calc-digit-map
33764 This is the keymap that is used during numeric entry.  Numeric
33765 entry uses the minibuffer, but this map binds every non-numeric
33766 key to @code{calcDigit-nondigit} which generally calls
33767 @code{exit-minibuffer} and ``retypes'' the key.
33768 @end defvar
33770 @defvar calc-alg-ent-map
33771 This is the keymap that is used during algebraic entry.  This is
33772 mostly a copy of @code{minibuffer-local-map}.
33773 @end defvar
33775 @defvar calc-store-var-map
33776 This is the keymap that is used during entry of variable names for
33777 commands like @code{calc-store} and @code{calc-recall}.  This is
33778 mostly a copy of @code{minibuffer-local-completion-map}.
33779 @end defvar
33781 @defvar calc-edit-mode-map
33782 This is the (sparse) keymap used by @code{calc-edit} and other
33783 temporary editing commands.  It binds @key{RET}, @key{LFD},
33784 and @kbd{C-c C-c} to @code{calc-edit-finish}.
33785 @end defvar
33787 @defvar calc-mode-var-list
33788 This is a list of variables which are saved by @code{calc-save-modes}.
33789 Each entry is a list of two items, the variable (as a Lisp symbol)
33790 and its default value.  When modes are being saved, each variable
33791 is compared with its default value (using @code{equal}) and any
33792 non-default variables are written out.
33793 @end defvar
33795 @defvar calc-local-var-list
33796 This is a list of variables which should be buffer-local to the
33797 Calc buffer.  Each entry is a variable name (as a Lisp symbol).
33798 These variables also have their default values manipulated by
33799 the @code{calc} and @code{calc-quit} commands; @pxref{Multiple Calculators}.
33800 Since @code{calc-mode-hook} is called after this list has been
33801 used the first time, your hook should add a variable to the
33802 list and also call @code{make-local-variable} itself.
33803 @end defvar
33805 @node Installation, Reporting Bugs, Programming, Top
33806 @appendix Installation
33808 @noindent
33809 As of Calc 2.02g, Calc is integrated with GNU Emacs, and thus requires
33810 no separate installation of its Lisp files and this manual.
33812 @appendixsec The GNUPLOT Program
33814 @noindent
33815 Calc's graphing commands use the GNUPLOT program.  If you have GNUPLOT
33816 but you must type some command other than @file{gnuplot} to get it,
33817 you should add a command to set the Lisp variable @code{calc-gnuplot-name}
33818 to the appropriate file name.  You may also need to change the variables
33819 @code{calc-gnuplot-plot-command} and @code{calc-gnuplot-print-command} in
33820 order to get correct displays and hardcopies, respectively, of your
33821 plots.@refill
33823 @ifinfo
33824 @example
33826 @end example
33827 @end ifinfo
33828 @appendixsec Printed Documentation
33830 @noindent
33831 Because the Calc manual is so large, you should only make a printed
33832 copy if you really need it.  To print the manual, you will need the
33833 @TeX{} typesetting program (this is a free program by Donald Knuth
33834 at Stanford University) as well as the @file{texindex} program and
33835 @file{texinfo.tex} file, both of which can be obtained from the FSF
33836 as part of the @code{texinfo} package.@refill
33838 To print the Calc manual in one huge 550 page tome, you will need the
33839 source code to this manual, @file{calc.texi}, available as part of the
33840 Emacs source.  Once you have this file, type @samp{tex calc.texi}
33841 twice.  (Running the manual through @TeX{} twice is necessary so that
33842 references to later parts of the manual will have correct page
33843 numbers.  (Don't worry if you get some ``overfull box'' warnings.)
33845 The result will be a device-independent output file called
33846 @file{calc.dvi}, which you must print in whatever way is right
33847 for your system.  On many systems, the command is
33849 @example
33850 lpr -d calc.dvi
33851 @end example
33853 @cindex Marginal notes, adjusting
33854 Marginal notes for each function and key sequence normally alternate
33855 between the left and right sides of the page, which is correct if the
33856 manual is going to be bound as double-sided pages.  Near the top of
33857 the file @file{calc.texi} you will find alternate definitions of
33858 the @code{\bumpoddpages} macro that put the marginal notes always on
33859 the same side, best if you plan to be binding single-sided pages.
33861 @appendixsec Settings File
33863 @noindent
33864 @vindex calc-settings-file
33865 Another variable you might want to set is @code{calc-settings-file},
33866 which holds the file name in which commands like @kbd{m m} and @kbd{Z P}
33867 store ``permanent'' definitions.  The default value for this variable
33868 is @code{"~/.emacs"}.  If @code{calc-settings-file} does not contain
33869 @code{".emacs"} as a substring, and if the variable
33870 @code{calc-loaded-settings-file} is @code{nil}, then Calc will
33871 automatically load your settings file (if it exists) the first time
33872 Calc is invoked.@refill
33874 @ifinfo
33875 @example
33877 @end example
33878 @end ifinfo
33879 @appendixsec Testing the Installation
33881 @noindent
33882 To test your installation of Calc, start a new Emacs and type @kbd{M-# c}
33883 to make sure the autoloads and key bindings work.  Type @kbd{M-# i}
33884 to make sure Calc can find its Info documentation.  Press @kbd{q} to
33885 exit the Info system and @kbd{M-# c} to re-enter the Calculator.
33886 Type @kbd{20 S} to compute the sine of 20 degrees; this will test the
33887 autoloading of the extensions modules.  The result should be
33888 0.342020143326.  Finally, press @kbd{M-# c} again to make sure the
33889 Calculator can exit.
33891 You may also wish to test the GNUPLOT interface; to plot a sine wave,
33892 type @kbd{' [0 ..@: 360], sin(x) RET g f}.  Type @kbd{g q} when you
33893 are done viewing the plot.
33895 Calc is now ready to use.  If you wish to go through the Calc Tutorial,
33896 press @kbd{M-# t} to begin.
33897 @example
33899 @end example
33900 @node Reporting Bugs, Summary, Installation, Top
33901 @appendix Reporting Bugs
33903 @noindent
33904 If you find a bug in Calc, send e-mail to Colin Walters,
33906 @example
33907 walters@@debian.org           @r{or}
33908 walters@@verbum.org
33909 @end example
33911 @noindent
33912 (In the following text, ``I'' refers to the original Calc author, Dave
33913 Gillespie).
33915 While I cannot guarantee that I will have time to work on your bug,
33916 I do try to fix bugs quickly whenever I can.
33918 The latest version of Calc is available from Savannah, in the Emacs
33919 CVS tree.  See @uref{http://savannah.gnu.org/projects/emacs}.
33921 There is an automatic command @kbd{M-x report-calc-bug} which helps
33922 you to report bugs.  This command prompts you for a brief subject
33923 line, then leaves you in a mail editing buffer.  Type @kbd{C-c C-c} to
33924 send your mail.  Make sure your subject line indicates that you are
33925 reporting a Calc bug; this command sends mail to the maintainer's
33926 regular mailbox.
33928 If you have suggestions for additional features for Calc, I would
33929 love to hear them.  Some have dared to suggest that Calc is already
33930 top-heavy with features; I really don't see what they're talking
33931 about, so, if you have ideas, send them right in.  (I may even have
33932 time to implement them!)
33934 At the front of the source file, @file{calc.el}, is a list of ideas for
33935 future work which I have not had time to do.  If any enthusiastic souls
33936 wish to take it upon themselves to work on these, I would be delighted.
33937 Please let me know if you plan to contribute to Calc so I can coordinate
33938 your efforts with mine and those of others.  I will do my best to help
33939 you in whatever way I can.
33941 @c [summary]
33942 @node Summary, Key Index, Reporting Bugs, Top
33943 @appendix Calc Summary
33945 @noindent
33946 This section includes a complete list of Calc 2.02 keystroke commands.
33947 Each line lists the stack entries used by the command (top-of-stack
33948 last), the keystrokes themselves, the prompts asked by the command,
33949 and the result of the command (also with top-of-stack last).
33950 The result is expressed using the equivalent algebraic function.
33951 Commands which put no results on the stack show the full @kbd{M-x}
33952 command name in that position.  Numbers preceding the result or
33953 command name refer to notes at the end.
33955 Algebraic functions and @kbd{M-x} commands that don't have corresponding
33956 keystrokes are not listed in this summary.
33957 @xref{Command Index}.  @xref{Function Index}.
33959 @iftex
33960 @begingroup
33961 @tex
33962 \vskip-2\baselineskip \null
33963 \gdef\sumrow#1{\sumrowx#1\relax}%
33964 \gdef\sumrowx#1\:#2\:#3\:#4\:#5\:#6\relax{%
33965 \leavevmode%
33966 \hbox to5em{\indsl\hss#1}%
33967 \hbox to5em{\ninett#2\hss}%
33968 \hbox to4em{\indsl#3\hss}%
33969 \hbox to5em{\indrm\hss#4}%
33970 \thinspace%
33971 {\ninett#5}%
33972 {\indsl#6}%
33974 \gdef\sumlpar{{\indrm(}}%
33975 \gdef\sumrpar{{\indrm)}}%
33976 \gdef\sumcomma{{\indrm,\thinspace}}%
33977 \gdef\sumexcl{{\indrm!}}%
33978 \gdef\sumbreak{\vskip-2.5\baselineskip\goodbreak}%
33979 \gdef\minus#1{{\tt-}}%
33980 @end tex
33981 @let@:=@sumsep
33982 @let@r=@sumrow
33983 @catcode`@(=@active @let(=@sumlpar
33984 @catcode`@)=@active @let)=@sumrpar
33985 @catcode`@,=@active @let,=@sumcomma
33986 @catcode`@!=@active @let!=@sumexcl
33987 @end iftex
33988 @format
33989 @iftex
33990 @advance@baselineskip-2.5pt
33991 @let@tt@ninett
33992 @let@c@sumbreak
33993 @end iftex
33994 @r{       @:     M-# a  @:             @:    33  @:calc-embedded-activate@:}
33995 @r{       @:     M-# b  @:             @:        @:calc-big-or-small@:}
33996 @r{       @:     M-# c  @:             @:        @:calc@:}
33997 @r{       @:     M-# d  @:             @:        @:calc-embedded-duplicate@:}
33998 @r{       @:     M-# e  @:             @:    34  @:calc-embedded@:}
33999 @r{       @:     M-# f  @:formula      @:        @:calc-embedded-new-formula@:}
34000 @r{       @:     M-# g  @:             @:    35  @:calc-grab-region@:}
34001 @r{       @:     M-# i  @:             @:        @:calc-info@:}
34002 @r{       @:     M-# j  @:             @:        @:calc-embedded-select@:}
34003 @r{       @:     M-# k  @:             @:        @:calc-keypad@:}
34004 @r{       @:     M-# l  @:             @:        @:calc-load-everything@:}
34005 @r{       @:     M-# m  @:             @:        @:read-kbd-macro@:}
34006 @r{       @:     M-# n  @:             @:     4  @:calc-embedded-next@:}
34007 @r{       @:     M-# o  @:             @:        @:calc-other-window@:}
34008 @r{       @:     M-# p  @:             @:     4  @:calc-embedded-previous@:}
34009 @r{       @:     M-# q  @:formula      @:        @:quick-calc@:}
34010 @r{       @:     M-# r  @:             @:    36  @:calc-grab-rectangle@:}
34011 @r{       @:     M-# s  @:             @:        @:calc-info-summary@:}
34012 @r{       @:     M-# t  @:             @:        @:calc-tutorial@:}
34013 @r{       @:     M-# u  @:             @:        @:calc-embedded-update@:}
34014 @r{       @:     M-# w  @:             @:        @:calc-embedded-word@:}
34015 @r{       @:     M-# x  @:             @:        @:calc-quit@:}
34016 @r{       @:     M-# y  @:            @:1,28,49  @:calc-copy-to-buffer@:}
34017 @r{       @:     M-# z  @:             @:        @:calc-user-invocation@:}
34018 @r{       @:     M-# :  @:             @:    36  @:calc-grab-sum-down@:}
34019 @r{       @:     M-# _  @:             @:    36  @:calc-grab-sum-across@:}
34020 @r{       @:     M-# `  @:editing      @:    30  @:calc-embedded-edit@:}
34021 @r{       @:     M-# 0  @:(zero)       @:        @:calc-reset@:}
34023 @c 
34024 @r{       @:      0-9   @:number       @:        @:@:number}
34025 @r{       @:      .     @:number       @:        @:@:0.number}
34026 @r{       @:      _     @:number       @:        @:-@:number}
34027 @r{       @:      e     @:number       @:        @:@:1e number}
34028 @r{       @:      #     @:number       @:        @:@:current-radix@t{#}number}
34029 @r{       @:      P     @:(in number)  @:        @:+/-@:}
34030 @r{       @:      M     @:(in number)  @:        @:mod@:}
34031 @r{       @:      @@ ' " @:  (in number)@:        @:@:HMS form}
34032 @r{       @:      h m s @:  (in number)@:        @:@:HMS form}
34034 @c 
34035 @r{       @:      '     @:formula      @: 37,46  @:@:formula}
34036 @r{       @:      $     @:formula      @: 37,46  @:$@:formula}
34037 @r{       @:      "     @:string       @: 37,46  @:@:string}
34039 @c 
34040 @r{    a b@:      +     @:             @:     2  @:add@:(a,b)  a+b}
34041 @r{    a b@:      -     @:             @:     2  @:sub@:(a,b)  a@minus{}b}
34042 @r{    a b@:      *     @:             @:     2  @:mul@:(a,b)  a b, a*b}
34043 @r{    a b@:      /     @:             @:     2  @:div@:(a,b)  a/b}
34044 @r{    a b@:      ^     @:             @:     2  @:pow@:(a,b)  a^b}
34045 @r{    a b@:    I ^     @:             @:     2  @:nroot@:(a,b)  a^(1/b)}
34046 @r{    a b@:      %     @:             @:     2  @:mod@:(a,b)  a%b}
34047 @r{    a b@:      \     @:             @:     2  @:idiv@:(a,b)  a\b}
34048 @r{    a b@:      :     @:             @:     2  @:fdiv@:(a,b)}
34049 @r{    a b@:      |     @:             @:     2  @:vconcat@:(a,b)  a|b}
34050 @r{    a b@:    I |     @:             @:        @:vconcat@:(b,a)  b|a}
34051 @r{    a b@:    H |     @:             @:     2  @:append@:(a,b)}
34052 @r{    a b@:  I H |     @:             @:        @:append@:(b,a)}
34053 @r{      a@:      &     @:             @:     1  @:inv@:(a)  1/a}
34054 @r{      a@:      !     @:             @:     1  @:fact@:(a)  a!}
34055 @r{      a@:      =     @:             @:     1  @:evalv@:(a)}
34056 @r{      a@:      M-%   @:             @:        @:percent@:(a)  a%}
34058 @c 
34059 @r{  ... a@:      RET   @:             @:     1  @:@:... a a}
34060 @r{  ... a@:      SPC   @:             @:     1  @:@:... a a}
34061 @r{... a b@:      TAB   @:             @:     3  @:@:... b a}
34062 @r{. a b c@:      M-TAB @:             @:     3  @:@:... b c a}
34063 @r{... a b@:      LFD   @:             @:     1  @:@:... a b a}
34064 @r{  ... a@:      DEL   @:             @:     1  @:@:...}
34065 @r{... a b@:      M-DEL @:             @:     1  @:@:... b}
34066 @r{       @:      M-RET @:             @:     4  @:calc-last-args@:}
34067 @r{      a@:      `     @:editing      @:  1,30  @:calc-edit@:}
34069 @c 
34070 @r{  ... a@:      C-d   @:             @:     1  @:@:...}
34071 @r{       @:      C-k   @:             @:    27  @:calc-kill@:}
34072 @r{       @:      C-w   @:             @:    27  @:calc-kill-region@:}
34073 @r{       @:      C-y   @:             @:        @:calc-yank@:}
34074 @r{       @:      C-_   @:             @:     4  @:calc-undo@:}
34075 @r{       @:      M-k   @:             @:    27  @:calc-copy-as-kill@:}
34076 @r{       @:      M-w   @:             @:    27  @:calc-copy-region-as-kill@:}
34078 @c 
34079 @r{       @:      [     @:             @:        @:@:[...}
34080 @r{[.. a b@:      ]     @:             @:        @:@:[a,b]}
34081 @r{       @:      (     @:             @:        @:@:(...}
34082 @r{(.. a b@:      )     @:             @:        @:@:(a,b)}
34083 @r{       @:      ,     @:             @:        @:@:vector or rect complex}
34084 @r{       @:      ;     @:             @:        @:@:matrix or polar complex}
34085 @r{       @:      ..    @:             @:        @:@:interval}
34087 @c 
34088 @r{       @:      ~     @:             @:        @:calc-num-prefix@:}
34089 @r{       @:      <     @:             @:     4  @:calc-scroll-left@:}
34090 @r{       @:      >     @:             @:     4  @:calc-scroll-right@:}
34091 @r{       @:      @{     @:             @:     4  @:calc-scroll-down@:}
34092 @r{       @:      @}     @:             @:     4  @:calc-scroll-up@:}
34093 @r{       @:      ?     @:             @:        @:calc-help@:}
34095 @c 
34096 @r{      a@:      n     @:             @:     1  @:neg@:(a)  @minus{}a}
34097 @r{       @:      o     @:             @:     4  @:calc-realign@:}
34098 @r{       @:      p     @:precision    @:    31  @:calc-precision@:}
34099 @r{       @:      q     @:             @:        @:calc-quit@:}
34100 @r{       @:      w     @:             @:        @:calc-why@:}
34101 @r{       @:      x     @:command      @:        @:M-x calc-@:command}
34102 @r{      a@:      y     @:            @:1,28,49  @:calc-copy-to-buffer@:}
34104 @c 
34105 @r{      a@:      A     @:             @:     1  @:abs@:(a)}
34106 @r{    a b@:      B     @:             @:     2  @:log@:(a,b)}
34107 @r{    a b@:    I B     @:             @:     2  @:alog@:(a,b)  b^a}
34108 @r{      a@:      C     @:             @:     1  @:cos@:(a)}
34109 @r{      a@:    I C     @:             @:     1  @:arccos@:(a)}
34110 @r{      a@:    H C     @:             @:     1  @:cosh@:(a)}
34111 @r{      a@:  I H C     @:             @:     1  @:arccosh@:(a)}
34112 @r{       @:      D     @:             @:     4  @:calc-redo@:}
34113 @r{      a@:      E     @:             @:     1  @:exp@:(a)}
34114 @r{      a@:    H E     @:             @:     1  @:exp10@:(a)  10.^a}
34115 @r{      a@:      F     @:             @:  1,11  @:floor@:(a,d)}
34116 @r{      a@:    I F     @:             @:  1,11  @:ceil@:(a,d)}
34117 @r{      a@:    H F     @:             @:  1,11  @:ffloor@:(a,d)}
34118 @r{      a@:  I H F     @:             @:  1,11  @:fceil@:(a,d)}
34119 @r{      a@:      G     @:             @:     1  @:arg@:(a)}
34120 @r{       @:      H     @:command      @:    32  @:@:Hyperbolic}
34121 @r{       @:      I     @:command      @:    32  @:@:Inverse}
34122 @r{      a@:      J     @:             @:     1  @:conj@:(a)}
34123 @r{       @:      K     @:command      @:    32  @:@:Keep-args}
34124 @r{      a@:      L     @:             @:     1  @:ln@:(a)}
34125 @r{      a@:    H L     @:             @:     1  @:log10@:(a)}
34126 @r{       @:      M     @:             @:        @:calc-more-recursion-depth@:}
34127 @r{       @:    I M     @:             @:        @:calc-less-recursion-depth@:}
34128 @r{      a@:      N     @:             @:     5  @:evalvn@:(a)}
34129 @r{       @:      P     @:             @:        @:@:pi}
34130 @r{       @:    I P     @:             @:        @:@:gamma}
34131 @r{       @:    H P     @:             @:        @:@:e}
34132 @r{       @:  I H P     @:             @:        @:@:phi}
34133 @r{      a@:      Q     @:             @:     1  @:sqrt@:(a)}
34134 @r{      a@:    I Q     @:             @:     1  @:sqr@:(a)  a^2}
34135 @r{      a@:      R     @:             @:  1,11  @:round@:(a,d)}
34136 @r{      a@:    I R     @:             @:  1,11  @:trunc@:(a,d)}
34137 @r{      a@:    H R     @:             @:  1,11  @:fround@:(a,d)}
34138 @r{      a@:  I H R     @:             @:  1,11  @:ftrunc@:(a,d)}
34139 @r{      a@:      S     @:             @:     1  @:sin@:(a)}
34140 @r{      a@:    I S     @:             @:     1  @:arcsin@:(a)}
34141 @r{      a@:    H S     @:             @:     1  @:sinh@:(a)}
34142 @r{      a@:  I H S     @:             @:     1  @:arcsinh@:(a)}
34143 @r{      a@:      T     @:             @:     1  @:tan@:(a)}
34144 @r{      a@:    I T     @:             @:     1  @:arctan@:(a)}
34145 @r{      a@:    H T     @:             @:     1  @:tanh@:(a)}
34146 @r{      a@:  I H T     @:             @:     1  @:arctanh@:(a)}
34147 @r{       @:      U     @:             @:     4  @:calc-undo@:}
34148 @r{       @:      X     @:             @:     4  @:calc-call-last-kbd-macro@:}
34150 @c 
34151 @r{    a b@:      a =   @:             @:     2  @:eq@:(a,b)  a=b}
34152 @r{    a b@:      a #   @:             @:     2  @:neq@:(a,b)  a!=b}
34153 @r{    a b@:      a <   @:             @:     2  @:lt@:(a,b)  a<b}
34154 @r{    a b@:      a >   @:             @:     2  @:gt@:(a,b)  a>b}
34155 @r{    a b@:      a [   @:             @:     2  @:leq@:(a,b)  a<=b}
34156 @r{    a b@:      a ]   @:             @:     2  @:geq@:(a,b)  a>=b}
34157 @r{    a b@:      a @{   @:             @:     2  @:in@:(a,b)}
34158 @r{    a b@:      a &   @:             @:  2,45  @:land@:(a,b)  a&&b}
34159 @r{    a b@:      a |   @:             @:  2,45  @:lor@:(a,b)  a||b}
34160 @r{      a@:      a !   @:             @:  1,45  @:lnot@:(a)  !a}
34161 @r{  a b c@:      a :   @:             @:    45  @:if@:(a,b,c)  a?b:c}
34162 @r{      a@:      a .   @:             @:     1  @:rmeq@:(a)}
34163 @r{      a@:      a "   @:             @:   7,8  @:calc-expand-formula@:}
34165 @c 
34166 @r{      a@:      a +   @:i, l, h      @:  6,38  @:sum@:(a,i,l,h)}
34167 @r{      a@:      a -   @:i, l, h      @:  6,38  @:asum@:(a,i,l,h)}
34168 @r{      a@:      a *   @:i, l, h      @:  6,38  @:prod@:(a,i,l,h)}
34169 @r{    a b@:      a _   @:             @:     2  @:subscr@:(a,b)  a_b}
34171 @c 
34172 @r{    a b@:      a \   @:             @:     2  @:pdiv@:(a,b)}
34173 @r{    a b@:      a %   @:             @:     2  @:prem@:(a,b)}
34174 @r{    a b@:      a /   @:             @:     2  @:pdivrem@:(a,b)  [q,r]}
34175 @r{    a b@:    H a /   @:             @:     2  @:pdivide@:(a,b)  q+r/b}
34177 @c 
34178 @r{      a@:      a a   @:             @:     1  @:apart@:(a)}
34179 @r{      a@:      a b   @:old, new     @:    38  @:subst@:(a,old,new)}
34180 @r{      a@:      a c   @:v            @:    38  @:collect@:(a,v)}
34181 @r{      a@:      a d   @:v            @:  4,38  @:deriv@:(a,v)}
34182 @r{      a@:    H a d   @:v            @:  4,38  @:tderiv@:(a,v)}
34183 @r{      a@:      a e   @:             @:        @:esimplify@:(a)}
34184 @r{      a@:      a f   @:             @:     1  @:factor@:(a)}
34185 @r{      a@:    H a f   @:             @:     1  @:factors@:(a)}
34186 @r{    a b@:      a g   @:             @:     2  @:pgcd@:(a,b)}
34187 @r{      a@:      a i   @:v            @:    38  @:integ@:(a,v)}
34188 @r{      a@:      a m   @:pats         @:    38  @:match@:(a,pats)}
34189 @r{      a@:    I a m   @:pats         @:    38  @:matchnot@:(a,pats)}
34190 @r{ data x@:      a p   @:             @:    28  @:polint@:(data,x)}
34191 @r{ data x@:    H a p   @:             @:    28  @:ratint@:(data,x)}
34192 @r{      a@:      a n   @:             @:     1  @:nrat@:(a)}
34193 @r{      a@:      a r   @:rules        @:4,8,38  @:rewrite@:(a,rules,n)}
34194 @r{      a@:      a s   @:             @:        @:simplify@:(a)}
34195 @r{      a@:      a t   @:v, n         @: 31,39  @:taylor@:(a,v,n)}
34196 @r{      a@:      a v   @:             @:   7,8  @:calc-alg-evaluate@:}
34197 @r{      a@:      a x   @:             @:   4,8  @:expand@:(a)}
34199 @c 
34200 @r{   data@:      a F   @:model, vars  @:    48  @:fit@:(m,iv,pv,data)}
34201 @r{   data@:    I a F   @:model, vars  @:    48  @:xfit@:(m,iv,pv,data)}
34202 @r{   data@:    H a F   @:model, vars  @:    48  @:efit@:(m,iv,pv,data)}
34203 @r{      a@:      a I   @:v, l, h      @:    38  @:ninteg@:(a,v,l,h)}
34204 @r{    a b@:      a M   @:op           @:    22  @:mapeq@:(op,a,b)}
34205 @r{    a b@:    I a M   @:op           @:    22  @:mapeqr@:(op,a,b)}
34206 @r{    a b@:    H a M   @:op           @:    22  @:mapeqp@:(op,a,b)}
34207 @r{    a g@:      a N   @:v            @:    38  @:minimize@:(a,v,g)}
34208 @r{    a g@:    H a N   @:v            @:    38  @:wminimize@:(a,v,g)}
34209 @r{      a@:      a P   @:v            @:    38  @:roots@:(a,v)}
34210 @r{    a g@:      a R   @:v            @:    38  @:root@:(a,v,g)}
34211 @r{    a g@:    H a R   @:v            @:    38  @:wroot@:(a,v,g)}
34212 @r{      a@:      a S   @:v            @:    38  @:solve@:(a,v)}
34213 @r{      a@:    I a S   @:v            @:    38  @:finv@:(a,v)}
34214 @r{      a@:    H a S   @:v            @:    38  @:fsolve@:(a,v)}
34215 @r{      a@:  I H a S   @:v            @:    38  @:ffinv@:(a,v)}
34216 @r{      a@:      a T   @:i, l, h      @:  6,38  @:table@:(a,i,l,h)}
34217 @r{    a g@:      a X   @:v            @:    38  @:maximize@:(a,v,g)}
34218 @r{    a g@:    H a X   @:v            @:    38  @:wmaximize@:(a,v,g)}
34220 @c 
34221 @r{    a b@:      b a   @:             @:     9  @:and@:(a,b,w)}
34222 @r{      a@:      b c   @:             @:     9  @:clip@:(a,w)}
34223 @r{    a b@:      b d   @:             @:     9  @:diff@:(a,b,w)}
34224 @r{      a@:      b l   @:             @:    10  @:lsh@:(a,n,w)}
34225 @r{    a n@:    H b l   @:             @:     9  @:lsh@:(a,n,w)}
34226 @r{      a@:      b n   @:             @:     9  @:not@:(a,w)}
34227 @r{    a b@:      b o   @:             @:     9  @:or@:(a,b,w)}
34228 @r{      v@:      b p   @:             @:     1  @:vpack@:(v)}
34229 @r{      a@:      b r   @:             @:    10  @:rsh@:(a,n,w)}
34230 @r{    a n@:    H b r   @:             @:     9  @:rsh@:(a,n,w)}
34231 @r{      a@:      b t   @:             @:    10  @:rot@:(a,n,w)}
34232 @r{    a n@:    H b t   @:             @:     9  @:rot@:(a,n,w)}
34233 @r{      a@:      b u   @:             @:     1  @:vunpack@:(a)}
34234 @r{       @:      b w   @:w            @:  9,50  @:calc-word-size@:}
34235 @r{    a b@:      b x   @:             @:     9  @:xor@:(a,b,w)}
34237 @c 
34238 @r{c s l p@:      b D   @:             @:        @:ddb@:(c,s,l,p)}
34239 @r{  r n p@:      b F   @:             @:        @:fv@:(r,n,p)}
34240 @r{  r n p@:    I b F   @:             @:        @:fvb@:(r,n,p)}
34241 @r{  r n p@:    H b F   @:             @:        @:fvl@:(r,n,p)}
34242 @r{      v@:      b I   @:             @:    19  @:irr@:(v)}
34243 @r{      v@:    I b I   @:             @:    19  @:irrb@:(v)}
34244 @r{      a@:      b L   @:             @:    10  @:ash@:(a,n,w)}
34245 @r{    a n@:    H b L   @:             @:     9  @:ash@:(a,n,w)}
34246 @r{  r n a@:      b M   @:             @:        @:pmt@:(r,n,a)}
34247 @r{  r n a@:    I b M   @:             @:        @:pmtb@:(r,n,a)}
34248 @r{  r n a@:    H b M   @:             @:        @:pmtl@:(r,n,a)}
34249 @r{    r v@:      b N   @:             @:    19  @:npv@:(r,v)}
34250 @r{    r v@:    I b N   @:             @:    19  @:npvb@:(r,v)}
34251 @r{  r n p@:      b P   @:             @:        @:pv@:(r,n,p)}
34252 @r{  r n p@:    I b P   @:             @:        @:pvb@:(r,n,p)}
34253 @r{  r n p@:    H b P   @:             @:        @:pvl@:(r,n,p)}
34254 @r{      a@:      b R   @:             @:    10  @:rash@:(a,n,w)}
34255 @r{    a n@:    H b R   @:             @:     9  @:rash@:(a,n,w)}
34256 @r{  c s l@:      b S   @:             @:        @:sln@:(c,s,l)}
34257 @r{  n p a@:      b T   @:             @:        @:rate@:(n,p,a)}
34258 @r{  n p a@:    I b T   @:             @:        @:rateb@:(n,p,a)}
34259 @r{  n p a@:    H b T   @:             @:        @:ratel@:(n,p,a)}
34260 @r{c s l p@:      b Y   @:             @:        @:syd@:(c,s,l,p)}
34262 @r{  r p a@:      b #   @:             @:        @:nper@:(r,p,a)}
34263 @r{  r p a@:    I b #   @:             @:        @:nperb@:(r,p,a)}
34264 @r{  r p a@:    H b #   @:             @:        @:nperl@:(r,p,a)}
34265 @r{    a b@:      b %   @:             @:        @:relch@:(a,b)}
34267 @c 
34268 @r{      a@:      c c   @:             @:     5  @:pclean@:(a,p)}
34269 @r{      a@:      c 0-9 @:             @:        @:pclean@:(a,p)}
34270 @r{      a@:    H c c   @:             @:     5  @:clean@:(a,p)}
34271 @r{      a@:    H c 0-9 @:             @:        @:clean@:(a,p)}
34272 @r{      a@:      c d   @:             @:     1  @:deg@:(a)}
34273 @r{      a@:      c f   @:             @:     1  @:pfloat@:(a)}
34274 @r{      a@:    H c f   @:             @:     1  @:float@:(a)}
34275 @r{      a@:      c h   @:             @:     1  @:hms@:(a)}
34276 @r{      a@:      c p   @:             @:        @:polar@:(a)}
34277 @r{      a@:    I c p   @:             @:        @:rect@:(a)}
34278 @r{      a@:      c r   @:             @:     1  @:rad@:(a)}
34280 @c 
34281 @r{      a@:      c F   @:             @:     5  @:pfrac@:(a,p)}
34282 @r{      a@:    H c F   @:             @:     5  @:frac@:(a,p)}
34284 @c 
34285 @r{      a@:      c %   @:             @:        @:percent@:(a*100)}
34287 @c 
34288 @r{       @:      d .   @:char         @:    50  @:calc-point-char@:}
34289 @r{       @:      d ,   @:char         @:    50  @:calc-group-char@:}
34290 @r{       @:      d <   @:             @: 13,50  @:calc-left-justify@:}
34291 @r{       @:      d =   @:             @: 13,50  @:calc-center-justify@:}
34292 @r{       @:      d >   @:             @: 13,50  @:calc-right-justify@:}
34293 @r{       @:      d @{   @:label        @:    50  @:calc-left-label@:}
34294 @r{       @:      d @}   @:label        @:    50  @:calc-right-label@:}
34295 @r{       @:      d [   @:             @:     4  @:calc-truncate-up@:}
34296 @r{       @:      d ]   @:             @:     4  @:calc-truncate-down@:}
34297 @r{       @:      d "   @:             @: 12,50  @:calc-display-strings@:}
34298 @r{       @:      d SPC @:             @:        @:calc-refresh@:}
34299 @r{       @:      d RET @:             @:     1  @:calc-refresh-top@:}
34301 @c 
34302 @r{       @:      d 0   @:             @:    50  @:calc-decimal-radix@:}
34303 @r{       @:      d 2   @:             @:    50  @:calc-binary-radix@:}
34304 @r{       @:      d 6   @:             @:    50  @:calc-hex-radix@:}
34305 @r{       @:      d 8   @:             @:    50  @:calc-octal-radix@:}
34307 @c 
34308 @r{       @:      d b   @:           @:12,13,50  @:calc-line-breaking@:}
34309 @r{       @:      d c   @:             @:    50  @:calc-complex-notation@:}
34310 @r{       @:      d d   @:format       @:    50  @:calc-date-notation@:}
34311 @r{       @:      d e   @:             @:  5,50  @:calc-eng-notation@:}
34312 @r{       @:      d f   @:num          @: 31,50  @:calc-fix-notation@:}
34313 @r{       @:      d g   @:           @:12,13,50  @:calc-group-digits@:}
34314 @r{       @:      d h   @:format       @:    50  @:calc-hms-notation@:}
34315 @r{       @:      d i   @:             @:    50  @:calc-i-notation@:}
34316 @r{       @:      d j   @:             @:    50  @:calc-j-notation@:}
34317 @r{       @:      d l   @:             @: 12,50  @:calc-line-numbering@:}
34318 @r{       @:      d n   @:             @:  5,50  @:calc-normal-notation@:}
34319 @r{       @:      d o   @:format       @:    50  @:calc-over-notation@:}
34320 @r{       @:      d p   @:             @: 12,50  @:calc-show-plain@:}
34321 @r{       @:      d r   @:radix        @: 31,50  @:calc-radix@:}
34322 @r{       @:      d s   @:             @:  5,50  @:calc-sci-notation@:}
34323 @r{       @:      d t   @:             @:    27  @:calc-truncate-stack@:}
34324 @r{       @:      d w   @:             @: 12,13  @:calc-auto-why@:}
34325 @r{       @:      d z   @:             @: 12,50  @:calc-leading-zeros@:}
34327 @c 
34328 @r{       @:      d B   @:             @:    50  @:calc-big-language@:}
34329 @r{       @:      d C   @:             @:    50  @:calc-c-language@:}
34330 @r{       @:      d E   @:             @:    50  @:calc-eqn-language@:}
34331 @r{       @:      d F   @:             @:    50  @:calc-fortran-language@:}
34332 @r{       @:      d M   @:             @:    50  @:calc-mathematica-language@:}
34333 @r{       @:      d N   @:             @:    50  @:calc-normal-language@:}
34334 @r{       @:      d O   @:             @:    50  @:calc-flat-language@:}
34335 @r{       @:      d P   @:             @:    50  @:calc-pascal-language@:}
34336 @r{       @:      d T   @:             @:    50  @:calc-tex-language@:}
34337 @r{       @:      d U   @:             @:    50  @:calc-unformatted-language@:}
34338 @r{       @:      d W   @:             @:    50  @:calc-maple-language@:}
34340 @c 
34341 @r{      a@:      f [   @:             @:     4  @:decr@:(a,n)}
34342 @r{      a@:      f ]   @:             @:     4  @:incr@:(a,n)}
34344 @c 
34345 @r{    a b@:      f b   @:             @:     2  @:beta@:(a,b)}
34346 @r{      a@:      f e   @:             @:     1  @:erf@:(a)}
34347 @r{      a@:    I f e   @:             @:     1  @:erfc@:(a)}
34348 @r{      a@:      f g   @:             @:     1  @:gamma@:(a)}
34349 @r{    a b@:      f h   @:             @:     2  @:hypot@:(a,b)}
34350 @r{      a@:      f i   @:             @:     1  @:im@:(a)}
34351 @r{    n a@:      f j   @:             @:     2  @:besJ@:(n,a)}
34352 @r{    a b@:      f n   @:             @:     2  @:min@:(a,b)}
34353 @r{      a@:      f r   @:             @:     1  @:re@:(a)}
34354 @r{      a@:      f s   @:             @:     1  @:sign@:(a)}
34355 @r{    a b@:      f x   @:             @:     2  @:max@:(a,b)}
34356 @r{    n a@:      f y   @:             @:     2  @:besY@:(n,a)}
34358 @c 
34359 @r{      a@:      f A   @:             @:     1  @:abssqr@:(a)}
34360 @r{  x a b@:      f B   @:             @:        @:betaI@:(x,a,b)}
34361 @r{  x a b@:    H f B   @:             @:        @:betaB@:(x,a,b)}
34362 @r{      a@:      f E   @:             @:     1  @:expm1@:(a)}
34363 @r{    a x@:      f G   @:             @:     2  @:gammaP@:(a,x)}
34364 @r{    a x@:    I f G   @:             @:     2  @:gammaQ@:(a,x)}
34365 @r{    a x@:    H f G   @:             @:     2  @:gammag@:(a,x)}
34366 @r{    a x@:  I H f G   @:             @:     2  @:gammaG@:(a,x)}
34367 @r{    a b@:      f I   @:             @:     2  @:ilog@:(a,b)}
34368 @r{    a b@:    I f I   @:             @:     2  @:alog@:(a,b)  b^a}
34369 @r{      a@:      f L   @:             @:     1  @:lnp1@:(a)}
34370 @r{      a@:      f M   @:             @:     1  @:mant@:(a)}
34371 @r{      a@:      f Q   @:             @:     1  @:isqrt@:(a)}
34372 @r{      a@:    I f Q   @:             @:     1  @:sqr@:(a)  a^2}
34373 @r{    a n@:      f S   @:             @:     2  @:scf@:(a,n)}
34374 @r{    y x@:      f T   @:             @:        @:arctan2@:(y,x)}
34375 @r{      a@:      f X   @:             @:     1  @:xpon@:(a)}
34377 @c 
34378 @r{    x y@:      g a   @:             @: 28,40  @:calc-graph-add@:}
34379 @r{       @:      g b   @:             @:    12  @:calc-graph-border@:}
34380 @r{       @:      g c   @:             @:        @:calc-graph-clear@:}
34381 @r{       @:      g d   @:             @:    41  @:calc-graph-delete@:}
34382 @r{    x y@:      g f   @:             @: 28,40  @:calc-graph-fast@:}
34383 @r{       @:      g g   @:             @:    12  @:calc-graph-grid@:}
34384 @r{       @:      g h   @:title        @:        @:calc-graph-header@:}
34385 @r{       @:      g j   @:             @:     4  @:calc-graph-juggle@:}
34386 @r{       @:      g k   @:             @:    12  @:calc-graph-key@:}
34387 @r{       @:      g l   @:             @:    12  @:calc-graph-log-x@:}
34388 @r{       @:      g n   @:name         @:        @:calc-graph-name@:}
34389 @r{       @:      g p   @:             @:    42  @:calc-graph-plot@:}
34390 @r{       @:      g q   @:             @:        @:calc-graph-quit@:}
34391 @r{       @:      g r   @:range        @:        @:calc-graph-range-x@:}
34392 @r{       @:      g s   @:             @: 12,13  @:calc-graph-line-style@:}
34393 @r{       @:      g t   @:title        @:        @:calc-graph-title-x@:}
34394 @r{       @:      g v   @:             @:        @:calc-graph-view-commands@:}
34395 @r{       @:      g x   @:display      @:        @:calc-graph-display@:}
34396 @r{       @:      g z   @:             @:    12  @:calc-graph-zero-x@:}
34398 @c 
34399 @r{  x y z@:      g A   @:             @: 28,40  @:calc-graph-add-3d@:}
34400 @r{       @:      g C   @:command      @:        @:calc-graph-command@:}
34401 @r{       @:      g D   @:device       @: 43,44  @:calc-graph-device@:}
34402 @r{  x y z@:      g F   @:             @: 28,40  @:calc-graph-fast-3d@:}
34403 @r{       @:      g H   @:             @:    12  @:calc-graph-hide@:}
34404 @r{       @:      g K   @:             @:        @:calc-graph-kill@:}
34405 @r{       @:      g L   @:             @:    12  @:calc-graph-log-y@:}
34406 @r{       @:      g N   @:number       @: 43,51  @:calc-graph-num-points@:}
34407 @r{       @:      g O   @:filename     @: 43,44  @:calc-graph-output@:}
34408 @r{       @:      g P   @:             @:    42  @:calc-graph-print@:}
34409 @r{       @:      g R   @:range        @:        @:calc-graph-range-y@:}
34410 @r{       @:      g S   @:             @: 12,13  @:calc-graph-point-style@:}
34411 @r{       @:      g T   @:title        @:        @:calc-graph-title-y@:}
34412 @r{       @:      g V   @:             @:        @:calc-graph-view-trail@:}
34413 @r{       @:      g X   @:format       @:        @:calc-graph-geometry@:}
34414 @r{       @:      g Z   @:             @:    12  @:calc-graph-zero-y@:}
34416 @c 
34417 @r{       @:      g C-l @:             @:    12  @:calc-graph-log-z@:}
34418 @r{       @:      g C-r @:range        @:        @:calc-graph-range-z@:}
34419 @r{       @:      g C-t @:title        @:        @:calc-graph-title-z@:}
34421 @c 
34422 @r{       @:      h b   @:             @:        @:calc-describe-bindings@:}
34423 @r{       @:      h c   @:key          @:        @:calc-describe-key-briefly@:}
34424 @r{       @:      h f   @:function     @:        @:calc-describe-function@:}
34425 @r{       @:      h h   @:             @:        @:calc-full-help@:}
34426 @r{       @:      h i   @:             @:        @:calc-info@:}
34427 @r{       @:      h k   @:key          @:        @:calc-describe-key@:}
34428 @r{       @:      h n   @:             @:        @:calc-view-news@:}
34429 @r{       @:      h s   @:             @:        @:calc-info-summary@:}
34430 @r{       @:      h t   @:             @:        @:calc-tutorial@:}
34431 @r{       @:      h v   @:var          @:        @:calc-describe-variable@:}
34433 @c 
34434 @r{       @:      j 1-9 @:             @:        @:calc-select-part@:}
34435 @r{       @:      j RET @:             @:    27  @:calc-copy-selection@:}
34436 @r{       @:      j DEL @:             @:    27  @:calc-del-selection@:}
34437 @r{       @:      j '   @:formula      @:    27  @:calc-enter-selection@:}
34438 @r{       @:      j `   @:editing      @: 27,30  @:calc-edit-selection@:}
34439 @r{       @:      j "   @:             @:  7,27  @:calc-sel-expand-formula@:}
34441 @c 
34442 @r{       @:      j +   @:formula      @:    27  @:calc-sel-add-both-sides@:}
34443 @r{       @:      j -   @:formula      @:    27  @:calc-sel-sub-both-sides@:}
34444 @r{       @:      j *   @:formula      @:    27  @:calc-sel-mul-both-sides@:}
34445 @r{       @:      j /   @:formula      @:    27  @:calc-sel-div-both-sides@:}
34446 @r{       @:      j &   @:             @:    27  @:calc-sel-invert@:}
34448 @c 
34449 @r{       @:      j a   @:             @:    27  @:calc-select-additional@:}
34450 @r{       @:      j b   @:             @:    12  @:calc-break-selections@:}
34451 @r{       @:      j c   @:             @:        @:calc-clear-selections@:}
34452 @r{       @:      j d   @:             @: 12,50  @:calc-show-selections@:}
34453 @r{       @:      j e   @:             @:    12  @:calc-enable-selections@:}
34454 @r{       @:      j l   @:             @:  4,27  @:calc-select-less@:}
34455 @r{       @:      j m   @:             @:  4,27  @:calc-select-more@:}
34456 @r{       @:      j n   @:             @:     4  @:calc-select-next@:}
34457 @r{       @:      j o   @:             @:  4,27  @:calc-select-once@:}
34458 @r{       @:      j p   @:             @:     4  @:calc-select-previous@:}
34459 @r{       @:      j r   @:rules        @:4,8,27  @:calc-rewrite-selection@:}
34460 @r{       @:      j s   @:             @:  4,27  @:calc-select-here@:}
34461 @r{       @:      j u   @:             @:    27  @:calc-unselect@:}
34462 @r{       @:      j v   @:             @:  7,27  @:calc-sel-evaluate@:}
34464 @c 
34465 @r{       @:      j C   @:             @:    27  @:calc-sel-commute@:}
34466 @r{       @:      j D   @:             @:  4,27  @:calc-sel-distribute@:}
34467 @r{       @:      j E   @:             @:    27  @:calc-sel-jump-equals@:}
34468 @r{       @:      j I   @:             @:    27  @:calc-sel-isolate@:}
34469 @r{       @:    H j I   @:             @:    27  @:calc-sel-isolate@: (full)}
34470 @r{       @:      j L   @:             @:  4,27  @:calc-commute-left@:}
34471 @r{       @:      j M   @:             @:    27  @:calc-sel-merge@:}
34472 @r{       @:      j N   @:             @:    27  @:calc-sel-negate@:}
34473 @r{       @:      j O   @:             @:  4,27  @:calc-select-once-maybe@:}
34474 @r{       @:      j R   @:             @:  4,27  @:calc-commute-right@:}
34475 @r{       @:      j S   @:             @:  4,27  @:calc-select-here-maybe@:}
34476 @r{       @:      j U   @:             @:    27  @:calc-sel-unpack@:}
34478 @c 
34479 @r{       @:      k a   @:             @:        @:calc-random-again@:}
34480 @r{      n@:      k b   @:             @:     1  @:bern@:(n)}
34481 @r{    n x@:    H k b   @:             @:     2  @:bern@:(n,x)}
34482 @r{    n m@:      k c   @:             @:     2  @:choose@:(n,m)}
34483 @r{    n m@:    H k c   @:             @:     2  @:perm@:(n,m)}
34484 @r{      n@:      k d   @:             @:     1  @:dfact@:(n)  n!!}
34485 @r{      n@:      k e   @:             @:     1  @:euler@:(n)}
34486 @r{    n x@:    H k e   @:             @:     2  @:euler@:(n,x)}
34487 @r{      n@:      k f   @:             @:     4  @:prfac@:(n)}
34488 @r{    n m@:      k g   @:             @:     2  @:gcd@:(n,m)}
34489 @r{    m n@:      k h   @:             @:    14  @:shuffle@:(n,m)}
34490 @r{    n m@:      k l   @:             @:     2  @:lcm@:(n,m)}
34491 @r{      n@:      k m   @:             @:     1  @:moebius@:(n)}
34492 @r{      n@:      k n   @:             @:     4  @:nextprime@:(n)}
34493 @r{      n@:    I k n   @:             @:     4  @:prevprime@:(n)}
34494 @r{      n@:      k p   @:             @:  4,28  @:calc-prime-test@:}
34495 @r{      m@:      k r   @:             @:    14  @:random@:(m)}
34496 @r{    n m@:      k s   @:             @:     2  @:stir1@:(n,m)}
34497 @r{    n m@:    H k s   @:             @:     2  @:stir2@:(n,m)}
34498 @r{      n@:      k t   @:             @:     1  @:totient@:(n)}
34500 @c 
34501 @r{  n p x@:      k B   @:             @:        @:utpb@:(x,n,p)}
34502 @r{  n p x@:    I k B   @:             @:        @:ltpb@:(x,n,p)}
34503 @r{    v x@:      k C   @:             @:        @:utpc@:(x,v)}
34504 @r{    v x@:    I k C   @:             @:        @:ltpc@:(x,v)}
34505 @r{    n m@:      k E   @:             @:        @:egcd@:(n,m)}
34506 @r{v1 v2 x@:      k F   @:             @:        @:utpf@:(x,v1,v2)}
34507 @r{v1 v2 x@:    I k F   @:             @:        @:ltpf@:(x,v1,v2)}
34508 @r{  m s x@:      k N   @:             @:        @:utpn@:(x,m,s)}
34509 @r{  m s x@:    I k N   @:             @:        @:ltpn@:(x,m,s)}
34510 @r{    m x@:      k P   @:             @:        @:utpp@:(x,m)}
34511 @r{    m x@:    I k P   @:             @:        @:ltpp@:(x,m)}
34512 @r{    v x@:      k T   @:             @:        @:utpt@:(x,v)}
34513 @r{    v x@:    I k T   @:             @:        @:ltpt@:(x,v)}
34515 @c 
34516 @r{       @:      m a   @:             @: 12,13  @:calc-algebraic-mode@:}
34517 @r{       @:      m d   @:             @:        @:calc-degrees-mode@:}
34518 @r{       @:      m f   @:             @:    12  @:calc-frac-mode@:}
34519 @r{       @:      m g   @:             @:    52  @:calc-get-modes@:}
34520 @r{       @:      m h   @:             @:        @:calc-hms-mode@:}
34521 @r{       @:      m i   @:             @: 12,13  @:calc-infinite-mode@:}
34522 @r{       @:      m m   @:             @:        @:calc-save-modes@:}
34523 @r{       @:      m p   @:             @:    12  @:calc-polar-mode@:}
34524 @r{       @:      m r   @:             @:        @:calc-radians-mode@:}
34525 @r{       @:      m s   @:             @:    12  @:calc-symbolic-mode@:}
34526 @r{       @:      m t   @:             @:    12  @:calc-total-algebraic-mode@:}
34527 @r{       @:      m v   @:             @: 12,13  @:calc-matrix-mode@:}
34528 @r{       @:      m w   @:             @:    13  @:calc-working@:}
34529 @r{       @:      m x   @:             @:        @:calc-always-load-extensions@:}
34531 @c 
34532 @r{       @:      m A   @:             @:    12  @:calc-alg-simplify-mode@:}
34533 @r{       @:      m B   @:             @:    12  @:calc-bin-simplify-mode@:}
34534 @r{       @:      m C   @:             @:    12  @:calc-auto-recompute@:}
34535 @r{       @:      m D   @:             @:        @:calc-default-simplify-mode@:}
34536 @r{       @:      m E   @:             @:    12  @:calc-ext-simplify-mode@:}
34537 @r{       @:      m F   @:filename     @:    13  @:calc-settings-file-name@:}
34538 @r{       @:      m N   @:             @:    12  @:calc-num-simplify-mode@:}
34539 @r{       @:      m O   @:             @:    12  @:calc-no-simplify-mode@:}
34540 @r{       @:      m R   @:             @: 12,13  @:calc-mode-record-mode@:}
34541 @r{       @:      m S   @:             @:    12  @:calc-shift-prefix@:}
34542 @r{       @:      m U   @:             @:    12  @:calc-units-simplify-mode@:}
34544 @c 
34545 @r{       @:      s c   @:var1, var2   @:    29  @:calc-copy-variable@:}
34546 @r{       @:      s d   @:var, decl    @:        @:calc-declare-variable@:}
34547 @r{       @:      s e   @:var, editing @: 29,30  @:calc-edit-variable@:}
34548 @r{       @:      s i   @:buffer       @:        @:calc-insert-variables@:}
34549 @r{    a b@:      s l   @:var          @:    29  @:@:a  (letting var=b)}
34550 @r{  a ...@:      s m   @:op, var      @: 22,29  @:calc-store-map@:}
34551 @r{       @:      s n   @:var          @: 29,47  @:calc-store-neg@:  (v/-1)}
34552 @r{       @:      s p   @:var          @:    29  @:calc-permanent-variable@:}
34553 @r{       @:      s r   @:var          @:    29  @:@:v  (recalled value)}
34554 @r{       @:      r 0-9 @:             @:        @:calc-recall-quick@:}
34555 @r{      a@:      s s   @:var          @: 28,29  @:calc-store@:}
34556 @r{      a@:      s 0-9 @:             @:        @:calc-store-quick@:}
34557 @r{      a@:      s t   @:var          @:    29  @:calc-store-into@:}
34558 @r{      a@:      t 0-9 @:             @:        @:calc-store-into-quick@:}
34559 @r{       @:      s u   @:var          @:    29  @:calc-unstore@:}
34560 @r{      a@:      s x   @:var          @:    29  @:calc-store-exchange@:}
34562 @c 
34563 @r{       @:      s A   @:editing      @:    30  @:calc-edit-AlgSimpRules@:}
34564 @r{       @:      s D   @:editing      @:    30  @:calc-edit-Decls@:}
34565 @r{       @:      s E   @:editing      @:    30  @:calc-edit-EvalRules@:}
34566 @r{       @:      s F   @:editing      @:    30  @:calc-edit-FitRules@:}
34567 @r{       @:      s G   @:editing      @:    30  @:calc-edit-GenCount@:}
34568 @r{       @:      s H   @:editing      @:    30  @:calc-edit-Holidays@:}
34569 @r{       @:      s I   @:editing      @:    30  @:calc-edit-IntegLimit@:}
34570 @r{       @:      s L   @:editing      @:    30  @:calc-edit-LineStyles@:}
34571 @r{       @:      s P   @:editing      @:    30  @:calc-edit-PointStyles@:}
34572 @r{       @:      s R   @:editing      @:    30  @:calc-edit-PlotRejects@:}
34573 @r{       @:      s T   @:editing      @:    30  @:calc-edit-TimeZone@:}
34574 @r{       @:      s U   @:editing      @:    30  @:calc-edit-Units@:}
34575 @r{       @:      s X   @:editing      @:    30  @:calc-edit-ExtSimpRules@:}
34577 @c 
34578 @r{      a@:      s +   @:var          @: 29,47  @:calc-store-plus@:  (v+a)}
34579 @r{      a@:      s -   @:var          @: 29,47  @:calc-store-minus@:  (v-a)}
34580 @r{      a@:      s *   @:var          @: 29,47  @:calc-store-times@:  (v*a)}
34581 @r{      a@:      s /   @:var          @: 29,47  @:calc-store-div@:  (v/a)}
34582 @r{      a@:      s ^   @:var          @: 29,47  @:calc-store-power@:  (v^a)}
34583 @r{      a@:      s |   @:var          @: 29,47  @:calc-store-concat@:  (v|a)}
34584 @r{       @:      s &   @:var          @: 29,47  @:calc-store-inv@:  (v^-1)}
34585 @r{       @:      s [   @:var          @: 29,47  @:calc-store-decr@:  (v-1)}
34586 @r{       @:      s ]   @:var          @: 29,47  @:calc-store-incr@:  (v-(-1))}
34587 @r{    a b@:      s :   @:             @:     2  @:assign@:(a,b)  a @t{:=} b}
34588 @r{      a@:      s =   @:             @:     1  @:evalto@:(a,b)  a @t{=>}}
34590 @c 
34591 @r{       @:      t [   @:             @:     4  @:calc-trail-first@:}
34592 @r{       @:      t ]   @:             @:     4  @:calc-trail-last@:}
34593 @r{       @:      t <   @:             @:     4  @:calc-trail-scroll-left@:}
34594 @r{       @:      t >   @:             @:     4  @:calc-trail-scroll-right@:}
34595 @r{       @:      t .   @:             @:    12  @:calc-full-trail-vectors@:}
34597 @c 
34598 @r{       @:      t b   @:             @:     4  @:calc-trail-backward@:}
34599 @r{       @:      t d   @:             @: 12,50  @:calc-trail-display@:}
34600 @r{       @:      t f   @:             @:     4  @:calc-trail-forward@:}
34601 @r{       @:      t h   @:             @:        @:calc-trail-here@:}
34602 @r{       @:      t i   @:             @:        @:calc-trail-in@:}
34603 @r{       @:      t k   @:             @:     4  @:calc-trail-kill@:}
34604 @r{       @:      t m   @:string       @:        @:calc-trail-marker@:}
34605 @r{       @:      t n   @:             @:     4  @:calc-trail-next@:}
34606 @r{       @:      t o   @:             @:        @:calc-trail-out@:}
34607 @r{       @:      t p   @:             @:     4  @:calc-trail-previous@:}
34608 @r{       @:      t r   @:string       @:        @:calc-trail-isearch-backward@:}
34609 @r{       @:      t s   @:string       @:        @:calc-trail-isearch-forward@:}
34610 @r{       @:      t y   @:             @:     4  @:calc-trail-yank@:}
34612 @c 
34613 @r{      d@:      t C   @:oz, nz       @:        @:tzconv@:(d,oz,nz)}
34614 @r{d oz nz@:      t C   @:$            @:        @:tzconv@:(d,oz,nz)}
34615 @r{      d@:      t D   @:             @:    15  @:date@:(d)}
34616 @r{      d@:      t I   @:             @:     4  @:incmonth@:(d,n)}
34617 @r{      d@:      t J   @:             @:    16  @:julian@:(d,z)}
34618 @r{      d@:      t M   @:             @:    17  @:newmonth@:(d,n)}
34619 @r{       @:      t N   @:             @:    16  @:now@:(z)}
34620 @r{      d@:      t P   @:1            @:    31  @:year@:(d)}
34621 @r{      d@:      t P   @:2            @:    31  @:month@:(d)}
34622 @r{      d@:      t P   @:3            @:    31  @:day@:(d)}
34623 @r{      d@:      t P   @:4            @:    31  @:hour@:(d)}
34624 @r{      d@:      t P   @:5            @:    31  @:minute@:(d)}
34625 @r{      d@:      t P   @:6            @:    31  @:second@:(d)}
34626 @r{      d@:      t P   @:7            @:    31  @:weekday@:(d)}
34627 @r{      d@:      t P   @:8            @:    31  @:yearday@:(d)}
34628 @r{      d@:      t P   @:9            @:    31  @:time@:(d)}
34629 @r{      d@:      t U   @:             @:    16  @:unixtime@:(d,z)}
34630 @r{      d@:      t W   @:             @:    17  @:newweek@:(d,w)}
34631 @r{      d@:      t Y   @:             @:    17  @:newyear@:(d,n)}
34633 @c 
34634 @r{    a b@:      t +   @:             @:     2  @:badd@:(a,b)}
34635 @r{    a b@:      t -   @:             @:     2  @:bsub@:(a,b)}
34637 @c 
34638 @r{       @:      u a   @:             @:    12  @:calc-autorange-units@:}
34639 @r{      a@:      u b   @:             @:        @:calc-base-units@:}
34640 @r{      a@:      u c   @:units        @:    18  @:calc-convert-units@:}
34641 @r{   defn@:      u d   @:unit, descr  @:        @:calc-define-unit@:}
34642 @r{       @:      u e   @:             @:        @:calc-explain-units@:}
34643 @r{       @:      u g   @:unit         @:        @:calc-get-unit-definition@:}
34644 @r{       @:      u p   @:             @:        @:calc-permanent-units@:}
34645 @r{      a@:      u r   @:             @:        @:calc-remove-units@:}
34646 @r{      a@:      u s   @:             @:        @:usimplify@:(a)}
34647 @r{      a@:      u t   @:units        @:    18  @:calc-convert-temperature@:}
34648 @r{       @:      u u   @:unit         @:        @:calc-undefine-unit@:}
34649 @r{       @:      u v   @:             @:        @:calc-enter-units-table@:}
34650 @r{      a@:      u x   @:             @:        @:calc-extract-units@:}
34651 @r{      a@:      u 0-9 @:             @:        @:calc-quick-units@:}
34653 @c 
34654 @r{  v1 v2@:      u C   @:             @:    20  @:vcov@:(v1,v2)}
34655 @r{  v1 v2@:    I u C   @:             @:    20  @:vpcov@:(v1,v2)}
34656 @r{  v1 v2@:    H u C   @:             @:    20  @:vcorr@:(v1,v2)}
34657 @r{      v@:      u G   @:             @:    19  @:vgmean@:(v)}
34658 @r{    a b@:    H u G   @:             @:     2  @:agmean@:(a,b)}
34659 @r{      v@:      u M   @:             @:    19  @:vmean@:(v)}
34660 @r{      v@:    I u M   @:             @:    19  @:vmeane@:(v)}
34661 @r{      v@:    H u M   @:             @:    19  @:vmedian@:(v)}
34662 @r{      v@:  I H u M   @:             @:    19  @:vhmean@:(v)}
34663 @r{      v@:      u N   @:             @:    19  @:vmin@:(v)}
34664 @r{      v@:      u S   @:             @:    19  @:vsdev@:(v)}
34665 @r{      v@:    I u S   @:             @:    19  @:vpsdev@:(v)}
34666 @r{      v@:    H u S   @:             @:    19  @:vvar@:(v)}
34667 @r{      v@:  I H u S   @:             @:    19  @:vpvar@:(v)}
34668 @r{       @:      u V   @:             @:        @:calc-view-units-table@:}
34669 @r{      v@:      u X   @:             @:    19  @:vmax@:(v)}
34671 @c 
34672 @r{      v@:      u +   @:             @:    19  @:vsum@:(v)}
34673 @r{      v@:      u *   @:             @:    19  @:vprod@:(v)}
34674 @r{      v@:      u #   @:             @:    19  @:vcount@:(v)}
34676 @c 
34677 @r{       @:      V (   @:             @:    50  @:calc-vector-parens@:}
34678 @r{       @:      V @{   @:             @:    50  @:calc-vector-braces@:}
34679 @r{       @:      V [   @:             @:    50  @:calc-vector-brackets@:}
34680 @r{       @:      V ]   @:ROCP         @:    50  @:calc-matrix-brackets@:}
34681 @r{       @:      V ,   @:             @:    50  @:calc-vector-commas@:}
34682 @r{       @:      V <   @:             @:    50  @:calc-matrix-left-justify@:}
34683 @r{       @:      V =   @:             @:    50  @:calc-matrix-center-justify@:}
34684 @r{       @:      V >   @:             @:    50  @:calc-matrix-right-justify@:}
34685 @r{       @:      V /   @:             @: 12,50  @:calc-break-vectors@:}
34686 @r{       @:      V .   @:             @: 12,50  @:calc-full-vectors@:}
34688 @c 
34689 @r{    s t@:      V ^   @:             @:     2  @:vint@:(s,t)}
34690 @r{    s t@:      V -   @:             @:     2  @:vdiff@:(s,t)}
34691 @r{      s@:      V ~   @:             @:     1  @:vcompl@:(s)}
34692 @r{      s@:      V #   @:             @:     1  @:vcard@:(s)}
34693 @r{      s@:      V :   @:             @:     1  @:vspan@:(s)}
34694 @r{      s@:      V +   @:             @:     1  @:rdup@:(s)}
34696 @c 
34697 @r{      m@:      V &   @:             @:     1  @:inv@:(m)  1/m}
34699 @c 
34700 @r{      v@:      v a   @:n            @:        @:arrange@:(v,n)}
34701 @r{      a@:      v b   @:n            @:        @:cvec@:(a,n)}
34702 @r{      v@:      v c   @:n >0         @: 21,31  @:mcol@:(v,n)}
34703 @r{      v@:      v c   @:n <0         @:    31  @:mrcol@:(v,-n)}
34704 @r{      m@:      v c   @:0            @:    31  @:getdiag@:(m)}
34705 @r{      v@:      v d   @:             @:    25  @:diag@:(v,n)}
34706 @r{    v m@:      v e   @:             @:     2  @:vexp@:(v,m)}
34707 @r{  v m f@:    H v e   @:             @:     2  @:vexp@:(v,m,f)}
34708 @r{    v a@:      v f   @:             @:    26  @:find@:(v,a,n)}
34709 @r{      v@:      v h   @:             @:     1  @:head@:(v)}
34710 @r{      v@:    I v h   @:             @:     1  @:tail@:(v)}
34711 @r{      v@:    H v h   @:             @:     1  @:rhead@:(v)}
34712 @r{      v@:  I H v h   @:             @:     1  @:rtail@:(v)}
34713 @r{       @:      v i   @:n            @:    31  @:idn@:(1,n)}
34714 @r{       @:      v i   @:0            @:    31  @:idn@:(1)}
34715 @r{    h t@:      v k   @:             @:     2  @:cons@:(h,t)}
34716 @r{    h t@:    H v k   @:             @:     2  @:rcons@:(h,t)}
34717 @r{      v@:      v l   @:             @:     1  @:vlen@:(v)}
34718 @r{      v@:    H v l   @:             @:     1  @:mdims@:(v)}
34719 @r{    v m@:      v m   @:             @:     2  @:vmask@:(v,m)}
34720 @r{      v@:      v n   @:             @:     1  @:rnorm@:(v)}
34721 @r{  a b c@:      v p   @:             @:    24  @:calc-pack@:}
34722 @r{      v@:      v r   @:n >0         @: 21,31  @:mrow@:(v,n)}
34723 @r{      v@:      v r   @:n <0         @:    31  @:mrrow@:(v,-n)}
34724 @r{      m@:      v r   @:0            @:    31  @:getdiag@:(m)}
34725 @r{  v i j@:      v s   @:             @:        @:subvec@:(v,i,j)}
34726 @r{  v i j@:    I v s   @:             @:        @:rsubvec@:(v,i,j)}
34727 @r{      m@:      v t   @:             @:     1  @:trn@:(m)}
34728 @r{      v@:      v u   @:             @:    24  @:calc-unpack@:}
34729 @r{      v@:      v v   @:             @:     1  @:rev@:(v)}
34730 @r{       @:      v x   @:n            @:    31  @:index@:(n)}
34731 @r{  n s i@:  C-u v x   @:             @:        @:index@:(n,s,i)}
34733 @c 
34734 @r{      v@:      V A   @:op           @:    22  @:apply@:(op,v)}
34735 @r{  v1 v2@:      V C   @:             @:     2  @:cross@:(v1,v2)}
34736 @r{      m@:      V D   @:             @:     1  @:det@:(m)}
34737 @r{      s@:      V E   @:             @:     1  @:venum@:(s)}
34738 @r{      s@:      V F   @:             @:     1  @:vfloor@:(s)}
34739 @r{      v@:      V G   @:             @:        @:grade@:(v)}
34740 @r{      v@:    I V G   @:             @:        @:rgrade@:(v)}
34741 @r{      v@:      V H   @:n            @:    31  @:histogram@:(v,n)}
34742 @r{    v w@:    H V H   @:n            @:    31  @:histogram@:(v,w,n)}
34743 @r{  v1 v2@:      V I   @:mop aop      @:    22  @:inner@:(mop,aop,v1,v2)}
34744 @r{      m@:      V J   @:             @:     1  @:ctrn@:(m)}
34745 @r{      m@:      V L   @:             @:     1  @:lud@:(m)}
34746 @r{      v@:      V M   @:op           @: 22,23  @:map@:(op,v)}
34747 @r{      v@:      V N   @:             @:     1  @:cnorm@:(v)}
34748 @r{  v1 v2@:      V O   @:op           @:    22  @:outer@:(op,v1,v2)}
34749 @r{      v@:      V R   @:op           @: 22,23  @:reduce@:(op,v)}
34750 @r{      v@:    I V R   @:op           @: 22,23  @:rreduce@:(op,v)}
34751 @r{    a n@:    H V R   @:op           @:    22  @:nest@:(op,a,n)}
34752 @r{      a@:  I H V R   @:op           @:    22  @:fixp@:(op,a)}
34753 @r{      v@:      V S   @:             @:        @:sort@:(v)}
34754 @r{      v@:    I V S   @:             @:        @:rsort@:(v)}
34755 @r{      m@:      V T   @:             @:     1  @:tr@:(m)}
34756 @r{      v@:      V U   @:op           @:    22  @:accum@:(op,v)}
34757 @r{      v@:    I V U   @:op           @:    22  @:raccum@:(op,v)}
34758 @r{    a n@:    H V U   @:op           @:    22  @:anest@:(op,a,n)}
34759 @r{      a@:  I H V U   @:op           @:    22  @:afixp@:(op,a)}
34760 @r{    s t@:      V V   @:             @:     2  @:vunion@:(s,t)}
34761 @r{    s t@:      V X   @:             @:     2  @:vxor@:(s,t)}
34763 @c 
34764 @r{       @:      Y     @:             @:        @:@:user commands}
34766 @c 
34767 @r{       @:      z     @:             @:        @:@:user commands}
34769 @c 
34770 @r{      c@:      Z [   @:             @:    45  @:calc-kbd-if@:}
34771 @r{      c@:      Z |   @:             @:    45  @:calc-kbd-else-if@:}
34772 @r{       @:      Z :   @:             @:        @:calc-kbd-else@:}
34773 @r{       @:      Z ]   @:             @:        @:calc-kbd-end-if@:}
34775 @c 
34776 @r{       @:      Z @{   @:             @:     4  @:calc-kbd-loop@:}
34777 @r{      c@:      Z /   @:             @:    45  @:calc-kbd-break@:}
34778 @r{       @:      Z @}   @:             @:        @:calc-kbd-end-loop@:}
34779 @r{      n@:      Z <   @:             @:        @:calc-kbd-repeat@:}
34780 @r{       @:      Z >   @:             @:        @:calc-kbd-end-repeat@:}
34781 @r{    n m@:      Z (   @:             @:        @:calc-kbd-for@:}
34782 @r{      s@:      Z )   @:             @:        @:calc-kbd-end-for@:}
34784 @c 
34785 @r{       @:      Z C-g @:             @:        @:@:cancel if/loop command}
34787 @c 
34788 @r{       @:      Z `   @:             @:        @:calc-kbd-push@:}
34789 @r{       @:      Z '   @:             @:        @:calc-kbd-pop@:}
34790 @r{      a@:      Z =   @:message      @:    28  @:calc-kbd-report@:}
34791 @r{       @:      Z #   @:prompt       @:        @:calc-kbd-query@:}
34793 @c 
34794 @r{   comp@:      Z C   @:func, args   @:    50  @:calc-user-define-composition@:}
34795 @r{       @:      Z D   @:key, command @:        @:calc-user-define@:}
34796 @r{       @:      Z E   @:key, editing @:    30  @:calc-user-define-edit@:}
34797 @r{   defn@:      Z F   @:k, c, f, a, n@:    28  @:calc-user-define-formula@:}
34798 @r{       @:      Z G   @:key          @:        @:calc-get-user-defn@:}
34799 @r{       @:      Z I   @:             @:        @:calc-user-define-invocation@:}
34800 @r{       @:      Z K   @:key, command @:        @:calc-user-define-kbd-macro@:}
34801 @r{       @:      Z P   @:key          @:        @:calc-user-define-permanent@:}
34802 @r{       @:      Z S   @:             @:    30  @:calc-edit-user-syntax@:}
34803 @r{       @:      Z T   @:             @:    12  @:calc-timing@:}
34804 @r{       @:      Z U   @:key          @:        @:calc-user-undefine@:}
34806 @end format
34808 @noindent
34809 NOTES
34811 @enumerate
34812 @c 1
34813 @item
34814 Positive prefix arguments apply to @cite{n} stack entries.
34815 Negative prefix arguments apply to the @cite{-n}th stack entry.
34816 A prefix of zero applies to the entire stack.  (For @key{LFD} and
34817 @kbd{M-DEL}, the meaning of the sign is reversed.)
34819 @c 2
34820 @item
34821 Positive prefix arguments apply to @cite{n} stack entries.
34822 Negative prefix arguments apply to the top stack entry
34823 and the next @cite{-n} stack entries.
34825 @c 3
34826 @item
34827 Positive prefix arguments rotate top @cite{n} stack entries by one.
34828 Negative prefix arguments rotate the entire stack by @cite{-n}.
34829 A prefix of zero reverses the entire stack.
34831 @c 4
34832 @item
34833 Prefix argument specifies a repeat count or distance.
34835 @c 5
34836 @item
34837 Positive prefix arguments specify a precision @cite{p}.
34838 Negative prefix arguments reduce the current precision by @cite{-p}.
34840 @c 6
34841 @item
34842 A prefix argument is interpreted as an additional step-size parameter.
34843 A plain @kbd{C-u} prefix means to prompt for the step size.
34845 @c 7
34846 @item
34847 A prefix argument specifies simplification level and depth.
34848 1=Default, 2=like @kbd{a s}, 3=like @kbd{a e}.
34850 @c 8
34851 @item
34852 A negative prefix operates only on the top level of the input formula.
34854 @c 9
34855 @item
34856 Positive prefix arguments specify a word size of @cite{w} bits, unsigned.
34857 Negative prefix arguments specify a word size of @cite{w} bits, signed.
34859 @c 10
34860 @item
34861 Prefix arguments specify the shift amount @cite{n}.  The @cite{w} argument
34862 cannot be specified in the keyboard version of this command.
34864 @c 11
34865 @item
34866 From the keyboard, @cite{d} is omitted and defaults to zero.
34868 @c 12
34869 @item
34870 Mode is toggled; a positive prefix always sets the mode, and a negative
34871 prefix always clears the mode.
34873 @c 13
34874 @item
34875 Some prefix argument values provide special variations of the mode.
34877 @c 14
34878 @item
34879 A prefix argument, if any, is used for @cite{m} instead of taking
34880 @cite{m} from the stack.  @cite{M} may take any of these values:
34881 @iftex
34882 {@advance@tableindent10pt
34883 @end iftex
34884 @table @asis
34885 @item Integer
34886 Random integer in the interval @cite{[0 .. m)}.
34887 @item Float
34888 Random floating-point number in the interval @cite{[0 .. m)}.
34889 @item 0.0
34890 Gaussian with mean 1 and standard deviation 0.
34891 @item Error form
34892 Gaussian with specified mean and standard deviation.
34893 @item Interval
34894 Random integer or floating-point number in that interval.
34895 @item Vector
34896 Random element from the vector.
34897 @end table
34898 @iftex
34900 @end iftex
34902 @c 15
34903 @item
34904 A prefix argument from 1 to 6 specifies number of date components
34905 to remove from the stack.  @xref{Date Conversions}.
34907 @c 16
34908 @item
34909 A prefix argument specifies a time zone; @kbd{C-u} says to take the
34910 time zone number or name from the top of the stack.  @xref{Time Zones}.
34912 @c 17
34913 @item
34914 A prefix argument specifies a day number (0-6, 0-31, or 0-366).
34916 @c 18
34917 @item
34918 If the input has no units, you will be prompted for both the old and
34919 the new units.
34921 @c 19
34922 @item
34923 With a prefix argument, collect that many stack entries to form the
34924 input data set.  Each entry may be a single value or a vector of values.
34926 @c 20
34927 @item
34928 With a prefix argument of 1, take a single @c{$N\times2$}
34929 @asis{Nx2} matrix from the
34930 stack instead of two separate data vectors.
34932 @c 21
34933 @item
34934 The row or column number @cite{n} may be given as a numeric prefix
34935 argument instead.  A plain @kbd{C-u} prefix says to take @cite{n}
34936 from the top of the stack.  If @cite{n} is a vector or interval,
34937 a subvector/submatrix of the input is created.
34939 @c 22
34940 @item
34941 The @cite{op} prompt can be answered with the key sequence for the
34942 desired function, or with @kbd{x} or @kbd{z} followed by a function name,
34943 or with @kbd{$} to take a formula from the top of the stack, or with
34944 @kbd{'} and a typed formula.  In the last two cases, the formula may
34945 be a nameless function like @samp{<#1+#2>} or @samp{<x, y : x+y>}, or it
34946 may include @kbd{$}, @kbd{$$}, etc. (where @kbd{$} will correspond to the
34947 last argument of the created function), or otherwise you will be
34948 prompted for an argument list.  The number of vectors popped from the
34949 stack by @kbd{V M} depends on the number of arguments of the function.
34951 @c 23
34952 @item
34953 One of the mapping direction keys @kbd{_} (horizontal, i.e., map
34954 by rows or reduce across), @kbd{:} (vertical, i.e., map by columns or
34955 reduce down), or @kbd{=} (map or reduce by rows) may be used before
34956 entering @cite{op}; these modify the function name by adding the letter
34957 @code{r} for ``rows,'' @code{c} for ``columns,'' @code{a} for ``across,''
34958 or @code{d} for ``down.''
34960 @c 24
34961 @item
34962 The prefix argument specifies a packing mode.  A nonnegative mode
34963 is the number of items (for @kbd{v p}) or the number of levels
34964 (for @kbd{v u}).  A negative mode is as described below.  With no
34965 prefix argument, the mode is taken from the top of the stack and
34966 may be an integer or a vector of integers.
34967 @iftex
34968 {@advance@tableindent-20pt
34969 @end iftex
34970 @table @cite
34971 @item -1
34972 (@var{2})  Rectangular complex number.
34973 @item -2
34974 (@var{2})  Polar complex number.
34975 @item -3
34976 (@var{3})  HMS form.
34977 @item -4
34978 (@var{2})  Error form.
34979 @item -5
34980 (@var{2})  Modulo form.
34981 @item -6
34982 (@var{2})  Closed interval.
34983 @item -7
34984 (@var{2})  Closed .. open interval.
34985 @item -8
34986 (@var{2})  Open .. closed interval.
34987 @item -9
34988 (@var{2})  Open interval.
34989 @item -10
34990 (@var{2})  Fraction.
34991 @item -11
34992 (@var{2})  Float with integer mantissa.
34993 @item -12
34994 (@var{2})  Float with mantissa in @cite{[1 .. 10)}.
34995 @item -13
34996 (@var{1})  Date form (using date numbers).
34997 @item -14
34998 (@var{3})  Date form (using year, month, day).
34999 @item -15
35000 (@var{6})  Date form (using year, month, day, hour, minute, second).
35001 @end table
35002 @iftex
35004 @end iftex
35006 @c 25
35007 @item
35008 A prefix argument specifies the size @cite{n} of the matrix.  With no
35009 prefix argument, @cite{n} is omitted and the size is inferred from
35010 the input vector.
35012 @c 26
35013 @item
35014 The prefix argument specifies the starting position @cite{n} (default 1).
35016 @c 27
35017 @item
35018 Cursor position within stack buffer affects this command.
35020 @c 28
35021 @item
35022 Arguments are not actually removed from the stack by this command.
35024 @c 29
35025 @item
35026 Variable name may be a single digit or a full name.
35028 @c 30
35029 @item
35030 Editing occurs in a separate buffer.  Press @kbd{M-# M-#} (or @kbd{C-c C-c},
35031 @key{LFD}, or in some cases @key{RET}) to finish the edit, or press
35032 @kbd{M-# x} to cancel the edit.  The @key{LFD} key prevents evaluation
35033 of the result of the edit.
35035 @c 31
35036 @item
35037 The number prompted for can also be provided as a prefix argument.
35039 @c 32
35040 @item
35041 Press this key a second time to cancel the prefix.
35043 @c 33
35044 @item
35045 With a negative prefix, deactivate all formulas.  With a positive
35046 prefix, deactivate and then reactivate from scratch.
35048 @c 34
35049 @item
35050 Default is to scan for nearest formula delimiter symbols.  With a
35051 prefix of zero, formula is delimited by mark and point.  With a
35052 non-zero prefix, formula is delimited by scanning forward or
35053 backward by that many lines.
35055 @c 35
35056 @item
35057 Parse the region between point and mark as a vector.  A nonzero prefix
35058 parses @var{n} lines before or after point as a vector.  A zero prefix
35059 parses the current line as a vector.  A @kbd{C-u} prefix parses the
35060 region between point and mark as a single formula.
35062 @c 36
35063 @item
35064 Parse the rectangle defined by point and mark as a matrix.  A positive
35065 prefix @var{n} divides the rectangle into columns of width @var{n}.
35066 A zero or @kbd{C-u} prefix parses each line as one formula.  A negative
35067 prefix suppresses special treatment of bracketed portions of a line.
35069 @c 37
35070 @item
35071 A numeric prefix causes the current language mode to be ignored.
35073 @c 38
35074 @item
35075 Responding to a prompt with a blank line answers that and all
35076 later prompts by popping additional stack entries.
35078 @c 39
35079 @item
35080 Answer for @cite{v} may also be of the form @cite{v = v_0} or
35081 @cite{v - v_0}.
35083 @c 40
35084 @item
35085 With a positive prefix argument, stack contains many @cite{y}'s and one
35086 common @cite{x}.  With a zero prefix, stack contains a vector of
35087 @cite{y}s and a common @cite{x}.  With a negative prefix, stack
35088 contains many @cite{[x,y]} vectors.  (For 3D plots, substitute
35089 @cite{z} for @cite{y} and @cite{x,y} for @cite{x}.)
35091 @c 41
35092 @item
35093 With any prefix argument, all curves in the graph are deleted.
35095 @c 42
35096 @item
35097 With a positive prefix, refines an existing plot with more data points.
35098 With a negative prefix, forces recomputation of the plot data.
35100 @c 43
35101 @item
35102 With any prefix argument, set the default value instead of the
35103 value for this graph.
35105 @c 44
35106 @item
35107 With a negative prefix argument, set the value for the printer.
35109 @c 45
35110 @item
35111 Condition is considered ``true'' if it is a nonzero real or complex
35112 number, or a formula whose value is known to be nonzero; it is ``false''
35113 otherwise.
35115 @c 46
35116 @item
35117 Several formulas separated by commas are pushed as multiple stack
35118 entries.  Trailing @kbd{)}, @kbd{]}, @kbd{@}}, @kbd{>}, and @kbd{"}
35119 delimiters may be omitted.  The notation @kbd{$$$} refers to the value
35120 in stack level three, and causes the formula to replace the top three
35121 stack levels.  The notation @kbd{$3} refers to stack level three without
35122 causing that value to be removed from the stack.  Use @key{LFD} in place
35123 of @key{RET} to prevent evaluation; use @kbd{M-=} in place of @key{RET}
35124 to evaluate variables.@refill
35126 @c 47
35127 @item
35128 The variable is replaced by the formula shown on the right.  The
35129 Inverse flag reverses the order of the operands, e.g., @kbd{I s - x}
35130 assigns @c{$x \coloneq a-x$}
35131 @cite{x := a-x}.
35133 @c 48
35134 @item
35135 Press @kbd{?} repeatedly to see how to choose a model.  Answer the
35136 variables prompt with @cite{iv} or @cite{iv;pv} to specify
35137 independent and parameter variables.  A positive prefix argument
35138 takes @i{N+1} vectors from the stack; a zero prefix takes a matrix
35139 and a vector from the stack.
35141 @c 49
35142 @item
35143 With a plain @kbd{C-u} prefix, replace the current region of the
35144 destination buffer with the yanked text instead of inserting.
35146 @c 50
35147 @item
35148 All stack entries are reformatted; the @kbd{H} prefix inhibits this.
35149 The @kbd{I} prefix sets the mode temporarily, redraws the top stack
35150 entry, then restores the original setting of the mode.
35152 @c 51
35153 @item
35154 A negative prefix sets the default 3D resolution instead of the
35155 default 2D resolution.
35157 @c 52
35158 @item
35159 This grabs a vector of the form [@var{prec}, @var{wsize}, @var{ssize},
35160 @var{radix}, @var{flfmt}, @var{ang}, @var{frac}, @var{symb}, @var{polar},
35161 @var{matrix}, @var{simp}, @var{inf}].  A prefix argument from 1 to 12
35162 grabs the @var{n}th mode value only.
35163 @end enumerate
35165 @iftex
35166 (Space is provided below for you to keep your own written notes.)
35167 @page
35168 @endgroup
35169 @end iftex
35172 @c [end-summary]
35174 @node Key Index, Command Index, Summary, Top
35175 @unnumbered Index of Key Sequences
35177 @printindex ky
35179 @node Command Index, Function Index, Key Index, Top
35180 @unnumbered Index of Calculator Commands
35182 Since all Calculator commands begin with the prefix @samp{calc-}, the
35183 @kbd{x} key has been provided as a variant of @kbd{M-x} which automatically
35184 types @samp{calc-} for you.  Thus, @kbd{x last-args} is short for
35185 @kbd{M-x calc-last-args}.
35187 @printindex pg
35189 @node Function Index, Concept Index, Command Index, Top
35190 @unnumbered Index of Algebraic Functions
35192 This is a list of built-in functions and operators usable in algebraic
35193 expressions.  Their full Lisp names are derived by adding the prefix
35194 @samp{calcFunc-}, as in @code{calcFunc-sqrt}.
35195 @iftex
35196 All functions except those noted with ``*'' have corresponding
35197 Calc keystrokes and can also be found in the Calc Summary.
35198 @end iftex
35200 @printindex tp
35202 @node Concept Index, Variable Index, Function Index, Top
35203 @unnumbered Concept Index
35205 @printindex cp
35207 @node Variable Index, Lisp Function Index, Concept Index, Top
35208 @unnumbered Index of Variables
35210 The variables in this list that do not contain dashes are accessible
35211 as Calc variables.  Add a @samp{var-} prefix to get the name of the
35212 corresponding Lisp variable.
35214 The remaining variables are Lisp variables suitable for @code{setq}ing
35215 in your @file{.emacs} file.
35217 @printindex vr
35219 @node Lisp Function Index, , Variable Index, Top
35220 @unnumbered Index of Lisp Math Functions
35222 The following functions are meant to be used with @code{defmath}, not
35223 @code{defun} definitions.  For names that do not start with @samp{calc-},
35224 the corresponding full Lisp name is derived by adding a prefix of
35225 @samp{math-}.
35227 @printindex fn
35229 @summarycontents
35231 @c [end]
35233 @contents
35234 @bye